]> git.bitcoin.ninja Git - rust-lightning/blob - src/ln/channelmanager.rs
Handle monitor update failures in msg-recv functions
[rust-lightning] / src / ln / channelmanager.rs
1 //! The top-level channel management and payment tracking stuff lives here.
2 //!
3 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
4 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
5 //! upon reconnect to the relevant peer(s).
6 //!
7 //! It does not manage routing logic (see ln::router for that) nor does it manage constructing
8 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
9 //! imply it needs to fail HTLCs/payments/channels it manages).
10
11 use bitcoin::blockdata::block::BlockHeader;
12 use bitcoin::blockdata::transaction::Transaction;
13 use bitcoin::blockdata::constants::genesis_block;
14 use bitcoin::network::constants::Network;
15 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
16
17 use secp256k1::key::{SecretKey,PublicKey};
18 use secp256k1::{Secp256k1,Message};
19 use secp256k1::ecdh::SharedSecret;
20 use secp256k1;
21
22 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
23 use chain::transaction::OutPoint;
24 use ln::channel::{Channel, ChannelError};
25 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
26 use ln::router::{Route,RouteHop};
27 use ln::msgs;
28 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
29 use chain::keysinterface::KeysInterface;
30 use util::config::UserConfig;
31 use util::{byte_utils, events, internal_traits, rng};
32 use util::sha2::Sha256;
33 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
34 use util::chacha20poly1305rfc::ChaCha20;
35 use util::logger::Logger;
36 use util::errors::APIError;
37
38 use crypto;
39 use crypto::mac::{Mac,MacResult};
40 use crypto::hmac::Hmac;
41 use crypto::digest::Digest;
42 use crypto::symmetriccipher::SynchronousStreamCipher;
43
44 use std::{cmp, ptr, mem};
45 use std::collections::{HashMap, hash_map, HashSet};
46 use std::io::Cursor;
47 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
48 use std::sync::atomic::{AtomicUsize, Ordering};
49 use std::time::{Instant,Duration};
50
51 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
52 ///
53 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
54 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
55 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
56 ///
57 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
58 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
59 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
60 /// the HTLC backwards along the relevant path).
61 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
62 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
63 mod channel_held_info {
64         use ln::msgs;
65         use ln::router::Route;
66         use secp256k1::key::SecretKey;
67
68         /// Stores the info we will need to send when we want to forward an HTLC onwards
69         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
70         pub struct PendingForwardHTLCInfo {
71                 pub(super) onion_packet: Option<msgs::OnionPacket>,
72                 pub(super) incoming_shared_secret: [u8; 32],
73                 pub(super) payment_hash: [u8; 32],
74                 pub(super) short_channel_id: u64,
75                 pub(super) amt_to_forward: u64,
76                 pub(super) outgoing_cltv_value: u32,
77         }
78
79         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
80         pub enum HTLCFailureMsg {
81                 Relay(msgs::UpdateFailHTLC),
82                 Malformed(msgs::UpdateFailMalformedHTLC),
83         }
84
85         /// Stores whether we can't forward an HTLC or relevant forwarding info
86         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
87         pub enum PendingHTLCStatus {
88                 Forward(PendingForwardHTLCInfo),
89                 Fail(HTLCFailureMsg),
90         }
91
92         /// Tracks the inbound corresponding to an outbound HTLC
93         #[derive(Clone)]
94         pub struct HTLCPreviousHopData {
95                 pub(super) short_channel_id: u64,
96                 pub(super) htlc_id: u64,
97                 pub(super) incoming_packet_shared_secret: [u8; 32],
98         }
99
100         /// Tracks the inbound corresponding to an outbound HTLC
101         #[derive(Clone)]
102         pub enum HTLCSource {
103                 PreviousHopData(HTLCPreviousHopData),
104                 OutboundRoute {
105                         route: Route,
106                         session_priv: SecretKey,
107                         /// Technically we can recalculate this from the route, but we cache it here to avoid
108                         /// doing a double-pass on route when we get a failure back
109                         first_hop_htlc_msat: u64,
110                 },
111         }
112         #[cfg(test)]
113         impl HTLCSource {
114                 pub fn dummy() -> Self {
115                         HTLCSource::OutboundRoute {
116                                 route: Route { hops: Vec::new() },
117                                 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
118                                 first_hop_htlc_msat: 0,
119                         }
120                 }
121         }
122
123         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
124         pub(crate) enum HTLCFailReason {
125                 ErrorPacket {
126                         err: msgs::OnionErrorPacket,
127                 },
128                 Reason {
129                         failure_code: u16,
130                         data: Vec<u8>,
131                 }
132         }
133 }
134 pub(super) use self::channel_held_info::*;
135
136 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, [u8; 32])>);
137
138 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
139 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
140 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
141 /// channel_state lock. We then return the set of things that need to be done outside the lock in
142 /// this struct and call handle_error!() on it.
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 /// Pass to fail_htlc_backwwards to indicate the reason to fail the payment
206 /// after a PaymentReceived event.
207 #[derive(PartialEq)]
208 pub enum PaymentFailReason {
209         /// Indicate the preimage for payment_hash is not known after a PaymentReceived event
210         PreimageUnknown,
211         /// Indicate the payment amount is incorrect ( received is < expected or > 2*expected ) after a PaymentReceived event
212         AmountMismatch,
213 }
214
215 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
216 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
217 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
218 /// probably increase this significantly.
219 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
220
221 struct HTLCForwardInfo {
222         prev_short_channel_id: u64,
223         prev_htlc_id: u64,
224         forward_info: PendingForwardHTLCInfo,
225 }
226
227 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
228 /// be sent in the order they appear in the return value, however sometimes the order needs to be
229 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
230 /// they were originally sent). In those cases, this enum is also returned.
231 #[derive(Clone, PartialEq)]
232 pub(super) enum RAACommitmentOrder {
233         /// Send the CommitmentUpdate messages first
234         CommitmentFirst,
235         /// Send the RevokeAndACK message first
236         RevokeAndACKFirst,
237 }
238
239 struct ChannelHolder {
240         by_id: HashMap<[u8; 32], Channel>,
241         short_to_id: HashMap<u64, [u8; 32]>,
242         next_forward: Instant,
243         /// short channel id -> forward infos. Key of 0 means payments received
244         /// Note that while this is held in the same mutex as the channels themselves, no consistency
245         /// guarantees are made about there existing a channel with the short id here, nor the short
246         /// ids in the PendingForwardHTLCInfo!
247         forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
248         /// Note that while this is held in the same mutex as the channels themselves, no consistency
249         /// guarantees are made about the channels given here actually existing anymore by the time you
250         /// go to read them!
251         claimable_htlcs: HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
252         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
253         /// for broadcast messages, where ordering isn't as strict).
254         pending_msg_events: Vec<events::MessageSendEvent>,
255 }
256 struct MutChannelHolder<'a> {
257         by_id: &'a mut HashMap<[u8; 32], Channel>,
258         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
259         next_forward: &'a mut Instant,
260         forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
261         claimable_htlcs: &'a mut HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
262         pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
263 }
264 impl ChannelHolder {
265         fn borrow_parts(&mut self) -> MutChannelHolder {
266                 MutChannelHolder {
267                         by_id: &mut self.by_id,
268                         short_to_id: &mut self.short_to_id,
269                         next_forward: &mut self.next_forward,
270                         forward_htlcs: &mut self.forward_htlcs,
271                         claimable_htlcs: &mut self.claimable_htlcs,
272                         pending_msg_events: &mut self.pending_msg_events,
273                 }
274         }
275 }
276
277 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
278 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
279
280 /// Manager which keeps track of a number of channels and sends messages to the appropriate
281 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
282 ///
283 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
284 /// to individual Channels.
285 ///
286 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
287 /// all peers during write/read (though does not modify this instance, only the instance being
288 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
289 /// called funding_transaction_generated for outbound channels).
290 ///
291 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
292 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
293 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
294 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
295 /// the serialization process). If the deserialized version is out-of-date compared to the
296 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
297 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
298 ///
299 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
300 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
301 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
302 /// block_connected() to step towards your best block) upon deserialization before using the
303 /// object!
304 pub struct ChannelManager {
305         default_configuration: UserConfig,
306         genesis_hash: Sha256dHash,
307         fee_estimator: Arc<FeeEstimator>,
308         monitor: Arc<ManyChannelMonitor>,
309         chain_monitor: Arc<ChainWatchInterface>,
310         tx_broadcaster: Arc<BroadcasterInterface>,
311
312         latest_block_height: AtomicUsize,
313         last_block_hash: Mutex<Sha256dHash>,
314         secp_ctx: Secp256k1<secp256k1::All>,
315
316         channel_state: Mutex<ChannelHolder>,
317         our_network_key: SecretKey,
318
319         pending_events: Mutex<Vec<events::Event>>,
320         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
321         /// Essentially just when we're serializing ourselves out.
322         /// Taken first everywhere where we are making changes before any other locks.
323         total_consistency_lock: RwLock<()>,
324
325         keys_manager: Arc<KeysInterface>,
326
327         logger: Arc<Logger>,
328 }
329
330 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
331 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
332 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
333 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
334 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
335 const CLTV_EXPIRY_DELTA: u16 = 6 * 24 * 2; //TODO?
336 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
337
338 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS, ie that
339 // if the next-hop peer fails the HTLC within HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have
340 // HTLC_FAIL_TIMEOUT_BLOCKS left to fail it backwards ourselves before hitting the
341 // CLTV_CLAIM_BUFFER point and failing the channel on-chain to time out the HTLC.
342 #[deny(const_err)]
343 #[allow(dead_code)]
344 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER;
345
346 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
347 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
348 #[deny(const_err)]
349 #[allow(dead_code)]
350 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
351
352 macro_rules! secp_call {
353         ( $res: expr, $err: expr ) => {
354                 match $res {
355                         Ok(key) => key,
356                         Err(_) => return Err($err),
357                 }
358         };
359 }
360
361 struct OnionKeys {
362         #[cfg(test)]
363         shared_secret: SharedSecret,
364         #[cfg(test)]
365         blinding_factor: [u8; 32],
366         ephemeral_pubkey: PublicKey,
367         rho: [u8; 32],
368         mu: [u8; 32],
369 }
370
371 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
372 pub struct ChannelDetails {
373         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
374         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
375         /// Note that this means this value is *not* persistent - it can change once during the
376         /// lifetime of the channel.
377         pub channel_id: [u8; 32],
378         /// The position of the funding transaction in the chain. None if the funding transaction has
379         /// not yet been confirmed and the channel fully opened.
380         pub short_channel_id: Option<u64>,
381         /// The node_id of our counterparty
382         pub remote_network_id: PublicKey,
383         /// The value, in satoshis, of this channel as appears in the funding output
384         pub channel_value_satoshis: u64,
385         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
386         pub user_id: u64,
387 }
388
389 macro_rules! handle_error {
390         ($self: ident, $internal: expr, $their_node_id: expr) => {
391                 match $internal {
392                         Ok(msg) => Ok(msg),
393                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
394                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
395                                         $self.finish_force_close_channel(shutdown_res);
396                                         if let Some(update) = update_option {
397                                                 let mut channel_state = $self.channel_state.lock().unwrap();
398                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
399                                                         msg: update
400                                                 });
401                                         }
402                                 }
403                                 Err(err)
404                         },
405                 }
406         }
407 }
408
409 macro_rules! break_chan_entry {
410         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
411                 match $res {
412                         Ok(res) => res,
413                         Err(ChannelError::Ignore(msg)) => {
414                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
415                         },
416                         Err(ChannelError::Close(msg)) => {
417                                 let (channel_id, mut chan) = $entry.remove_entry();
418                                 if let Some(short_id) = chan.get_short_channel_id() {
419                                         $channel_state.short_to_id.remove(&short_id);
420                                 }
421                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
422                         },
423                 }
424         }
425 }
426
427 macro_rules! try_chan_entry {
428         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
429                 match $res {
430                         Ok(res) => res,
431                         Err(ChannelError::Ignore(msg)) => {
432                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
433                         },
434                         Err(ChannelError::Close(msg)) => {
435                                 let (channel_id, mut chan) = $entry.remove_entry();
436                                 if let Some(short_id) = chan.get_short_channel_id() {
437                                         $channel_state.short_to_id.remove(&short_id);
438                                 }
439                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
440                         },
441                 }
442         }
443 }
444
445 macro_rules! return_monitor_err {
446         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
447                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
448         };
449         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
450                 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
451                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
452         };
453         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
454                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
455         };
456         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
457                 match $err {
458                         ChannelMonitorUpdateErr::PermanentFailure => {
459                                 let (channel_id, mut chan) = $entry.remove_entry();
460                                 if let Some(short_id) = chan.get_short_channel_id() {
461                                         $channel_state.short_to_id.remove(&short_id);
462                                 }
463                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
464                                 // chain in a confused state! We need to move them into the ChannelMonitor which
465                                 // will be responsible for failing backwards once things confirm on-chain.
466                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
467                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
468                                 // us bother trying to claim it just to forward on to another peer. If we're
469                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
470                                 // given up the preimage yet, so might as well just wait until the payment is
471                                 // retried, avoiding the on-chain fees.
472                                 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
473                         },
474                         ChannelMonitorUpdateErr::TemporaryFailure => {
475                                 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
476                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
477                         },
478                 }
479         }
480 }
481
482 // Does not break in case of TemporaryFailure!
483 macro_rules! maybe_break_monitor_err {
484         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
485                 match $err {
486                         ChannelMonitorUpdateErr::PermanentFailure => {
487                                 let (channel_id, mut chan) = $entry.remove_entry();
488                                 if let Some(short_id) = chan.get_short_channel_id() {
489                                         $channel_state.short_to_id.remove(&short_id);
490                                 }
491                                 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
492                         },
493                         ChannelMonitorUpdateErr::TemporaryFailure => {
494                                 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
495                         },
496                 }
497         }
498 }
499
500 impl ChannelManager {
501         /// Constructs a new ChannelManager to hold several channels and route between them.
502         ///
503         /// This is the main "logic hub" for all channel-related actions, and implements
504         /// ChannelMessageHandler.
505         ///
506         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
507         ///
508         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
509         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> {
510                 let secp_ctx = Secp256k1::new();
511
512                 let res = Arc::new(ChannelManager {
513                         default_configuration: config.clone(),
514                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
515                         fee_estimator: feeest.clone(),
516                         monitor: monitor.clone(),
517                         chain_monitor,
518                         tx_broadcaster,
519
520                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
521                         last_block_hash: Mutex::new(Default::default()),
522                         secp_ctx,
523
524                         channel_state: Mutex::new(ChannelHolder{
525                                 by_id: HashMap::new(),
526                                 short_to_id: HashMap::new(),
527                                 next_forward: Instant::now(),
528                                 forward_htlcs: HashMap::new(),
529                                 claimable_htlcs: HashMap::new(),
530                                 pending_msg_events: Vec::new(),
531                         }),
532                         our_network_key: keys_manager.get_node_secret(),
533
534                         pending_events: Mutex::new(Vec::new()),
535                         total_consistency_lock: RwLock::new(()),
536
537                         keys_manager,
538
539                         logger,
540                 });
541                 let weak_res = Arc::downgrade(&res);
542                 res.chain_monitor.register_listener(weak_res);
543                 Ok(res)
544         }
545
546         /// Creates a new outbound channel to the given remote node and with the given value.
547         ///
548         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
549         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
550         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
551         /// may wish to avoid using 0 for user_id here.
552         ///
553         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
554         /// PeerManager::process_events afterwards.
555         ///
556         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
557         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
558         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
559                 if channel_value_satoshis < 1000 {
560                         return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
561                 }
562
563                 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)?;
564                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
565
566                 let _ = self.total_consistency_lock.read().unwrap();
567                 let mut channel_state = self.channel_state.lock().unwrap();
568                 match channel_state.by_id.entry(channel.channel_id()) {
569                         hash_map::Entry::Occupied(_) => {
570                                 if cfg!(feature = "fuzztarget") {
571                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
572                                 } else {
573                                         panic!("RNG is bad???");
574                                 }
575                         },
576                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
577                 }
578                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
579                         node_id: their_network_key,
580                         msg: res,
581                 });
582                 Ok(())
583         }
584
585         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
586         /// more information.
587         pub fn list_channels(&self) -> Vec<ChannelDetails> {
588                 let channel_state = self.channel_state.lock().unwrap();
589                 let mut res = Vec::with_capacity(channel_state.by_id.len());
590                 for (channel_id, channel) in channel_state.by_id.iter() {
591                         res.push(ChannelDetails {
592                                 channel_id: (*channel_id).clone(),
593                                 short_channel_id: channel.get_short_channel_id(),
594                                 remote_network_id: channel.get_their_node_id(),
595                                 channel_value_satoshis: channel.get_value_satoshis(),
596                                 user_id: channel.get_user_id(),
597                         });
598                 }
599                 res
600         }
601
602         /// Gets the list of usable channels, in random order. Useful as an argument to
603         /// Router::get_route to ensure non-announced channels are used.
604         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
605                 let channel_state = self.channel_state.lock().unwrap();
606                 let mut res = Vec::with_capacity(channel_state.by_id.len());
607                 for (channel_id, channel) in channel_state.by_id.iter() {
608                         // Note we use is_live here instead of usable which leads to somewhat confused
609                         // internal/external nomenclature, but that's ok cause that's probably what the user
610                         // really wanted anyway.
611                         if channel.is_live() {
612                                 res.push(ChannelDetails {
613                                         channel_id: (*channel_id).clone(),
614                                         short_channel_id: channel.get_short_channel_id(),
615                                         remote_network_id: channel.get_their_node_id(),
616                                         channel_value_satoshis: channel.get_value_satoshis(),
617                                         user_id: channel.get_user_id(),
618                                 });
619                         }
620                 }
621                 res
622         }
623
624         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
625         /// will be accepted on the given channel, and after additional timeout/the closing of all
626         /// pending HTLCs, the channel will be closed on chain.
627         ///
628         /// May generate a SendShutdown message event on success, which should be relayed.
629         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
630                 let _ = self.total_consistency_lock.read().unwrap();
631
632                 let (mut failed_htlcs, chan_option) = {
633                         let mut channel_state_lock = self.channel_state.lock().unwrap();
634                         let channel_state = channel_state_lock.borrow_parts();
635                         match channel_state.by_id.entry(channel_id.clone()) {
636                                 hash_map::Entry::Occupied(mut chan_entry) => {
637                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
638                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
639                                                 node_id: chan_entry.get().get_their_node_id(),
640                                                 msg: shutdown_msg
641                                         });
642                                         if chan_entry.get().is_shutdown() {
643                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
644                                                         channel_state.short_to_id.remove(&short_id);
645                                                 }
646                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
647                                         } else { (failed_htlcs, None) }
648                                 },
649                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
650                         }
651                 };
652                 for htlc_source in failed_htlcs.drain(..) {
653                         // unknown_next_peer...I dunno who that is anymore....
654                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
655                 }
656                 let chan_update = if let Some(chan) = chan_option {
657                         if let Ok(update) = self.get_channel_update(&chan) {
658                                 Some(update)
659                         } else { None }
660                 } else { None };
661
662                 if let Some(update) = chan_update {
663                         let mut channel_state = self.channel_state.lock().unwrap();
664                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
665                                 msg: update
666                         });
667                 }
668
669                 Ok(())
670         }
671
672         #[inline]
673         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
674                 let (local_txn, mut failed_htlcs) = shutdown_res;
675                 for htlc_source in failed_htlcs.drain(..) {
676                         // unknown_next_peer...I dunno who that is anymore....
677                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
678                 }
679                 for tx in local_txn {
680                         self.tx_broadcaster.broadcast_transaction(&tx);
681                 }
682                 //TODO: We need to have a way where outbound HTLC claims can result in us claiming the
683                 //now-on-chain HTLC output for ourselves (and, thereafter, passing the HTLC backwards).
684                 //TODO: We need to handle monitoring of pending offered HTLCs which just hit the chain and
685                 //may be claimed, resulting in us claiming the inbound HTLCs (and back-failing after
686                 //timeouts are hit and our claims confirm).
687                 //TODO: In any case, we need to make sure we remove any pending htlc tracking (via
688                 //fail_backwards or claim_funds) eventually for all HTLCs that were in the channel
689         }
690
691         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
692         /// the chain and rejecting new HTLCs on the given channel.
693         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
694                 let _ = self.total_consistency_lock.read().unwrap();
695
696                 let mut chan = {
697                         let mut channel_state_lock = self.channel_state.lock().unwrap();
698                         let channel_state = channel_state_lock.borrow_parts();
699                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
700                                 if let Some(short_id) = chan.get_short_channel_id() {
701                                         channel_state.short_to_id.remove(&short_id);
702                                 }
703                                 chan
704                         } else {
705                                 return;
706                         }
707                 };
708                 self.finish_force_close_channel(chan.force_shutdown());
709                 if let Ok(update) = self.get_channel_update(&chan) {
710                         let mut channel_state = self.channel_state.lock().unwrap();
711                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
712                                 msg: update
713                         });
714                 }
715         }
716
717         /// Force close all channels, immediately broadcasting the latest local commitment transaction
718         /// for each to the chain and rejecting new HTLCs on each.
719         pub fn force_close_all_channels(&self) {
720                 for chan in self.list_channels() {
721                         self.force_close_channel(&chan.channel_id);
722                 }
723         }
724
725         #[inline]
726         fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
727                 assert_eq!(shared_secret.len(), 32);
728                 ({
729                         let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
730                         hmac.input(&shared_secret[..]);
731                         let mut res = [0; 32];
732                         hmac.raw_result(&mut res);
733                         res
734                 },
735                 {
736                         let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
737                         hmac.input(&shared_secret[..]);
738                         let mut res = [0; 32];
739                         hmac.raw_result(&mut res);
740                         res
741                 })
742         }
743
744         #[inline]
745         fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
746                 assert_eq!(shared_secret.len(), 32);
747                 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
748                 hmac.input(&shared_secret[..]);
749                 let mut res = [0; 32];
750                 hmac.raw_result(&mut res);
751                 res
752         }
753
754         #[inline]
755         fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
756                 assert_eq!(shared_secret.len(), 32);
757                 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
758                 hmac.input(&shared_secret[..]);
759                 let mut res = [0; 32];
760                 hmac.raw_result(&mut res);
761                 res
762         }
763
764         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
765         #[inline]
766         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> {
767                 let mut blinded_priv = session_priv.clone();
768                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
769
770                 for hop in route.hops.iter() {
771                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
772
773                         let mut sha = Sha256::new();
774                         sha.input(&blinded_pub.serialize()[..]);
775                         sha.input(&shared_secret[..]);
776                         let mut blinding_factor = [0u8; 32];
777                         sha.result(&mut blinding_factor);
778
779                         let ephemeral_pubkey = blinded_pub;
780
781                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
782                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
783
784                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
785                 }
786
787                 Ok(())
788         }
789
790         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
791         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
792                 let mut res = Vec::with_capacity(route.hops.len());
793
794                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
795                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
796
797                         res.push(OnionKeys {
798                                 #[cfg(test)]
799                                 shared_secret,
800                                 #[cfg(test)]
801                                 blinding_factor: _blinding_factor,
802                                 ephemeral_pubkey,
803                                 rho,
804                                 mu,
805                         });
806                 })?;
807
808                 Ok(res)
809         }
810
811         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
812         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
813                 let mut cur_value_msat = 0u64;
814                 let mut cur_cltv = starting_htlc_offset;
815                 let mut last_short_channel_id = 0;
816                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
817                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
818                 unsafe { res.set_len(route.hops.len()); }
819
820                 for (idx, hop) in route.hops.iter().enumerate().rev() {
821                         // First hop gets special values so that it can check, on receipt, that everything is
822                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
823                         // the intended recipient).
824                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
825                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
826                         res[idx] = msgs::OnionHopData {
827                                 realm: 0,
828                                 data: msgs::OnionRealm0HopData {
829                                         short_channel_id: last_short_channel_id,
830                                         amt_to_forward: value_msat,
831                                         outgoing_cltv_value: cltv,
832                                 },
833                                 hmac: [0; 32],
834                         };
835                         cur_value_msat += hop.fee_msat;
836                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
837                                 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
838                         }
839                         cur_cltv += hop.cltv_expiry_delta as u32;
840                         if cur_cltv >= 500000000 {
841                                 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
842                         }
843                         last_short_channel_id = hop.short_channel_id;
844                 }
845                 Ok((res, cur_value_msat, cur_cltv))
846         }
847
848         #[inline]
849         fn shift_arr_right(arr: &mut [u8; 20*65]) {
850                 unsafe {
851                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
852                 }
853                 for i in 0..65 {
854                         arr[i] = 0;
855                 }
856         }
857
858         #[inline]
859         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
860                 assert_eq!(dst.len(), src.len());
861
862                 for i in 0..dst.len() {
863                         dst[i] ^= src[i];
864                 }
865         }
866
867         const ZERO:[u8; 21*65] = [0; 21*65];
868         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &[u8; 32]) -> msgs::OnionPacket {
869                 let mut buf = Vec::with_capacity(21*65);
870                 buf.resize(21*65, 0);
871
872                 let filler = {
873                         let iters = payloads.len() - 1;
874                         let end_len = iters * 65;
875                         let mut res = Vec::with_capacity(end_len);
876                         res.resize(end_len, 0);
877
878                         for (i, keys) in onion_keys.iter().enumerate() {
879                                 if i == payloads.len() - 1 { continue; }
880                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
881                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
882                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
883                         }
884                         res
885                 };
886
887                 let mut packet_data = [0; 20*65];
888                 let mut hmac_res = [0; 32];
889
890                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
891                         ChannelManager::shift_arr_right(&mut packet_data);
892                         payload.hmac = hmac_res;
893                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
894
895                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
896                         chacha.process(&packet_data, &mut buf[0..20*65]);
897                         packet_data[..].copy_from_slice(&buf[0..20*65]);
898
899                         if i == 0 {
900                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
901                         }
902
903                         let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
904                         hmac.input(&packet_data);
905                         hmac.input(&associated_data[..]);
906                         hmac.raw_result(&mut hmac_res);
907                 }
908
909                 msgs::OnionPacket{
910                         version: 0,
911                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
912                         hop_data: packet_data,
913                         hmac: hmac_res,
914                 }
915         }
916
917         /// Encrypts a failure packet. raw_packet can either be a
918         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
919         fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
920                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
921
922                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
923                 packet_crypted.resize(raw_packet.len(), 0);
924                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
925                 chacha.process(&raw_packet, &mut packet_crypted[..]);
926                 msgs::OnionErrorPacket {
927                         data: packet_crypted,
928                 }
929         }
930
931         fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
932                 assert_eq!(shared_secret.len(), 32);
933                 assert!(failure_data.len() <= 256 - 2);
934
935                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
936
937                 let failuremsg = {
938                         let mut res = Vec::with_capacity(2 + failure_data.len());
939                         res.push(((failure_type >> 8) & 0xff) as u8);
940                         res.push(((failure_type >> 0) & 0xff) as u8);
941                         res.extend_from_slice(&failure_data[..]);
942                         res
943                 };
944                 let pad = {
945                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
946                         res.resize(256 - 2 - failure_data.len(), 0);
947                         res
948                 };
949                 let mut packet = msgs::DecodedOnionErrorPacket {
950                         hmac: [0; 32],
951                         failuremsg: failuremsg,
952                         pad: pad,
953                 };
954
955                 let mut hmac = Hmac::new(Sha256::new(), &um);
956                 hmac.input(&packet.encode()[32..]);
957                 hmac.raw_result(&mut packet.hmac);
958
959                 packet
960         }
961
962         #[inline]
963         fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
964                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
965                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
966         }
967
968         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
969                 macro_rules! get_onion_hash {
970                         () => {
971                                 {
972                                         let mut sha = Sha256::new();
973                                         sha.input(&msg.onion_routing_packet.hop_data);
974                                         let mut onion_hash = [0; 32];
975                                         sha.result(&mut onion_hash);
976                                         onion_hash
977                                 }
978                         }
979                 }
980
981                 if let Err(_) = msg.onion_routing_packet.public_key {
982                         log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
983                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
984                                 channel_id: msg.channel_id,
985                                 htlc_id: msg.htlc_id,
986                                 sha256_of_onion: get_onion_hash!(),
987                                 failure_code: 0x8000 | 0x4000 | 6,
988                         })), self.channel_state.lock().unwrap());
989                 }
990
991                 let shared_secret = {
992                         let mut arr = [0; 32];
993                         arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
994                         arr
995                 };
996                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
997
998                 let mut channel_state = None;
999                 macro_rules! return_err {
1000                         ($msg: expr, $err_code: expr, $data: expr) => {
1001                                 {
1002                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
1003                                         if channel_state.is_none() {
1004                                                 channel_state = Some(self.channel_state.lock().unwrap());
1005                                         }
1006                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1007                                                 channel_id: msg.channel_id,
1008                                                 htlc_id: msg.htlc_id,
1009                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1010                                         })), channel_state.unwrap());
1011                                 }
1012                         }
1013                 }
1014
1015                 if msg.onion_routing_packet.version != 0 {
1016                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1017                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1018                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
1019                         //receiving node would have to brute force to figure out which version was put in the
1020                         //packet by the node that send us the message, in the case of hashing the hop_data, the
1021                         //node knows the HMAC matched, so they already know what is there...
1022                         return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
1023                 }
1024
1025                 let mut hmac = Hmac::new(Sha256::new(), &mu);
1026                 hmac.input(&msg.onion_routing_packet.hop_data);
1027                 hmac.input(&msg.payment_hash);
1028                 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
1029                         return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
1030                 }
1031
1032                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1033                 let next_hop_data = {
1034                         let mut decoded = [0; 65];
1035                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1036                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1037                                 Err(err) => {
1038                                         let error_code = match err {
1039                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1040                                                 _ => 0x2000 | 2, // Should never happen
1041                                         };
1042                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1043                                 },
1044                                 Ok(msg) => msg
1045                         }
1046                 };
1047
1048                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1049                                 // OUR PAYMENT!
1050                                 // final_expiry_too_soon
1051                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1052                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1053                                 }
1054                                 // final_incorrect_htlc_amount
1055                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1056                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1057                                 }
1058                                 // final_incorrect_cltv_expiry
1059                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1060                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1061                                 }
1062
1063                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1064                                 // message, however that would leak that we are the recipient of this payment, so
1065                                 // instead we stay symmetric with the forwarding case, only responding (after a
1066                                 // delay) once they've send us a commitment_signed!
1067
1068                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1069                                         onion_packet: None,
1070                                         payment_hash: msg.payment_hash.clone(),
1071                                         short_channel_id: 0,
1072                                         incoming_shared_secret: shared_secret,
1073                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1074                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1075                                 })
1076                         } else {
1077                                 let mut new_packet_data = [0; 20*65];
1078                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1079                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1080
1081                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1082
1083                                 let blinding_factor = {
1084                                         let mut sha = Sha256::new();
1085                                         sha.input(&new_pubkey.serialize()[..]);
1086                                         sha.input(&shared_secret);
1087                                         let mut res = [0u8; 32];
1088                                         sha.result(&mut res);
1089                                         match SecretKey::from_slice(&self.secp_ctx, &res) {
1090                                                 Err(_) => {
1091                                                         return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1092                                                 },
1093                                                 Ok(key) => key
1094                                         }
1095                                 };
1096
1097                                 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1098                                         return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1099                                 }
1100
1101                                 let outgoing_packet = msgs::OnionPacket {
1102                                         version: 0,
1103                                         public_key: Ok(new_pubkey),
1104                                         hop_data: new_packet_data,
1105                                         hmac: next_hop_data.hmac.clone(),
1106                                 };
1107
1108                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1109                                         onion_packet: Some(outgoing_packet),
1110                                         payment_hash: msg.payment_hash.clone(),
1111                                         short_channel_id: next_hop_data.data.short_channel_id,
1112                                         incoming_shared_secret: shared_secret,
1113                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1114                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1115                                 })
1116                         };
1117
1118                 channel_state = Some(self.channel_state.lock().unwrap());
1119                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1120                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1121                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1122                                 let forwarding_id = match id_option {
1123                                         None => { // unknown_next_peer
1124                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1125                                         },
1126                                         Some(id) => id.clone(),
1127                                 };
1128                                 if let Some((err, code, chan_update)) = loop {
1129                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1130
1131                                         // Note that we could technically not return an error yet here and just hope
1132                                         // that the connection is reestablished or monitor updated by the time we get
1133                                         // around to doing the actual forward, but better to fail early if we can and
1134                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1135                                         // on a small/per-node/per-channel scale.
1136                                         if !chan.is_live() { // channel_disabled
1137                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1138                                         }
1139                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1140                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1141                                         }
1142                                         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) });
1143                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1144                                                 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())));
1145                                         }
1146                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1147                                                 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())));
1148                                         }
1149                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1150                                         // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1151                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1152                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1153                                         }
1154                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1155                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1156                                         }
1157                                         break None;
1158                                 }
1159                                 {
1160                                         let mut res = Vec::with_capacity(8 + 128);
1161                                         if code == 0x1000 | 11 || code == 0x1000 | 12 {
1162                                                 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1163                                         }
1164                                         else if code == 0x1000 | 13 {
1165                                                 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1166                                         }
1167                                         if let Some(chan_update) = chan_update {
1168                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1169                                         }
1170                                         return_err!(err, code, &res[..]);
1171                                 }
1172                         }
1173                 }
1174
1175                 (pending_forward_info, channel_state.unwrap())
1176         }
1177
1178         /// only fails if the channel does not yet have an assigned short_id
1179         /// May be called with channel_state already locked!
1180         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1181                 let short_channel_id = match chan.get_short_channel_id() {
1182                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
1183                         Some(id) => id,
1184                 };
1185
1186                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1187
1188                 let unsigned = msgs::UnsignedChannelUpdate {
1189                         chain_hash: self.genesis_hash,
1190                         short_channel_id: short_channel_id,
1191                         timestamp: chan.get_channel_update_count(),
1192                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1193                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1194                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1195                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1196                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1197                         excess_data: Vec::new(),
1198                 };
1199
1200                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1201                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1202
1203                 Ok(msgs::ChannelUpdate {
1204                         signature: sig,
1205                         contents: unsigned
1206                 })
1207         }
1208
1209         /// Sends a payment along a given route.
1210         ///
1211         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1212         /// fields for more info.
1213         ///
1214         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1215         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1216         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1217         /// specified in the last hop in the route! Thus, you should probably do your own
1218         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1219         /// payment") and prevent double-sends yourself.
1220         ///
1221         /// May generate a SendHTLCs message event on success, which should be relayed.
1222         ///
1223         /// Raises APIError::RoutError when invalid route or forward parameter
1224         /// (cltv_delta, fee, node public key) is specified.
1225         /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1226         /// (including due to previous monitor update failure or new permanent monitor update failure).
1227         /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1228         /// relevant updates.
1229         ///
1230         /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1231         /// and you may wish to retry via a different route immediately.
1232         /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1233         /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1234         /// the payment via a different route unless you intend to pay twice!
1235         pub fn send_payment(&self, route: Route, payment_hash: [u8; 32]) -> Result<(), APIError> {
1236                 if route.hops.len() < 1 || route.hops.len() > 20 {
1237                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1238                 }
1239                 let our_node_id = self.get_our_node_id();
1240                 for (idx, hop) in route.hops.iter().enumerate() {
1241                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1242                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1243                         }
1244                 }
1245
1246                 let session_priv = self.keys_manager.get_session_key();
1247
1248                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1249
1250                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1251                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1252                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1253                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1254
1255                 let _ = self.total_consistency_lock.read().unwrap();
1256
1257                 let err: Result<(), _> = loop {
1258                         let mut channel_lock = self.channel_state.lock().unwrap();
1259
1260                         let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1261                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1262                                 Some(id) => id.clone(),
1263                         };
1264
1265                         let channel_state = channel_lock.borrow_parts();
1266                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1267                                 match {
1268                                         if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1269                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1270                                         }
1271                                         if !chan.get().is_live() {
1272                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1273                                         }
1274                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1275                                                 route: route.clone(),
1276                                                 session_priv: session_priv.clone(),
1277                                                 first_hop_htlc_msat: htlc_msat,
1278                                         }, onion_packet), channel_state, chan)
1279                                 } {
1280                                         Some((update_add, commitment_signed, chan_monitor)) => {
1281                                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1282                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1283                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1284                                                         // that we will resent the commitment update once we unfree monitor
1285                                                         // updating, so we have to take special care that we don't return
1286                                                         // something else in case we will resend later!
1287                                                         return Err(APIError::MonitorUpdateFailed);
1288                                                 }
1289
1290                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1291                                                         node_id: route.hops.first().unwrap().pubkey,
1292                                                         updates: msgs::CommitmentUpdate {
1293                                                                 update_add_htlcs: vec![update_add],
1294                                                                 update_fulfill_htlcs: Vec::new(),
1295                                                                 update_fail_htlcs: Vec::new(),
1296                                                                 update_fail_malformed_htlcs: Vec::new(),
1297                                                                 update_fee: None,
1298                                                                 commitment_signed,
1299                                                         },
1300                                                 });
1301                                         },
1302                                         None => {},
1303                                 }
1304                         } else { unreachable!(); }
1305                         return Ok(());
1306                 };
1307
1308                 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1309                         Ok(_) => unreachable!(),
1310                         Err(e) => {
1311                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1312                                 } else {
1313                                         log_error!(self, "Got bad keys: {}!", e.err);
1314                                         let mut channel_state = self.channel_state.lock().unwrap();
1315                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1316                                                 node_id: route.hops.first().unwrap().pubkey,
1317                                                 action: e.action,
1318                                         });
1319                                 }
1320                                 Err(APIError::ChannelUnavailable { err: e.err })
1321                         },
1322                 }
1323         }
1324
1325         /// Call this upon creation of a funding transaction for the given channel.
1326         ///
1327         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1328         /// or your counterparty can steal your funds!
1329         ///
1330         /// Panics if a funding transaction has already been provided for this channel.
1331         ///
1332         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1333         /// be trivially prevented by using unique funding transaction keys per-channel).
1334         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1335                 let _ = self.total_consistency_lock.read().unwrap();
1336
1337                 let (chan, msg, chan_monitor) = {
1338                         let (res, chan) = {
1339                                 let mut channel_state = self.channel_state.lock().unwrap();
1340                                 match channel_state.by_id.remove(temporary_channel_id) {
1341                                         Some(mut chan) => {
1342                                                 (chan.get_outbound_funding_created(funding_txo)
1343                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
1344                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1345                                                         } else { unreachable!(); })
1346                                                 , chan)
1347                                         },
1348                                         None => return
1349                                 }
1350                         };
1351                         match handle_error!(self, res, chan.get_their_node_id()) {
1352                                 Ok(funding_msg) => {
1353                                         (chan, funding_msg.0, funding_msg.1)
1354                                 },
1355                                 Err(e) => {
1356                                         log_error!(self, "Got bad signatures: {}!", e.err);
1357                                         let mut channel_state = self.channel_state.lock().unwrap();
1358                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1359                                                 node_id: chan.get_their_node_id(),
1360                                                 action: e.action,
1361                                         });
1362                                         return;
1363                                 },
1364                         }
1365                 };
1366                 // Because we have exclusive ownership of the channel here we can release the channel_state
1367                 // lock before add_update_monitor
1368                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1369                         unimplemented!();
1370                 }
1371
1372                 let mut channel_state = self.channel_state.lock().unwrap();
1373                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1374                         node_id: chan.get_their_node_id(),
1375                         msg: msg,
1376                 });
1377                 match channel_state.by_id.entry(chan.channel_id()) {
1378                         hash_map::Entry::Occupied(_) => {
1379                                 panic!("Generated duplicate funding txid?");
1380                         },
1381                         hash_map::Entry::Vacant(e) => {
1382                                 e.insert(chan);
1383                         }
1384                 }
1385         }
1386
1387         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1388                 if !chan.should_announce() { return None }
1389
1390                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1391                         Ok(res) => res,
1392                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1393                 };
1394                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1395                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1396
1397                 Some(msgs::AnnouncementSignatures {
1398                         channel_id: chan.channel_id(),
1399                         short_channel_id: chan.get_short_channel_id().unwrap(),
1400                         node_signature: our_node_sig,
1401                         bitcoin_signature: our_bitcoin_sig,
1402                 })
1403         }
1404
1405         /// Processes HTLCs which are pending waiting on random forward delay.
1406         ///
1407         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1408         /// Will likely generate further events.
1409         pub fn process_pending_htlc_forwards(&self) {
1410                 let _ = self.total_consistency_lock.read().unwrap();
1411
1412                 let mut new_events = Vec::new();
1413                 let mut failed_forwards = Vec::new();
1414                 {
1415                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1416                         let channel_state = channel_state_lock.borrow_parts();
1417
1418                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1419                                 return;
1420                         }
1421
1422                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1423                                 if short_chan_id != 0 {
1424                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1425                                                 Some(chan_id) => chan_id.clone(),
1426                                                 None => {
1427                                                         failed_forwards.reserve(pending_forwards.len());
1428                                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1429                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1430                                                                         short_channel_id: prev_short_channel_id,
1431                                                                         htlc_id: prev_htlc_id,
1432                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1433                                                                 });
1434                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1435                                                         }
1436                                                         continue;
1437                                                 }
1438                                         };
1439                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1440
1441                                         let mut add_htlc_msgs = Vec::new();
1442                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1443                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1444                                                         short_channel_id: prev_short_channel_id,
1445                                                         htlc_id: prev_htlc_id,
1446                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1447                                                 });
1448                                                 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()) {
1449                                                         Err(_e) => {
1450                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1451                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1452                                                                 continue;
1453                                                         },
1454                                                         Ok(update_add) => {
1455                                                                 match update_add {
1456                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1457                                                                         None => {
1458                                                                                 // Nothing to do here...we're waiting on a remote
1459                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1460                                                                                 // will automatically handle building the update_add_htlc and
1461                                                                                 // commitment_signed messages when we can.
1462                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1463                                                                                 // as we don't really want others relying on us relaying through
1464                                                                                 // this channel currently :/.
1465                                                                         }
1466                                                                 }
1467                                                         }
1468                                                 }
1469                                         }
1470
1471                                         if !add_htlc_msgs.is_empty() {
1472                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1473                                                         Ok(res) => res,
1474                                                         Err(e) => {
1475                                                                 if let ChannelError::Ignore(_) = e {
1476                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1477                                                                 }
1478                                                                 //TODO: Handle...this is bad!
1479                                                                 continue;
1480                                                         },
1481                                                 };
1482                                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1483                                                         unimplemented!();
1484                                                 }
1485                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1486                                                         node_id: forward_chan.get_their_node_id(),
1487                                                         updates: msgs::CommitmentUpdate {
1488                                                                 update_add_htlcs: add_htlc_msgs,
1489                                                                 update_fulfill_htlcs: Vec::new(),
1490                                                                 update_fail_htlcs: Vec::new(),
1491                                                                 update_fail_malformed_htlcs: Vec::new(),
1492                                                                 update_fee: None,
1493                                                                 commitment_signed: commitment_msg,
1494                                                         },
1495                                                 });
1496                                         }
1497                                 } else {
1498                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1499                                                 let prev_hop_data = HTLCPreviousHopData {
1500                                                         short_channel_id: prev_short_channel_id,
1501                                                         htlc_id: prev_htlc_id,
1502                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1503                                                 };
1504                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1505                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1506                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1507                                                 };
1508                                                 new_events.push(events::Event::PaymentReceived {
1509                                                         payment_hash: forward_info.payment_hash,
1510                                                         amt: forward_info.amt_to_forward,
1511                                                 });
1512                                         }
1513                                 }
1514                         }
1515                 }
1516
1517                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1518                         match update {
1519                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1520                                 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() }),
1521                         };
1522                 }
1523
1524                 if new_events.is_empty() { return }
1525                 let mut events = self.pending_events.lock().unwrap();
1526                 events.append(&mut new_events);
1527         }
1528
1529         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect after a PaymentReceived event.
1530         pub fn fail_htlc_backwards(&self, payment_hash: &[u8; 32], reason: PaymentFailReason) -> bool {
1531                 let _ = self.total_consistency_lock.read().unwrap();
1532
1533                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1534                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1535                 if let Some(mut sources) = removed_source {
1536                         for htlc_with_hash in sources.drain(..) {
1537                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1538                                 self.fail_htlc_backwards_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_hash, HTLCFailReason::Reason { failure_code: if reason == PaymentFailReason::PreimageUnknown {0x4000 | 15} else {0x4000 | 16}, data: Vec::new() });
1539                         }
1540                         true
1541                 } else { false }
1542         }
1543
1544         /// Fails an HTLC backwards to the sender of it to us.
1545         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1546         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1547         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1548         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1549         /// still-available channels.
1550         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &[u8; 32], onion_error: HTLCFailReason) {
1551                 match source {
1552                         HTLCSource::OutboundRoute { .. } => {
1553                                 mem::drop(channel_state_lock);
1554                                 if let &HTLCFailReason::ErrorPacket { ref err } = &onion_error {
1555                                         let (channel_update, payment_retryable) = self.process_onion_failure(&source, err.data.clone());
1556                                         if let Some(update) = channel_update {
1557                                                 self.channel_state.lock().unwrap().pending_msg_events.push(
1558                                                         events::MessageSendEvent::PaymentFailureNetworkUpdate {
1559                                                                 update,
1560                                                         }
1561                                                 );
1562                                         }
1563                                         self.pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1564                                                 payment_hash: payment_hash.clone(),
1565                                                 rejected_by_dest: !payment_retryable,
1566                                         });
1567                                 } else {
1568                                         panic!("should have onion error packet here");
1569                                 }
1570                         },
1571                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1572                                 let err_packet = match onion_error {
1573                                         HTLCFailReason::Reason { failure_code, data } => {
1574                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1575                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1576                                         },
1577                                         HTLCFailReason::ErrorPacket { err } => {
1578                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1579                                         }
1580                                 };
1581
1582                                 let channel_state = channel_state_lock.borrow_parts();
1583
1584                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1585                                         Some(chan_id) => chan_id.clone(),
1586                                         None => return
1587                                 };
1588
1589                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1590                                 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1591                                         Ok(Some((msg, commitment_msg, chan_monitor))) => {
1592                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1593                                                         unimplemented!();
1594                                                 }
1595                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1596                                                         node_id: chan.get_their_node_id(),
1597                                                         updates: msgs::CommitmentUpdate {
1598                                                                 update_add_htlcs: Vec::new(),
1599                                                                 update_fulfill_htlcs: Vec::new(),
1600                                                                 update_fail_htlcs: vec![msg],
1601                                                                 update_fail_malformed_htlcs: Vec::new(),
1602                                                                 update_fee: None,
1603                                                                 commitment_signed: commitment_msg,
1604                                                         },
1605                                                 });
1606                                         },
1607                                         Ok(None) => {},
1608                                         Err(_e) => {
1609                                                 //TODO: Do something with e?
1610                                                 return;
1611                                         },
1612                                 }
1613                         },
1614                 }
1615         }
1616
1617         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1618         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1619         /// should probably kick the net layer to go send messages if this returns true!
1620         ///
1621         /// May panic if called except in response to a PaymentReceived event.
1622         pub fn claim_funds(&self, payment_preimage: [u8; 32]) -> bool {
1623                 let mut sha = Sha256::new();
1624                 sha.input(&payment_preimage);
1625                 let mut payment_hash = [0; 32];
1626                 sha.result(&mut payment_hash);
1627
1628                 let _ = self.total_consistency_lock.read().unwrap();
1629
1630                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1631                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1632                 if let Some(mut sources) = removed_source {
1633                         for htlc_with_hash in sources.drain(..) {
1634                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1635                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1636                         }
1637                         true
1638                 } else { false }
1639         }
1640         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: [u8; 32]) {
1641                 match source {
1642                         HTLCSource::OutboundRoute { .. } => {
1643                                 mem::drop(channel_state_lock);
1644                                 let mut pending_events = self.pending_events.lock().unwrap();
1645                                 pending_events.push(events::Event::PaymentSent {
1646                                         payment_preimage
1647                                 });
1648                         },
1649                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1650                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1651                                 let channel_state = channel_state_lock.borrow_parts();
1652
1653                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1654                                         Some(chan_id) => chan_id.clone(),
1655                                         None => {
1656                                                 // TODO: There is probably a channel manager somewhere that needs to
1657                                                 // learn the preimage as the channel already hit the chain and that's
1658                                                 // why its missing.
1659                                                 return
1660                                         }
1661                                 };
1662
1663                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1664                                 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1665                                         Ok((msgs, monitor_option)) => {
1666                                                 if let Some(chan_monitor) = monitor_option {
1667                                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1668                                                                 unimplemented!();// but def dont push the event...
1669                                                         }
1670                                                 }
1671                                                 if let Some((msg, commitment_signed)) = msgs {
1672                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1673                                                                 node_id: chan.get_their_node_id(),
1674                                                                 updates: msgs::CommitmentUpdate {
1675                                                                         update_add_htlcs: Vec::new(),
1676                                                                         update_fulfill_htlcs: vec![msg],
1677                                                                         update_fail_htlcs: Vec::new(),
1678                                                                         update_fail_malformed_htlcs: Vec::new(),
1679                                                                         update_fee: None,
1680                                                                         commitment_signed,
1681                                                                 }
1682                                                         });
1683                                                 }
1684                                         },
1685                                         Err(_e) => {
1686                                                 // TODO: There is probably a channel manager somewhere that needs to
1687                                                 // learn the preimage as the channel may be about to hit the chain.
1688                                                 //TODO: Do something with e?
1689                                                 return
1690                                         },
1691                                 }
1692                         },
1693                 }
1694         }
1695
1696         /// Gets the node_id held by this ChannelManager
1697         pub fn get_our_node_id(&self) -> PublicKey {
1698                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1699         }
1700
1701         /// Used to restore channels to normal operation after a
1702         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1703         /// operation.
1704         pub fn test_restore_channel_monitor(&self) {
1705                 let mut close_results = Vec::new();
1706                 let mut htlc_forwards = Vec::new();
1707                 let mut htlc_failures = Vec::new();
1708                 let _ = self.total_consistency_lock.read().unwrap();
1709
1710                 {
1711                         let mut channel_lock = self.channel_state.lock().unwrap();
1712                         let channel_state = channel_lock.borrow_parts();
1713                         let short_to_id = channel_state.short_to_id;
1714                         let pending_msg_events = channel_state.pending_msg_events;
1715                         channel_state.by_id.retain(|_, channel| {
1716                                 if channel.is_awaiting_monitor_update() {
1717                                         let chan_monitor = channel.channel_monitor();
1718                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1719                                                 match e {
1720                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1721                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1722                                                                 // backwards when a monitor update failed. We should make sure
1723                                                                 // knowledge of those gets moved into the appropriate in-memory
1724                                                                 // ChannelMonitor and they get failed backwards once we get
1725                                                                 // on-chain confirmations.
1726                                                                 // Note I think #198 addresses this, so once its merged a test
1727                                                                 // should be written.
1728                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1729                                                                         short_to_id.remove(&short_id);
1730                                                                 }
1731                                                                 close_results.push(channel.force_shutdown());
1732                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1733                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1734                                                                                 msg: update
1735                                                                         });
1736                                                                 }
1737                                                                 false
1738                                                         },
1739                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1740                                                 }
1741                                         } else {
1742                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1743                                                 if !pending_forwards.is_empty() {
1744                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1745                                                 }
1746                                                 htlc_failures.append(&mut pending_failures);
1747
1748                                                 macro_rules! handle_cs { () => {
1749                                                         if let Some(update) = commitment_update {
1750                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1751                                                                         node_id: channel.get_their_node_id(),
1752                                                                         updates: update,
1753                                                                 });
1754                                                         }
1755                                                 } }
1756                                                 macro_rules! handle_raa { () => {
1757                                                         if let Some(revoke_and_ack) = raa {
1758                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1759                                                                         node_id: channel.get_their_node_id(),
1760                                                                         msg: revoke_and_ack,
1761                                                                 });
1762                                                         }
1763                                                 } }
1764                                                 match order {
1765                                                         RAACommitmentOrder::CommitmentFirst => {
1766                                                                 handle_cs!();
1767                                                                 handle_raa!();
1768                                                         },
1769                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1770                                                                 handle_raa!();
1771                                                                 handle_cs!();
1772                                                         },
1773                                                 }
1774                                                 true
1775                                         }
1776                                 } else { true }
1777                         });
1778                 }
1779
1780                 for failure in htlc_failures.drain(..) {
1781                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1782                 }
1783                 self.forward_htlcs(&mut htlc_forwards[..]);
1784
1785                 for res in close_results.drain(..) {
1786                         self.finish_force_close_channel(res);
1787                 }
1788         }
1789
1790         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1791                 if msg.chain_hash != self.genesis_hash {
1792                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1793                 }
1794
1795                 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)
1796                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1797                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1798                 let channel_state = channel_state_lock.borrow_parts();
1799                 match channel_state.by_id.entry(channel.channel_id()) {
1800                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1801                         hash_map::Entry::Vacant(entry) => {
1802                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1803                                         node_id: their_node_id.clone(),
1804                                         msg: channel.get_accept_channel(),
1805                                 });
1806                                 entry.insert(channel);
1807                         }
1808                 }
1809                 Ok(())
1810         }
1811
1812         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1813                 let (value, output_script, user_id) = {
1814                         let mut channel_lock = self.channel_state.lock().unwrap();
1815                         let channel_state = channel_lock.borrow_parts();
1816                         match channel_state.by_id.entry(msg.temporary_channel_id) {
1817                                 hash_map::Entry::Occupied(mut chan) => {
1818                                         if chan.get().get_their_node_id() != *their_node_id {
1819                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1820                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1821                                         }
1822                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1823                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1824                                 },
1825                                 //TODO: same as above
1826                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1827                         }
1828                 };
1829                 let mut pending_events = self.pending_events.lock().unwrap();
1830                 pending_events.push(events::Event::FundingGenerationReady {
1831                         temporary_channel_id: msg.temporary_channel_id,
1832                         channel_value_satoshis: value,
1833                         output_script: output_script,
1834                         user_channel_id: user_id,
1835                 });
1836                 Ok(())
1837         }
1838
1839         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1840                 let ((funding_msg, monitor_update), chan) = {
1841                         let mut channel_lock = self.channel_state.lock().unwrap();
1842                         let channel_state = channel_lock.borrow_parts();
1843                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1844                                 hash_map::Entry::Occupied(mut chan) => {
1845                                         if chan.get().get_their_node_id() != *their_node_id {
1846                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1847                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1848                                         }
1849                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1850                                 },
1851                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1852                         }
1853                 };
1854                 // Because we have exclusive ownership of the channel here we can release the channel_state
1855                 // lock before add_update_monitor
1856                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1857                         unimplemented!();
1858                 }
1859                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1860                 let channel_state = channel_state_lock.borrow_parts();
1861                 match channel_state.by_id.entry(funding_msg.channel_id) {
1862                         hash_map::Entry::Occupied(_) => {
1863                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1864                         },
1865                         hash_map::Entry::Vacant(e) => {
1866                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1867                                         node_id: their_node_id.clone(),
1868                                         msg: funding_msg,
1869                                 });
1870                                 e.insert(chan);
1871                         }
1872                 }
1873                 Ok(())
1874         }
1875
1876         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1877                 let (funding_txo, user_id) = {
1878                         let mut channel_lock = self.channel_state.lock().unwrap();
1879                         let channel_state = channel_lock.borrow_parts();
1880                         match channel_state.by_id.entry(msg.channel_id) {
1881                                 hash_map::Entry::Occupied(mut chan) => {
1882                                         if chan.get().get_their_node_id() != *their_node_id {
1883                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1884                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1885                                         }
1886                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1887                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1888                                                 unimplemented!();
1889                                         }
1890                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1891                                 },
1892                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1893                         }
1894                 };
1895                 let mut pending_events = self.pending_events.lock().unwrap();
1896                 pending_events.push(events::Event::FundingBroadcastSafe {
1897                         funding_txo: funding_txo,
1898                         user_channel_id: user_id,
1899                 });
1900                 Ok(())
1901         }
1902
1903         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1904                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1905                 let channel_state = channel_state_lock.borrow_parts();
1906                 match channel_state.by_id.entry(msg.channel_id) {
1907                         hash_map::Entry::Occupied(mut chan) => {
1908                                 if chan.get().get_their_node_id() != *their_node_id {
1909                                         //TODO: here and below MsgHandleErrInternal, #153 case
1910                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1911                                 }
1912                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1913                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1914                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1915                                                 node_id: their_node_id.clone(),
1916                                                 msg: announcement_sigs,
1917                                         });
1918                                 }
1919                                 Ok(())
1920                         },
1921                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1922                 }
1923         }
1924
1925         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1926                 let (mut dropped_htlcs, chan_option) = {
1927                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1928                         let channel_state = channel_state_lock.borrow_parts();
1929
1930                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1931                                 hash_map::Entry::Occupied(mut chan_entry) => {
1932                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1933                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1934                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1935                                         }
1936                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1937                                         if let Some(msg) = shutdown {
1938                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1939                                                         node_id: their_node_id.clone(),
1940                                                         msg,
1941                                                 });
1942                                         }
1943                                         if let Some(msg) = closing_signed {
1944                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1945                                                         node_id: their_node_id.clone(),
1946                                                         msg,
1947                                                 });
1948                                         }
1949                                         if chan_entry.get().is_shutdown() {
1950                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1951                                                         channel_state.short_to_id.remove(&short_id);
1952                                                 }
1953                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1954                                         } else { (dropped_htlcs, None) }
1955                                 },
1956                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1957                         }
1958                 };
1959                 for htlc_source in dropped_htlcs.drain(..) {
1960                         // unknown_next_peer...I dunno who that is anymore....
1961                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
1962                 }
1963                 if let Some(chan) = chan_option {
1964                         if let Ok(update) = self.get_channel_update(&chan) {
1965                                 let mut channel_state = self.channel_state.lock().unwrap();
1966                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1967                                         msg: update
1968                                 });
1969                         }
1970                 }
1971                 Ok(())
1972         }
1973
1974         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1975                 let (tx, chan_option) = {
1976                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1977                         let channel_state = channel_state_lock.borrow_parts();
1978                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1979                                 hash_map::Entry::Occupied(mut chan_entry) => {
1980                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1981                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1982                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1983                                         }
1984                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
1985                                         if let Some(msg) = closing_signed {
1986                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1987                                                         node_id: their_node_id.clone(),
1988                                                         msg,
1989                                                 });
1990                                         }
1991                                         if tx.is_some() {
1992                                                 // We're done with this channel, we've got a signed closing transaction and
1993                                                 // will send the closing_signed back to the remote peer upon return. This
1994                                                 // also implies there are no pending HTLCs left on the channel, so we can
1995                                                 // fully delete it from tracking (the channel monitor is still around to
1996                                                 // watch for old state broadcasts)!
1997                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1998                                                         channel_state.short_to_id.remove(&short_id);
1999                                                 }
2000                                                 (tx, Some(chan_entry.remove_entry().1))
2001                                         } else { (tx, None) }
2002                                 },
2003                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2004                         }
2005                 };
2006                 if let Some(broadcast_tx) = tx {
2007                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2008                 }
2009                 if let Some(chan) = chan_option {
2010                         if let Ok(update) = self.get_channel_update(&chan) {
2011                                 let mut channel_state = self.channel_state.lock().unwrap();
2012                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2013                                         msg: update
2014                                 });
2015                         }
2016                 }
2017                 Ok(())
2018         }
2019
2020         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2021                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2022                 //determine the state of the payment based on our response/if we forward anything/the time
2023                 //we take to respond. We should take care to avoid allowing such an attack.
2024                 //
2025                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2026                 //us repeatedly garbled in different ways, and compare our error messages, which are
2027                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2028                 //but we should prevent it anyway.
2029
2030                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2031                 let channel_state = channel_state_lock.borrow_parts();
2032
2033                 match channel_state.by_id.entry(msg.channel_id) {
2034                         hash_map::Entry::Occupied(mut chan) => {
2035                                 if chan.get().get_their_node_id() != *their_node_id {
2036                                         //TODO: here MsgHandleErrInternal, #153 case
2037                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2038                                 }
2039                                 if !chan.get().is_usable() {
2040                                         // If the update_add is completely bogus, the call will Err and we will close,
2041                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2042                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2043                                         if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2044                                                 let chan_update = self.get_channel_update(chan.get());
2045                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2046                                                         channel_id: msg.channel_id,
2047                                                         htlc_id: msg.htlc_id,
2048                                                         reason: if let Ok(update) = chan_update {
2049                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &update.encode_with_len()[..])
2050                                                         } else {
2051                                                                 // This can only happen if the channel isn't in the fully-funded
2052                                                                 // state yet, implying our counterparty is trying to route payments
2053                                                                 // over the channel back to themselves (cause no one else should
2054                                                                 // know the short_id is a lightning channel yet). We should have no
2055                                                                 // problem just calling this unknown_next_peer
2056                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2057                                                         },
2058                                                 }));
2059                                         }
2060                                 }
2061                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2062                         },
2063                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2064                 }
2065                 Ok(())
2066         }
2067
2068         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2069                 let mut channel_lock = self.channel_state.lock().unwrap();
2070                 let htlc_source = {
2071                         let channel_state = channel_lock.borrow_parts();
2072                         match channel_state.by_id.entry(msg.channel_id) {
2073                                 hash_map::Entry::Occupied(mut chan) => {
2074                                         if chan.get().get_their_node_id() != *their_node_id {
2075                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2076                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2077                                         }
2078                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2079                                 },
2080                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2081                         }
2082                 };
2083                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2084                 Ok(())
2085         }
2086
2087         // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2088         // indicating that the payment itself failed
2089         fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool) {
2090                 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2091                         macro_rules! onion_failure_log {
2092                                 ( $error_code_textual: expr, $error_code: expr, $reported_name: expr, $reported_value: expr ) => {
2093                                         log_trace!(self, "{}({:#x}) {}({})", $error_code_textual, $error_code, $reported_name, $reported_value);
2094                                 };
2095                                 ( $error_code_textual: expr, $error_code: expr ) => {
2096                                         log_trace!(self, "{}({})", $error_code_textual, $error_code);
2097                                 };
2098                         }
2099
2100                         const BADONION: u16 = 0x8000;
2101                         const PERM: u16 = 0x4000;
2102                         const UPDATE: u16 = 0x1000;
2103
2104                         let mut res = None;
2105                         let mut htlc_msat = *first_hop_htlc_msat;
2106
2107                         // Handle packed channel/node updates for passing back for the route handler
2108                         Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2109                                 if res.is_some() { return; }
2110
2111                                 let incoming_htlc_msat = htlc_msat;
2112                                 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2113                                 htlc_msat = amt_to_forward;
2114
2115                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2116
2117                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2118                                 decryption_tmp.resize(packet_decrypted.len(), 0);
2119                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2120                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2121                                 packet_decrypted = decryption_tmp;
2122
2123                                 let is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2124
2125                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2126                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2127                                         let mut hmac = Hmac::new(Sha256::new(), &um);
2128                                         hmac.input(&err_packet.encode()[32..]);
2129                                         let mut calc_tag = [0u8; 32];
2130                                         hmac.raw_result(&mut calc_tag);
2131
2132                                         if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
2133                                                 if err_packet.failuremsg.len() < 2 {
2134                                                         // Useless packet that we can't use but it passed HMAC, so it
2135                                                         // definitely came from the peer in question
2136                                                         res = Some((None, !is_from_final_node));
2137                                                 } else {
2138                                                         let error_code = byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]);
2139
2140                                                         match error_code & 0xff {
2141                                                                 1|2|3 => {
2142                                                                         // either from an intermediate or final node
2143                                                                         //   invalid_realm(PERM|1),
2144                                                                         //   temporary_node_failure(NODE|2)
2145                                                                         //   permanent_node_failure(PERM|NODE|2)
2146                                                                         //   required_node_feature_mssing(PERM|NODE|3)
2147                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2148                                                                                 node_id: route_hop.pubkey,
2149                                                                                 is_permanent: error_code & PERM == PERM,
2150                                                                         }), !(error_code & PERM == PERM && is_from_final_node)));
2151                                                                         // node returning invalid_realm is removed from network_map,
2152                                                                         // although NODE flag is not set, TODO: or remove channel only?
2153                                                                         // retry payment when removed node is not a final node
2154                                                                         return;
2155                                                                 },
2156                                                                 _ => {}
2157                                                         }
2158
2159                                                         if is_from_final_node {
2160                                                                 let payment_retryable = match error_code {
2161                                                                         c if c == PERM|15 => false, // unknown_payment_hash
2162                                                                         c if c == PERM|16 => false, // incorrect_payment_amount
2163                                                                         17 => true, // final_expiry_too_soon
2164                                                                         18 if err_packet.failuremsg.len() == 6 => { // final_incorrect_cltv_expiry
2165                                                                                 let _reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2166                                                                                 true
2167                                                                         },
2168                                                                         19 if err_packet.failuremsg.len() == 10 => { // final_incorrect_htlc_amount
2169                                                                                 let _reported_incoming_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2170                                                                                 true
2171                                                                         },
2172                                                                         _ => {
2173                                                                                 // A final node has sent us either an invalid code or an error_code that
2174                                                                                 // MUST be sent from the processing node, or the formmat of failuremsg
2175                                                                                 // does not coform to the spec.
2176                                                                                 // Remove it from the network map and don't may retry payment
2177                                                                                 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2178                                                                                         node_id: route_hop.pubkey,
2179                                                                                         is_permanent: true,
2180                                                                                 }), false));
2181                                                                                 return;
2182                                                                         }
2183                                                                 };
2184                                                                 res = Some((None, payment_retryable));
2185                                                                 return;
2186                                                         }
2187
2188                                                         // now, error_code should be only from the intermediate nodes
2189                                                         match error_code {
2190                                                                 _c if error_code & PERM == PERM => {
2191                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2192                                                                                 short_channel_id: route_hop.short_channel_id,
2193                                                                                 is_permanent: true,
2194                                                                         }), false));
2195                                                                 },
2196                                                                 _c if error_code & UPDATE == UPDATE => {
2197                                                                         let offset = match error_code {
2198                                                                                 c if c == UPDATE|7  => 0, // temporary_channel_failure
2199                                                                                 c if c == UPDATE|11 => 8, // amount_below_minimum
2200                                                                                 c if c == UPDATE|12 => 8, // fee_insufficient
2201                                                                                 c if c == UPDATE|13 => 4, // incorrect_cltv_expiry
2202                                                                                 c if c == UPDATE|14 => 0, // expiry_too_soon
2203                                                                                 c if c == UPDATE|20 => 2, // channel_disabled
2204                                                                                 _ =>  {
2205                                                                                         // node sending unknown code
2206                                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2207                                                                                                 node_id: route_hop.pubkey,
2208                                                                                                 is_permanent: true,
2209                                                                                         }), false));
2210                                                                                         return;
2211                                                                                 }
2212                                                                         };
2213
2214                                                                         if err_packet.failuremsg.len() >= offset + 2 {
2215                                                                                 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[offset+2..offset+4]) as usize;
2216                                                                                 if err_packet.failuremsg.len() >= offset + 4 + update_len {
2217                                                                                         if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&err_packet.failuremsg[offset + 4..offset + 4 + update_len])) {
2218                                                                                                 // if channel_update should NOT have caused the failure:
2219                                                                                                 // MAY treat the channel_update as invalid.
2220                                                                                                 let is_chan_update_invalid = match error_code {
2221                                                                                                         c if c == UPDATE|7 => { // temporary_channel_failure
2222                                                                                                                 false
2223                                                                                                         },
2224                                                                                                         c if c == UPDATE|11 => { // amount_below_minimum
2225                                                                                                                 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2226                                                                                                                 onion_failure_log!("amount_below_minimum", UPDATE|11, "htlc_msat", reported_htlc_msat);
2227                                                                                                                 incoming_htlc_msat > chan_update.contents.htlc_minimum_msat
2228                                                                                                         },
2229                                                                                                         c if c == UPDATE|12 => { // fee_insufficient
2230                                                                                                                 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2231                                                                                                                 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) });
2232                                                                                                                 onion_failure_log!("fee_insufficient", UPDATE|12, "htlc_msat", reported_htlc_msat);
2233                                                                                                                 new_fee.is_none() || incoming_htlc_msat >= new_fee.unwrap() && incoming_htlc_msat >= amt_to_forward + new_fee.unwrap()
2234                                                                                                         }
2235                                                                                                         c if c == UPDATE|13 => { // incorrect_cltv_expiry
2236                                                                                                                 let reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2237                                                                                                                 onion_failure_log!("incorrect_cltv_expiry", UPDATE|13, "cltv_expiry", reported_cltv_expiry);
2238                                                                                                                 route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta
2239                                                                                                         },
2240                                                                                                         c if c == UPDATE|20 => { // channel_disabled
2241                                                                                                                 let reported_flags = byte_utils::slice_to_be16(&err_packet.failuremsg[2..2+2]);
2242                                                                                                                 onion_failure_log!("channel_disabled", UPDATE|20, "flags", reported_flags);
2243                                                                                                                 chan_update.contents.flags & 0x01 == 0x01
2244                                                                                                         },
2245                                                                                                         c if c == UPDATE|21 => true, // expiry_too_far
2246                                                                                                         _ => { unreachable!(); },
2247                                                                                                 };
2248
2249                                                                                                 let msg = if is_chan_update_invalid { None } else {
2250                                                                                                         Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2251                                                                                                                 msg: chan_update,
2252                                                                                                         })
2253                                                                                                 };
2254                                                                                                 res = Some((msg, true));
2255                                                                                                 return;
2256                                                                                         }
2257                                                                                 }
2258                                                                         }
2259                                                                 },
2260                                                                 _c if error_code & BADONION == BADONION => {
2261                                                                         //TODO
2262                                                                 },
2263                                                                 14 => { // expiry_too_soon
2264                                                                         res = Some((None, true));
2265                                                                         return;
2266                                                                 }
2267                                                                 _ => {
2268                                                                         // node sending unknown code
2269                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2270                                                                                 node_id: route_hop.pubkey,
2271                                                                                 is_permanent: true,
2272                                                                         }), false));
2273                                                                         return;
2274                                                                 }
2275                                                         }
2276                                                 }
2277                                         }
2278                                 }
2279                         }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2280                         res.unwrap_or((None, true))
2281                 } else { ((None, true)) }
2282         }
2283
2284         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2285                 let mut channel_lock = self.channel_state.lock().unwrap();
2286                 let channel_state = channel_lock.borrow_parts();
2287                 match channel_state.by_id.entry(msg.channel_id) {
2288                         hash_map::Entry::Occupied(mut chan) => {
2289                                 if chan.get().get_their_node_id() != *their_node_id {
2290                                         //TODO: here and below MsgHandleErrInternal, #153 case
2291                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2292                                 }
2293                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2294                         },
2295                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2296                 }
2297                 Ok(())
2298         }
2299
2300         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2301                 let mut channel_lock = self.channel_state.lock().unwrap();
2302                 let channel_state = channel_lock.borrow_parts();
2303                 match channel_state.by_id.entry(msg.channel_id) {
2304                         hash_map::Entry::Occupied(mut chan) => {
2305                                 if chan.get().get_their_node_id() != *their_node_id {
2306                                         //TODO: here and below MsgHandleErrInternal, #153 case
2307                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2308                                 }
2309                                 if (msg.failure_code & 0x8000) == 0 {
2310                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2311                                 }
2312                                 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);
2313                                 Ok(())
2314                         },
2315                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2316                 }
2317         }
2318
2319         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2320                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2321                 let channel_state = channel_state_lock.borrow_parts();
2322                 match channel_state.by_id.entry(msg.channel_id) {
2323                         hash_map::Entry::Occupied(mut chan) => {
2324                                 if chan.get().get_their_node_id() != *their_node_id {
2325                                         //TODO: here and below MsgHandleErrInternal, #153 case
2326                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2327                                 }
2328                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2329                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2330                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2331                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2332                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2333                                 }
2334                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2335                                         node_id: their_node_id.clone(),
2336                                         msg: revoke_and_ack,
2337                                 });
2338                                 if let Some(msg) = commitment_signed {
2339                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2340                                                 node_id: their_node_id.clone(),
2341                                                 updates: msgs::CommitmentUpdate {
2342                                                         update_add_htlcs: Vec::new(),
2343                                                         update_fulfill_htlcs: Vec::new(),
2344                                                         update_fail_htlcs: Vec::new(),
2345                                                         update_fail_malformed_htlcs: Vec::new(),
2346                                                         update_fee: None,
2347                                                         commitment_signed: msg,
2348                                                 },
2349                                         });
2350                                 }
2351                                 if let Some(msg) = closing_signed {
2352                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2353                                                 node_id: their_node_id.clone(),
2354                                                 msg,
2355                                         });
2356                                 }
2357                                 Ok(())
2358                         },
2359                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2360                 }
2361         }
2362
2363         #[inline]
2364         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2365                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2366                         let mut forward_event = None;
2367                         if !pending_forwards.is_empty() {
2368                                 let mut channel_state = self.channel_state.lock().unwrap();
2369                                 if channel_state.forward_htlcs.is_empty() {
2370                                         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));
2371                                         channel_state.next_forward = forward_event.unwrap();
2372                                 }
2373                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2374                                         match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2375                                                 hash_map::Entry::Occupied(mut entry) => {
2376                                                         entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2377                                                 },
2378                                                 hash_map::Entry::Vacant(entry) => {
2379                                                         entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2380                                                 }
2381                                         }
2382                                 }
2383                         }
2384                         match forward_event {
2385                                 Some(time) => {
2386                                         let mut pending_events = self.pending_events.lock().unwrap();
2387                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2388                                                 time_forwardable: time
2389                                         });
2390                                 }
2391                                 None => {},
2392                         }
2393                 }
2394         }
2395
2396         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2397                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2398                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2399                         let channel_state = channel_state_lock.borrow_parts();
2400                         match channel_state.by_id.entry(msg.channel_id) {
2401                                 hash_map::Entry::Occupied(mut chan) => {
2402                                         if chan.get().get_their_node_id() != *their_node_id {
2403                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2404                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2405                                         }
2406                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2407                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2408                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2409                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2410                                         }
2411                                         if let Some(updates) = commitment_update {
2412                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2413                                                         node_id: their_node_id.clone(),
2414                                                         updates,
2415                                                 });
2416                                         }
2417                                         if let Some(msg) = closing_signed {
2418                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2419                                                         node_id: their_node_id.clone(),
2420                                                         msg,
2421                                                 });
2422                                         }
2423                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2424                                 },
2425                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2426                         }
2427                 };
2428                 for failure in pending_failures.drain(..) {
2429                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2430                 }
2431                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2432
2433                 Ok(())
2434         }
2435
2436         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2437                 let mut channel_lock = self.channel_state.lock().unwrap();
2438                 let channel_state = channel_lock.borrow_parts();
2439                 match channel_state.by_id.entry(msg.channel_id) {
2440                         hash_map::Entry::Occupied(mut chan) => {
2441                                 if chan.get().get_their_node_id() != *their_node_id {
2442                                         //TODO: here and below MsgHandleErrInternal, #153 case
2443                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2444                                 }
2445                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2446                         },
2447                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2448                 }
2449                 Ok(())
2450         }
2451
2452         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2453                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2454                 let channel_state = channel_state_lock.borrow_parts();
2455
2456                 match channel_state.by_id.entry(msg.channel_id) {
2457                         hash_map::Entry::Occupied(mut chan) => {
2458                                 if chan.get().get_their_node_id() != *their_node_id {
2459                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2460                                 }
2461                                 if !chan.get().is_usable() {
2462                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2463                                 }
2464
2465                                 let our_node_id = self.get_our_node_id();
2466                                 let (announcement, our_bitcoin_sig) =
2467                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2468
2469                                 let were_node_one = announcement.node_id_1 == our_node_id;
2470                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2471                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2472                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2473                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2474                                 }
2475
2476                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2477
2478                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2479                                         msg: msgs::ChannelAnnouncement {
2480                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2481                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2482                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2483                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2484                                                 contents: announcement,
2485                                         },
2486                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2487                                 });
2488                         },
2489                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2490                 }
2491                 Ok(())
2492         }
2493
2494         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2495                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2496                 let channel_state = channel_state_lock.borrow_parts();
2497
2498                 match channel_state.by_id.entry(msg.channel_id) {
2499                         hash_map::Entry::Occupied(mut chan) => {
2500                                 if chan.get().get_their_node_id() != *their_node_id {
2501                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2502                                 }
2503                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2504                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2505                                 if let Some(monitor) = channel_monitor {
2506                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2507                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2508                                                 // for the messages it returns, but if we're setting what messages to
2509                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2510                                                 if revoke_and_ack.is_none() {
2511                                                         order = RAACommitmentOrder::CommitmentFirst;
2512                                                 }
2513                                                 if commitment_update.is_none() {
2514                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2515                                                 }
2516                                                 return_monitor_err!(self, e, channel_state, chan, order);
2517                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2518                                         }
2519                                 }
2520                                 if let Some(msg) = funding_locked {
2521                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2522                                                 node_id: their_node_id.clone(),
2523                                                 msg
2524                                         });
2525                                 }
2526                                 macro_rules! send_raa { () => {
2527                                         if let Some(msg) = revoke_and_ack {
2528                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2529                                                         node_id: their_node_id.clone(),
2530                                                         msg
2531                                                 });
2532                                         }
2533                                 } }
2534                                 macro_rules! send_cu { () => {
2535                                         if let Some(updates) = commitment_update {
2536                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2537                                                         node_id: their_node_id.clone(),
2538                                                         updates
2539                                                 });
2540                                         }
2541                                 } }
2542                                 match order {
2543                                         RAACommitmentOrder::RevokeAndACKFirst => {
2544                                                 send_raa!();
2545                                                 send_cu!();
2546                                         },
2547                                         RAACommitmentOrder::CommitmentFirst => {
2548                                                 send_cu!();
2549                                                 send_raa!();
2550                                         },
2551                                 }
2552                                 if let Some(msg) = shutdown {
2553                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2554                                                 node_id: their_node_id.clone(),
2555                                                 msg,
2556                                         });
2557                                 }
2558                                 Ok(())
2559                         },
2560                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2561                 }
2562         }
2563
2564         /// Begin Update fee process. Allowed only on an outbound channel.
2565         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2566         /// PeerManager::process_events afterwards.
2567         /// Note: This API is likely to change!
2568         #[doc(hidden)]
2569         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2570                 let _ = self.total_consistency_lock.read().unwrap();
2571                 let their_node_id;
2572                 let err: Result<(), _> = loop {
2573                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2574                         let channel_state = channel_state_lock.borrow_parts();
2575
2576                         match channel_state.by_id.entry(channel_id) {
2577                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2578                                 hash_map::Entry::Occupied(mut chan) => {
2579                                         if !chan.get().is_outbound() {
2580                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2581                                         }
2582                                         if chan.get().is_awaiting_monitor_update() {
2583                                                 return Err(APIError::MonitorUpdateFailed);
2584                                         }
2585                                         if !chan.get().is_live() {
2586                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2587                                         }
2588                                         their_node_id = chan.get().get_their_node_id();
2589                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2590                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2591                                         {
2592                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2593                                                         unimplemented!();
2594                                                 }
2595                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2596                                                         node_id: chan.get().get_their_node_id(),
2597                                                         updates: msgs::CommitmentUpdate {
2598                                                                 update_add_htlcs: Vec::new(),
2599                                                                 update_fulfill_htlcs: Vec::new(),
2600                                                                 update_fail_htlcs: Vec::new(),
2601                                                                 update_fail_malformed_htlcs: Vec::new(),
2602                                                                 update_fee: Some(update_fee),
2603                                                                 commitment_signed,
2604                                                         },
2605                                                 });
2606                                         }
2607                                 },
2608                         }
2609                         return Ok(())
2610                 };
2611
2612                 match handle_error!(self, err, their_node_id) {
2613                         Ok(_) => unreachable!(),
2614                         Err(e) => {
2615                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2616                                 } else {
2617                                         log_error!(self, "Got bad keys: {}!", e.err);
2618                                         let mut channel_state = self.channel_state.lock().unwrap();
2619                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2620                                                 node_id: their_node_id,
2621                                                 action: e.action,
2622                                         });
2623                                 }
2624                                 Err(APIError::APIMisuseError { err: e.err })
2625                         },
2626                 }
2627         }
2628 }
2629
2630 impl events::MessageSendEventsProvider for ChannelManager {
2631         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2632                 let mut ret = Vec::new();
2633                 let mut channel_state = self.channel_state.lock().unwrap();
2634                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2635                 ret
2636         }
2637 }
2638
2639 impl events::EventsProvider for ChannelManager {
2640         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2641                 let mut ret = Vec::new();
2642                 let mut pending_events = self.pending_events.lock().unwrap();
2643                 mem::swap(&mut ret, &mut *pending_events);
2644                 ret
2645         }
2646 }
2647
2648 impl ChainListener for ChannelManager {
2649         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
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                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2683                                                                         short_to_id.remove(&short_id);
2684                                                                 }
2685                                                                 // It looks like our counterparty went on-chain. We go ahead and
2686                                                                 // broadcast our latest local state as well here, just in case its
2687                                                                 // some kind of SPV attack, though we expect these to be dropped.
2688                                                                 failed_channels.push(channel.force_shutdown());
2689                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2690                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2691                                                                                 msg: update
2692                                                                         });
2693                                                                 }
2694                                                                 return false;
2695                                                         }
2696                                                 }
2697                                         }
2698                                 }
2699                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2700                                         if let Some(short_id) = channel.get_short_channel_id() {
2701                                                 short_to_id.remove(&short_id);
2702                                         }
2703                                         failed_channels.push(channel.force_shutdown());
2704                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2705                                         // the latest local tx for us, so we should skip that here (it doesn't really
2706                                         // hurt anything, but does make tests a bit simpler).
2707                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2708                                         if let Ok(update) = self.get_channel_update(&channel) {
2709                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2710                                                         msg: update
2711                                                 });
2712                                         }
2713                                         return false;
2714                                 }
2715                                 true
2716                         });
2717                 }
2718                 for failure in failed_channels.drain(..) {
2719                         self.finish_force_close_channel(failure);
2720                 }
2721                 self.latest_block_height.store(height as usize, Ordering::Release);
2722                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2723         }
2724
2725         /// We force-close the channel without letting our counterparty participate in the shutdown
2726         fn block_disconnected(&self, header: &BlockHeader) {
2727                 let _ = self.total_consistency_lock.read().unwrap();
2728                 let mut failed_channels = Vec::new();
2729                 {
2730                         let mut channel_lock = self.channel_state.lock().unwrap();
2731                         let channel_state = channel_lock.borrow_parts();
2732                         let short_to_id = channel_state.short_to_id;
2733                         let pending_msg_events = channel_state.pending_msg_events;
2734                         channel_state.by_id.retain(|_,  v| {
2735                                 if v.block_disconnected(header) {
2736                                         if let Some(short_id) = v.get_short_channel_id() {
2737                                                 short_to_id.remove(&short_id);
2738                                         }
2739                                         failed_channels.push(v.force_shutdown());
2740                                         if let Ok(update) = self.get_channel_update(&v) {
2741                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2742                                                         msg: update
2743                                                 });
2744                                         }
2745                                         false
2746                                 } else {
2747                                         true
2748                                 }
2749                         });
2750                 }
2751                 for failure in failed_channels.drain(..) {
2752                         self.finish_force_close_channel(failure);
2753                 }
2754                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2755                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2756         }
2757 }
2758
2759 impl ChannelMessageHandler for ChannelManager {
2760         //TODO: Handle errors and close channel (or so)
2761         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2762                 let _ = self.total_consistency_lock.read().unwrap();
2763                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2764         }
2765
2766         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2767                 let _ = self.total_consistency_lock.read().unwrap();
2768                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2769         }
2770
2771         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2772                 let _ = self.total_consistency_lock.read().unwrap();
2773                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2774         }
2775
2776         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2777                 let _ = self.total_consistency_lock.read().unwrap();
2778                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2779         }
2780
2781         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2782                 let _ = self.total_consistency_lock.read().unwrap();
2783                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2784         }
2785
2786         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2787                 let _ = self.total_consistency_lock.read().unwrap();
2788                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2789         }
2790
2791         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2792                 let _ = self.total_consistency_lock.read().unwrap();
2793                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2794         }
2795
2796         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2797                 let _ = self.total_consistency_lock.read().unwrap();
2798                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2799         }
2800
2801         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2802                 let _ = self.total_consistency_lock.read().unwrap();
2803                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2804         }
2805
2806         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2807                 let _ = self.total_consistency_lock.read().unwrap();
2808                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2809         }
2810
2811         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2812                 let _ = self.total_consistency_lock.read().unwrap();
2813                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2814         }
2815
2816         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2817                 let _ = self.total_consistency_lock.read().unwrap();
2818                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2819         }
2820
2821         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2822                 let _ = self.total_consistency_lock.read().unwrap();
2823                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2824         }
2825
2826         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2827                 let _ = self.total_consistency_lock.read().unwrap();
2828                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2829         }
2830
2831         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2832                 let _ = self.total_consistency_lock.read().unwrap();
2833                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2834         }
2835
2836         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2837                 let _ = self.total_consistency_lock.read().unwrap();
2838                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2839         }
2840
2841         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2842                 let _ = self.total_consistency_lock.read().unwrap();
2843                 let mut failed_channels = Vec::new();
2844                 let mut failed_payments = Vec::new();
2845                 {
2846                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2847                         let channel_state = channel_state_lock.borrow_parts();
2848                         let short_to_id = channel_state.short_to_id;
2849                         let pending_msg_events = channel_state.pending_msg_events;
2850                         if no_connection_possible {
2851                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2852                                 channel_state.by_id.retain(|_, chan| {
2853                                         if chan.get_their_node_id() == *their_node_id {
2854                                                 if let Some(short_id) = chan.get_short_channel_id() {
2855                                                         short_to_id.remove(&short_id);
2856                                                 }
2857                                                 failed_channels.push(chan.force_shutdown());
2858                                                 if let Ok(update) = self.get_channel_update(&chan) {
2859                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2860                                                                 msg: update
2861                                                         });
2862                                                 }
2863                                                 false
2864                                         } else {
2865                                                 true
2866                                         }
2867                                 });
2868                         } else {
2869                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2870                                 channel_state.by_id.retain(|_, chan| {
2871                                         if chan.get_their_node_id() == *their_node_id {
2872                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2873                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2874                                                 if !failed_adds.is_empty() {
2875                                                         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
2876                                                         failed_payments.push((chan_update, failed_adds));
2877                                                 }
2878                                                 if chan.is_shutdown() {
2879                                                         if let Some(short_id) = chan.get_short_channel_id() {
2880                                                                 short_to_id.remove(&short_id);
2881                                                         }
2882                                                         return false;
2883                                                 }
2884                                         }
2885                                         true
2886                                 })
2887                         }
2888                 }
2889                 for failure in failed_channels.drain(..) {
2890                         self.finish_force_close_channel(failure);
2891                 }
2892                 for (chan_update, mut htlc_sources) in failed_payments {
2893                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2894                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2895                         }
2896                 }
2897         }
2898
2899         fn peer_connected(&self, their_node_id: &PublicKey) {
2900                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2901
2902                 let _ = self.total_consistency_lock.read().unwrap();
2903                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2904                 let channel_state = channel_state_lock.borrow_parts();
2905                 let pending_msg_events = channel_state.pending_msg_events;
2906                 channel_state.by_id.retain(|_, chan| {
2907                         if chan.get_their_node_id() == *their_node_id {
2908                                 if !chan.have_received_message() {
2909                                         // If we created this (outbound) channel while we were disconnected from the
2910                                         // peer we probably failed to send the open_channel message, which is now
2911                                         // lost. We can't have had anything pending related to this channel, so we just
2912                                         // drop it.
2913                                         false
2914                                 } else {
2915                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2916                                                 node_id: chan.get_their_node_id(),
2917                                                 msg: chan.get_channel_reestablish(),
2918                                         });
2919                                         true
2920                                 }
2921                         } else { true }
2922                 });
2923                 //TODO: Also re-broadcast announcement_signatures
2924         }
2925
2926         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2927                 let _ = self.total_consistency_lock.read().unwrap();
2928
2929                 if msg.channel_id == [0; 32] {
2930                         for chan in self.list_channels() {
2931                                 if chan.remote_network_id == *their_node_id {
2932                                         self.force_close_channel(&chan.channel_id);
2933                                 }
2934                         }
2935                 } else {
2936                         self.force_close_channel(&msg.channel_id);
2937                 }
2938         }
2939 }
2940
2941 const SERIALIZATION_VERSION: u8 = 1;
2942 const MIN_SERIALIZATION_VERSION: u8 = 1;
2943
2944 impl Writeable for PendingForwardHTLCInfo {
2945         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2946                 if let &Some(ref onion) = &self.onion_packet {
2947                         1u8.write(writer)?;
2948                         onion.write(writer)?;
2949                 } else {
2950                         0u8.write(writer)?;
2951                 }
2952                 self.incoming_shared_secret.write(writer)?;
2953                 self.payment_hash.write(writer)?;
2954                 self.short_channel_id.write(writer)?;
2955                 self.amt_to_forward.write(writer)?;
2956                 self.outgoing_cltv_value.write(writer)?;
2957                 Ok(())
2958         }
2959 }
2960
2961 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2962         fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2963                 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
2964                         0 => None,
2965                         1 => Some(msgs::OnionPacket::read(reader)?),
2966                         _ => return Err(DecodeError::InvalidValue),
2967                 };
2968                 Ok(PendingForwardHTLCInfo {
2969                         onion_packet,
2970                         incoming_shared_secret: Readable::read(reader)?,
2971                         payment_hash: Readable::read(reader)?,
2972                         short_channel_id: Readable::read(reader)?,
2973                         amt_to_forward: Readable::read(reader)?,
2974                         outgoing_cltv_value: Readable::read(reader)?,
2975                 })
2976         }
2977 }
2978
2979 impl Writeable for HTLCFailureMsg {
2980         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2981                 match self {
2982                         &HTLCFailureMsg::Relay(ref fail_msg) => {
2983                                 0u8.write(writer)?;
2984                                 fail_msg.write(writer)?;
2985                         },
2986                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
2987                                 1u8.write(writer)?;
2988                                 fail_msg.write(writer)?;
2989                         }
2990                 }
2991                 Ok(())
2992         }
2993 }
2994
2995 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
2996         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
2997                 match <u8 as Readable<R>>::read(reader)? {
2998                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
2999                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3000                         _ => Err(DecodeError::InvalidValue),
3001                 }
3002         }
3003 }
3004
3005 impl Writeable for PendingHTLCStatus {
3006         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3007                 match self {
3008                         &PendingHTLCStatus::Forward(ref forward_info) => {
3009                                 0u8.write(writer)?;
3010                                 forward_info.write(writer)?;
3011                         },
3012                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3013                                 1u8.write(writer)?;
3014                                 fail_msg.write(writer)?;
3015                         }
3016                 }
3017                 Ok(())
3018         }
3019 }
3020
3021 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3022         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3023                 match <u8 as Readable<R>>::read(reader)? {
3024                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3025                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3026                         _ => Err(DecodeError::InvalidValue),
3027                 }
3028         }
3029 }
3030
3031 impl_writeable!(HTLCPreviousHopData, 0, {
3032         short_channel_id,
3033         htlc_id,
3034         incoming_packet_shared_secret
3035 });
3036
3037 impl Writeable for HTLCSource {
3038         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3039                 match self {
3040                         &HTLCSource::PreviousHopData(ref hop_data) => {
3041                                 0u8.write(writer)?;
3042                                 hop_data.write(writer)?;
3043                         },
3044                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3045                                 1u8.write(writer)?;
3046                                 route.write(writer)?;
3047                                 session_priv.write(writer)?;
3048                                 first_hop_htlc_msat.write(writer)?;
3049                         }
3050                 }
3051                 Ok(())
3052         }
3053 }
3054
3055 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3056         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3057                 match <u8 as Readable<R>>::read(reader)? {
3058                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3059                         1 => Ok(HTLCSource::OutboundRoute {
3060                                 route: Readable::read(reader)?,
3061                                 session_priv: Readable::read(reader)?,
3062                                 first_hop_htlc_msat: Readable::read(reader)?,
3063                         }),
3064                         _ => Err(DecodeError::InvalidValue),
3065                 }
3066         }
3067 }
3068
3069 impl Writeable for HTLCFailReason {
3070         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3071                 match self {
3072                         &HTLCFailReason::ErrorPacket { ref err } => {
3073                                 0u8.write(writer)?;
3074                                 err.write(writer)?;
3075                         },
3076                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3077                                 1u8.write(writer)?;
3078                                 failure_code.write(writer)?;
3079                                 data.write(writer)?;
3080                         }
3081                 }
3082                 Ok(())
3083         }
3084 }
3085
3086 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3087         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3088                 match <u8 as Readable<R>>::read(reader)? {
3089                         0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3090                         1 => Ok(HTLCFailReason::Reason {
3091                                 failure_code: Readable::read(reader)?,
3092                                 data: Readable::read(reader)?,
3093                         }),
3094                         _ => Err(DecodeError::InvalidValue),
3095                 }
3096         }
3097 }
3098
3099 impl_writeable!(HTLCForwardInfo, 0, {
3100         prev_short_channel_id,
3101         prev_htlc_id,
3102         forward_info
3103 });
3104
3105 impl Writeable for ChannelManager {
3106         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3107                 let _ = self.total_consistency_lock.write().unwrap();
3108
3109                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3110                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3111
3112                 self.genesis_hash.write(writer)?;
3113                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3114                 self.last_block_hash.lock().unwrap().write(writer)?;
3115
3116                 let channel_state = self.channel_state.lock().unwrap();
3117                 let mut unfunded_channels = 0;
3118                 for (_, channel) in channel_state.by_id.iter() {
3119                         if !channel.is_funding_initiated() {
3120                                 unfunded_channels += 1;
3121                         }
3122                 }
3123                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3124                 for (_, channel) in channel_state.by_id.iter() {
3125                         if channel.is_funding_initiated() {
3126                                 channel.write(writer)?;
3127                         }
3128                 }
3129
3130                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3131                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3132                         short_channel_id.write(writer)?;
3133                         (pending_forwards.len() as u64).write(writer)?;
3134                         for forward in pending_forwards {
3135                                 forward.write(writer)?;
3136                         }
3137                 }
3138
3139                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3140                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3141                         payment_hash.write(writer)?;
3142                         (previous_hops.len() as u64).write(writer)?;
3143                         for previous_hop in previous_hops {
3144                                 previous_hop.write(writer)?;
3145                         }
3146                 }
3147
3148                 Ok(())
3149         }
3150 }
3151
3152 /// Arguments for the creation of a ChannelManager that are not deserialized.
3153 ///
3154 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3155 /// is:
3156 /// 1) Deserialize all stored ChannelMonitors.
3157 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3158 ///    ChannelManager)>::read(reader, args).
3159 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3160 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3161 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3162 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3163 /// 4) Reconnect blocks on your ChannelMonitors.
3164 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3165 /// 6) Disconnect/connect blocks on the ChannelManager.
3166 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3167 ///    automatically as it does in ChannelManager::new()).
3168 pub struct ChannelManagerReadArgs<'a> {
3169         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3170         /// deserialization.
3171         pub keys_manager: Arc<KeysInterface>,
3172
3173         /// The fee_estimator for use in the ChannelManager in the future.
3174         ///
3175         /// No calls to the FeeEstimator will be made during deserialization.
3176         pub fee_estimator: Arc<FeeEstimator>,
3177         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3178         ///
3179         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3180         /// you have deserialized ChannelMonitors separately and will add them to your
3181         /// ManyChannelMonitor after deserializing this ChannelManager.
3182         pub monitor: Arc<ManyChannelMonitor>,
3183         /// The ChainWatchInterface for use in the ChannelManager in the future.
3184         ///
3185         /// No calls to the ChainWatchInterface will be made during deserialization.
3186         pub chain_monitor: Arc<ChainWatchInterface>,
3187         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3188         /// used to broadcast the latest local commitment transactions of channels which must be
3189         /// force-closed during deserialization.
3190         pub tx_broadcaster: Arc<BroadcasterInterface>,
3191         /// The Logger for use in the ChannelManager and which may be used to log information during
3192         /// deserialization.
3193         pub logger: Arc<Logger>,
3194         /// Default settings used for new channels. Any existing channels will continue to use the
3195         /// runtime settings which were stored when the ChannelManager was serialized.
3196         pub default_config: UserConfig,
3197
3198         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3199         /// value.get_funding_txo() should be the key).
3200         ///
3201         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3202         /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3203         /// is true for missing channels as well. If there is a monitor missing for which we find
3204         /// channel data Err(DecodeError::InvalidValue) will be returned.
3205         ///
3206         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3207         /// this struct.
3208         pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3209 }
3210
3211 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3212         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3213                 let _ver: u8 = Readable::read(reader)?;
3214                 let min_ver: u8 = Readable::read(reader)?;
3215                 if min_ver > SERIALIZATION_VERSION {
3216                         return Err(DecodeError::UnknownVersion);
3217                 }
3218
3219                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3220                 let latest_block_height: u32 = Readable::read(reader)?;
3221                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3222
3223                 let mut closed_channels = Vec::new();
3224
3225                 let channel_count: u64 = Readable::read(reader)?;
3226                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3227                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3228                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3229                 for _ in 0..channel_count {
3230                         let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3231                         if channel.last_block_connected != last_block_hash {
3232                                 return Err(DecodeError::InvalidValue);
3233                         }
3234
3235                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3236                         funding_txo_set.insert(funding_txo.clone());
3237                         if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3238                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3239                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3240                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3241                                         let mut force_close_res = channel.force_shutdown();
3242                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3243                                         closed_channels.push(force_close_res);
3244                                 } else {
3245                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3246                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3247                                         }
3248                                         by_id.insert(channel.channel_id(), channel);
3249                                 }
3250                         } else {
3251                                 return Err(DecodeError::InvalidValue);
3252                         }
3253                 }
3254
3255                 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3256                         if !funding_txo_set.contains(funding_txo) {
3257                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3258                         }
3259                 }
3260
3261                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3262                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3263                 for _ in 0..forward_htlcs_count {
3264                         let short_channel_id = Readable::read(reader)?;
3265                         let pending_forwards_count: u64 = Readable::read(reader)?;
3266                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3267                         for _ in 0..pending_forwards_count {
3268                                 pending_forwards.push(Readable::read(reader)?);
3269                         }
3270                         forward_htlcs.insert(short_channel_id, pending_forwards);
3271                 }
3272
3273                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3274                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3275                 for _ in 0..claimable_htlcs_count {
3276                         let payment_hash = Readable::read(reader)?;
3277                         let previous_hops_len: u64 = Readable::read(reader)?;
3278                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3279                         for _ in 0..previous_hops_len {
3280                                 previous_hops.push(Readable::read(reader)?);
3281                         }
3282                         claimable_htlcs.insert(payment_hash, previous_hops);
3283                 }
3284
3285                 let channel_manager = ChannelManager {
3286                         genesis_hash,
3287                         fee_estimator: args.fee_estimator,
3288                         monitor: args.monitor,
3289                         chain_monitor: args.chain_monitor,
3290                         tx_broadcaster: args.tx_broadcaster,
3291
3292                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3293                         last_block_hash: Mutex::new(last_block_hash),
3294                         secp_ctx: Secp256k1::new(),
3295
3296                         channel_state: Mutex::new(ChannelHolder {
3297                                 by_id,
3298                                 short_to_id,
3299                                 next_forward: Instant::now(),
3300                                 forward_htlcs,
3301                                 claimable_htlcs,
3302                                 pending_msg_events: Vec::new(),
3303                         }),
3304                         our_network_key: args.keys_manager.get_node_secret(),
3305
3306                         pending_events: Mutex::new(Vec::new()),
3307                         total_consistency_lock: RwLock::new(()),
3308                         keys_manager: args.keys_manager,
3309                         logger: args.logger,
3310                         default_configuration: args.default_config,
3311                 };
3312
3313                 for close_res in closed_channels.drain(..) {
3314                         channel_manager.finish_force_close_channel(close_res);
3315                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3316                         //connection or two.
3317                 }
3318
3319                 Ok((last_block_hash.clone(), channel_manager))
3320         }
3321 }
3322
3323 #[cfg(test)]
3324 mod tests {
3325         use chain::chaininterface;
3326         use chain::transaction::OutPoint;
3327         use chain::chaininterface::{ChainListener, ChainWatchInterface};
3328         use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3329         use chain::keysinterface;
3330         use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3331         use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder};
3332         use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3333         use ln::router::{Route, RouteHop, Router};
3334         use ln::msgs;
3335         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
3336         use util::test_utils;
3337         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3338         use util::errors::APIError;
3339         use util::logger::Logger;
3340         use util::ser::{Writeable, Writer, ReadableArgs};
3341         use util::config::UserConfig;
3342
3343         use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3344         use bitcoin::util::bip143;
3345         use bitcoin::util::address::Address;
3346         use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3347         use bitcoin::blockdata::block::{Block, BlockHeader};
3348         use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3349         use bitcoin::blockdata::script::{Builder, Script};
3350         use bitcoin::blockdata::opcodes;
3351         use bitcoin::blockdata::constants::genesis_block;
3352         use bitcoin::network::constants::Network;
3353
3354         use hex;
3355
3356         use secp256k1::{Secp256k1, Message};
3357         use secp256k1::key::{PublicKey,SecretKey};
3358
3359         use crypto::sha2::Sha256;
3360         use crypto::digest::Digest;
3361
3362         use rand::{thread_rng,Rng};
3363
3364         use std::cell::RefCell;
3365         use std::collections::{BTreeSet, HashMap};
3366         use std::default::Default;
3367         use std::rc::Rc;
3368         use std::sync::{Arc, Mutex};
3369         use std::sync::atomic::Ordering;
3370         use std::time::Instant;
3371         use std::mem;
3372
3373         fn build_test_onion_keys() -> Vec<OnionKeys> {
3374                 // Keys from BOLT 4, used in both test vector tests
3375                 let secp_ctx = Secp256k1::new();
3376
3377                 let route = Route {
3378                         hops: vec!(
3379                                         RouteHop {
3380                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3381                                                 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
3382                                         },
3383                                         RouteHop {
3384                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3385                                                 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
3386                                         },
3387                                         RouteHop {
3388                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3389                                                 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
3390                                         },
3391                                         RouteHop {
3392                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3393                                                 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
3394                                         },
3395                                         RouteHop {
3396                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3397                                                 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
3398                                         },
3399                         ),
3400                 };
3401
3402                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3403
3404                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3405                 assert_eq!(onion_keys.len(), route.hops.len());
3406                 onion_keys
3407         }
3408
3409         #[test]
3410         fn onion_vectors() {
3411                 // Packet creation test vectors from BOLT 4
3412                 let onion_keys = build_test_onion_keys();
3413
3414                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3415                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3416                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3417                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3418                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3419
3420                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3421                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3422                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3423                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3424                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3425
3426                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3427                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3428                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3429                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3430                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3431
3432                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3433                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3434                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3435                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3436                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3437
3438                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3439                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3440                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3441                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3442                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3443
3444                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3445                 let payloads = vec!(
3446                         msgs::OnionHopData {
3447                                 realm: 0,
3448                                 data: msgs::OnionRealm0HopData {
3449                                         short_channel_id: 0,
3450                                         amt_to_forward: 0,
3451                                         outgoing_cltv_value: 0,
3452                                 },
3453                                 hmac: [0; 32],
3454                         },
3455                         msgs::OnionHopData {
3456                                 realm: 0,
3457                                 data: msgs::OnionRealm0HopData {
3458                                         short_channel_id: 0x0101010101010101,
3459                                         amt_to_forward: 0x0100000001,
3460                                         outgoing_cltv_value: 0,
3461                                 },
3462                                 hmac: [0; 32],
3463                         },
3464                         msgs::OnionHopData {
3465                                 realm: 0,
3466                                 data: msgs::OnionRealm0HopData {
3467                                         short_channel_id: 0x0202020202020202,
3468                                         amt_to_forward: 0x0200000002,
3469                                         outgoing_cltv_value: 0,
3470                                 },
3471                                 hmac: [0; 32],
3472                         },
3473                         msgs::OnionHopData {
3474                                 realm: 0,
3475                                 data: msgs::OnionRealm0HopData {
3476                                         short_channel_id: 0x0303030303030303,
3477                                         amt_to_forward: 0x0300000003,
3478                                         outgoing_cltv_value: 0,
3479                                 },
3480                                 hmac: [0; 32],
3481                         },
3482                         msgs::OnionHopData {
3483                                 realm: 0,
3484                                 data: msgs::OnionRealm0HopData {
3485                                         short_channel_id: 0x0404040404040404,
3486                                         amt_to_forward: 0x0400000004,
3487                                         outgoing_cltv_value: 0,
3488                                 },
3489                                 hmac: [0; 32],
3490                         },
3491                 );
3492
3493                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &[0x42; 32]);
3494                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3495                 // anyway...
3496                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3497         }
3498
3499         #[test]
3500         fn test_failure_packet_onion() {
3501                 // Returning Errors test vectors from BOLT 4
3502
3503                 let onion_keys = build_test_onion_keys();
3504                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3505                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3506
3507                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3508                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3509
3510                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3511                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3512
3513                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3514                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3515
3516                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3517                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3518
3519                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3520                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3521         }
3522
3523         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3524                 assert!(chain.does_match_tx(tx));
3525                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3526                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3527                 for i in 2..100 {
3528                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3529                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3530                 }
3531         }
3532
3533         struct Node {
3534                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3535                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3536                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3537                 node: Arc<ChannelManager>,
3538                 router: Router,
3539                 node_seed: [u8; 32],
3540                 network_payment_count: Rc<RefCell<u8>>,
3541                 network_chan_count: Rc<RefCell<u32>>,
3542         }
3543         impl Drop for Node {
3544                 fn drop(&mut self) {
3545                         if !::std::thread::panicking() {
3546                                 // Check that we processed all pending events
3547                                 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3548                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3549                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3550                         }
3551                 }
3552         }
3553
3554         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3555                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3556         }
3557
3558         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) {
3559                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3560                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3561                 (announcement, as_update, bs_update, channel_id, tx)
3562         }
3563
3564         macro_rules! get_revoke_commit_msgs {
3565                 ($node: expr, $node_id: expr) => {
3566                         {
3567                                 let events = $node.node.get_and_clear_pending_msg_events();
3568                                 assert_eq!(events.len(), 2);
3569                                 (match events[0] {
3570                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3571                                                 assert_eq!(*node_id, $node_id);
3572                                                 (*msg).clone()
3573                                         },
3574                                         _ => panic!("Unexpected event"),
3575                                 }, match events[1] {
3576                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3577                                                 assert_eq!(*node_id, $node_id);
3578                                                 assert!(updates.update_add_htlcs.is_empty());
3579                                                 assert!(updates.update_fulfill_htlcs.is_empty());
3580                                                 assert!(updates.update_fail_htlcs.is_empty());
3581                                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
3582                                                 assert!(updates.update_fee.is_none());
3583                                                 updates.commitment_signed.clone()
3584                                         },
3585                                         _ => panic!("Unexpected event"),
3586                                 })
3587                         }
3588                 }
3589         }
3590
3591         macro_rules! get_event_msg {
3592                 ($node: expr, $event_type: path, $node_id: expr) => {
3593                         {
3594                                 let events = $node.node.get_and_clear_pending_msg_events();
3595                                 assert_eq!(events.len(), 1);
3596                                 match events[0] {
3597                                         $event_type { ref node_id, ref msg } => {
3598                                                 assert_eq!(*node_id, $node_id);
3599                                                 (*msg).clone()
3600                                         },
3601                                         _ => panic!("Unexpected event"),
3602                                 }
3603                         }
3604                 }
3605         }
3606
3607         macro_rules! get_htlc_update_msgs {
3608                 ($node: expr, $node_id: expr) => {
3609                         {
3610                                 let events = $node.node.get_and_clear_pending_msg_events();
3611                                 assert_eq!(events.len(), 1);
3612                                 match events[0] {
3613                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3614                                                 assert_eq!(*node_id, $node_id);
3615                                                 (*updates).clone()
3616                                         },
3617                                         _ => panic!("Unexpected event"),
3618                                 }
3619                         }
3620                 }
3621         }
3622
3623         macro_rules! get_feerate {
3624                 ($node: expr, $channel_id: expr) => {
3625                         {
3626                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3627                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3628                                 chan.get_feerate()
3629                         }
3630                 }
3631         }
3632
3633
3634         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3635                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3636                 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();
3637                 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();
3638
3639                 let chan_id = *node_a.network_chan_count.borrow();
3640                 let tx;
3641                 let funding_output;
3642
3643                 let events_2 = node_a.node.get_and_clear_pending_events();
3644                 assert_eq!(events_2.len(), 1);
3645                 match events_2[0] {
3646                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3647                                 assert_eq!(*channel_value_satoshis, channel_value);
3648                                 assert_eq!(user_channel_id, 42);
3649
3650                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3651                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3652                                 }]};
3653                                 funding_output = OutPoint::new(tx.txid(), 0);
3654
3655                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3656                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3657                                 assert_eq!(added_monitors.len(), 1);
3658                                 assert_eq!(added_monitors[0].0, funding_output);
3659                                 added_monitors.clear();
3660                         },
3661                         _ => panic!("Unexpected event"),
3662                 }
3663
3664                 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();
3665                 {
3666                         let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3667                         assert_eq!(added_monitors.len(), 1);
3668                         assert_eq!(added_monitors[0].0, funding_output);
3669                         added_monitors.clear();
3670                 }
3671
3672                 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();
3673                 {
3674                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3675                         assert_eq!(added_monitors.len(), 1);
3676                         assert_eq!(added_monitors[0].0, funding_output);
3677                         added_monitors.clear();
3678                 }
3679
3680                 let events_4 = node_a.node.get_and_clear_pending_events();
3681                 assert_eq!(events_4.len(), 1);
3682                 match events_4[0] {
3683                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3684                                 assert_eq!(user_channel_id, 42);
3685                                 assert_eq!(*funding_txo, funding_output);
3686                         },
3687                         _ => panic!("Unexpected event"),
3688                 };
3689
3690                 tx
3691         }
3692
3693         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3694                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3695                 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();
3696
3697                 let channel_id;
3698
3699                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3700                 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3701                 assert_eq!(events_6.len(), 2);
3702                 ((match events_6[0] {
3703                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3704                                 channel_id = msg.channel_id.clone();
3705                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3706                                 msg.clone()
3707                         },
3708                         _ => panic!("Unexpected event"),
3709                 }, match events_6[1] {
3710                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3711                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3712                                 msg.clone()
3713                         },
3714                         _ => panic!("Unexpected event"),
3715                 }), channel_id)
3716         }
3717
3718         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) {
3719                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3720                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3721                 (msgs, chan_id, tx)
3722         }
3723
3724         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) {
3725                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3726                 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3727                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3728
3729                 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3730                 assert_eq!(events_7.len(), 1);
3731                 let (announcement, bs_update) = match events_7[0] {
3732                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3733                                 (msg, update_msg)
3734                         },
3735                         _ => panic!("Unexpected event"),
3736                 };
3737
3738                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3739                 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3740                 assert_eq!(events_8.len(), 1);
3741                 let as_update = match events_8[0] {
3742                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3743                                 assert!(*announcement == *msg);
3744                                 update_msg
3745                         },
3746                         _ => panic!("Unexpected event"),
3747                 };
3748
3749                 *node_a.network_chan_count.borrow_mut() += 1;
3750
3751                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3752         }
3753
3754         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3755                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3756         }
3757
3758         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) {
3759                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3760                 for node in nodes {
3761                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3762                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
3763                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
3764                 }
3765                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3766         }
3767
3768         macro_rules! check_spends {
3769                 ($tx: expr, $spends_tx: expr) => {
3770                         {
3771                                 let mut funding_tx_map = HashMap::new();
3772                                 let spends_tx = $spends_tx;
3773                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3774                                 $tx.verify(&funding_tx_map).unwrap();
3775                         }
3776                 }
3777         }
3778
3779         macro_rules! get_closing_signed_broadcast {
3780                 ($node: expr, $dest_pubkey: expr) => {
3781                         {
3782                                 let events = $node.get_and_clear_pending_msg_events();
3783                                 assert!(events.len() == 1 || events.len() == 2);
3784                                 (match events[events.len() - 1] {
3785                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3786                                                 assert_eq!(msg.contents.flags & 2, 2);
3787                                                 msg.clone()
3788                                         },
3789                                         _ => panic!("Unexpected event"),
3790                                 }, if events.len() == 2 {
3791                                         match events[0] {
3792                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3793                                                         assert_eq!(*node_id, $dest_pubkey);
3794                                                         Some(msg.clone())
3795                                                 },
3796                                                 _ => panic!("Unexpected event"),
3797                                         }
3798                                 } else { None })
3799                         }
3800                 }
3801         }
3802
3803         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) {
3804                 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) };
3805                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3806                 let (tx_a, tx_b);
3807
3808                 node_a.close_channel(channel_id).unwrap();
3809                 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3810
3811                 let events_1 = node_b.get_and_clear_pending_msg_events();
3812                 assert!(events_1.len() >= 1);
3813                 let shutdown_b = match events_1[0] {
3814                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3815                                 assert_eq!(node_id, &node_a.get_our_node_id());
3816                                 msg.clone()
3817                         },
3818                         _ => panic!("Unexpected event"),
3819                 };
3820
3821                 let closing_signed_b = if !close_inbound_first {
3822                         assert_eq!(events_1.len(), 1);
3823                         None
3824                 } else {
3825                         Some(match events_1[1] {
3826                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3827                                         assert_eq!(node_id, &node_a.get_our_node_id());
3828                                         msg.clone()
3829                                 },
3830                                 _ => panic!("Unexpected event"),
3831                         })
3832                 };
3833
3834                 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3835                 let (as_update, bs_update) = if close_inbound_first {
3836                         assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3837                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3838                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3839                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3840                         let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3841
3842                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3843                         let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3844                         assert!(none_b.is_none());
3845                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3846                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3847                         (as_update, bs_update)
3848                 } else {
3849                         let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3850
3851                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3852                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3853                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3854                         let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3855
3856                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3857                         let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3858                         assert!(none_a.is_none());
3859                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3860                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3861                         (as_update, bs_update)
3862                 };
3863                 assert_eq!(tx_a, tx_b);
3864                 check_spends!(tx_a, funding_tx);
3865
3866                 (as_update, bs_update, tx_a)
3867         }
3868
3869         struct SendEvent {
3870                 node_id: PublicKey,
3871                 msgs: Vec<msgs::UpdateAddHTLC>,
3872                 commitment_msg: msgs::CommitmentSigned,
3873         }
3874         impl SendEvent {
3875                 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3876                         assert!(updates.update_fulfill_htlcs.is_empty());
3877                         assert!(updates.update_fail_htlcs.is_empty());
3878                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3879                         assert!(updates.update_fee.is_none());
3880                         SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3881                 }
3882
3883                 fn from_event(event: MessageSendEvent) -> SendEvent {
3884                         match event {
3885                                 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3886                                 _ => panic!("Unexpected event type!"),
3887                         }
3888                 }
3889         }
3890
3891         macro_rules! check_added_monitors {
3892                 ($node: expr, $count: expr) => {
3893                         {
3894                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3895                                 assert_eq!(added_monitors.len(), $count);
3896                                 added_monitors.clear();
3897                         }
3898                 }
3899         }
3900
3901         macro_rules! commitment_signed_dance {
3902                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3903                         {
3904                                 check_added_monitors!($node_a, 0);
3905                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3906                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3907                                 check_added_monitors!($node_a, 1);
3908                                 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3909                         }
3910                 };
3911                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3912                         {
3913                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3914                                 check_added_monitors!($node_b, 0);
3915                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3916                                 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3917                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3918                                 check_added_monitors!($node_b, 1);
3919                                 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3920                                 let (bs_revoke_and_ack, extra_msg_option) = {
3921                                         let events = $node_b.node.get_and_clear_pending_msg_events();
3922                                         assert!(events.len() <= 2);
3923                                         (match events[0] {
3924                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3925                                                         assert_eq!(*node_id, $node_a.node.get_our_node_id());
3926                                                         (*msg).clone()
3927                                                 },
3928                                                 _ => panic!("Unexpected event"),
3929                                         }, events.get(1).map(|e| e.clone()))
3930                                 };
3931                                 check_added_monitors!($node_b, 1);
3932                                 if $fail_backwards {
3933                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
3934                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3935                                 }
3936                                 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3937                                 {
3938                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
3939                                         if $fail_backwards {
3940                                                 assert_eq!(added_monitors.len(), 2);
3941                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
3942                                         } else {
3943                                                 assert_eq!(added_monitors.len(), 1);
3944                                         }
3945                                         added_monitors.clear();
3946                                 }
3947                                 extra_msg_option
3948                         }
3949                 };
3950                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
3951                         {
3952                                 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
3953                         }
3954                 };
3955                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
3956                         {
3957                                 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
3958                                 if $fail_backwards {
3959                                         let channel_state = $node_a.node.channel_state.lock().unwrap();
3960                                         assert_eq!(channel_state.pending_msg_events.len(), 1);
3961                                         if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
3962                                                 assert_ne!(*node_id, $node_b.node.get_our_node_id());
3963                                         } else { panic!("Unexpected event"); }
3964                                 } else {
3965                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3966                                 }
3967                         }
3968                 }
3969         }
3970
3971         macro_rules! get_payment_preimage_hash {
3972                 ($node: expr) => {
3973                         {
3974                                 let payment_preimage = [*$node.network_payment_count.borrow(); 32];
3975                                 *$node.network_payment_count.borrow_mut() += 1;
3976                                 let mut payment_hash = [0; 32];
3977                                 let mut sha = Sha256::new();
3978                                 sha.input(&payment_preimage[..]);
3979                                 sha.result(&mut payment_hash);
3980                                 (payment_preimage, payment_hash)
3981                         }
3982                 }
3983         }
3984
3985         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
3986                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
3987
3988                 let mut payment_event = {
3989                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
3990                         check_added_monitors!(origin_node, 1);
3991
3992                         let mut events = origin_node.node.get_and_clear_pending_msg_events();
3993                         assert_eq!(events.len(), 1);
3994                         SendEvent::from_event(events.remove(0))
3995                 };
3996                 let mut prev_node = origin_node;
3997
3998                 for (idx, &node) in expected_route.iter().enumerate() {
3999                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4000
4001                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4002                         check_added_monitors!(node, 0);
4003                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4004
4005                         let events_1 = node.node.get_and_clear_pending_events();
4006                         assert_eq!(events_1.len(), 1);
4007                         match events_1[0] {
4008                                 Event::PendingHTLCsForwardable { .. } => { },
4009                                 _ => panic!("Unexpected event"),
4010                         };
4011
4012                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4013                         node.node.process_pending_htlc_forwards();
4014
4015                         if idx == expected_route.len() - 1 {
4016                                 let events_2 = node.node.get_and_clear_pending_events();
4017                                 assert_eq!(events_2.len(), 1);
4018                                 match events_2[0] {
4019                                         Event::PaymentReceived { ref payment_hash, amt } => {
4020                                                 assert_eq!(our_payment_hash, *payment_hash);
4021                                                 assert_eq!(amt, recv_value);
4022                                         },
4023                                         _ => panic!("Unexpected event"),
4024                                 }
4025                         } else {
4026                                 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4027                                 assert_eq!(events_2.len(), 1);
4028                                 check_added_monitors!(node, 1);
4029                                 payment_event = SendEvent::from_event(events_2.remove(0));
4030                                 assert_eq!(payment_event.msgs.len(), 1);
4031                         }
4032
4033                         prev_node = node;
4034                 }
4035
4036                 (our_payment_preimage, our_payment_hash)
4037         }
4038
4039         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: [u8; 32]) {
4040                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4041                 check_added_monitors!(expected_route.last().unwrap(), 1);
4042
4043                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4044                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4045                 macro_rules! get_next_msgs {
4046                         ($node: expr) => {
4047                                 {
4048                                         let events = $node.node.get_and_clear_pending_msg_events();
4049                                         assert_eq!(events.len(), 1);
4050                                         match events[0] {
4051                                                 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 } } => {
4052                                                         assert!(update_add_htlcs.is_empty());
4053                                                         assert_eq!(update_fulfill_htlcs.len(), 1);
4054                                                         assert!(update_fail_htlcs.is_empty());
4055                                                         assert!(update_fail_malformed_htlcs.is_empty());
4056                                                         assert!(update_fee.is_none());
4057                                                         expected_next_node = node_id.clone();
4058                                                         Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4059                                                 },
4060                                                 _ => panic!("Unexpected event"),
4061                                         }
4062                                 }
4063                         }
4064                 }
4065
4066                 macro_rules! last_update_fulfill_dance {
4067                         ($node: expr, $prev_node: expr) => {
4068                                 {
4069                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4070                                         check_added_monitors!($node, 0);
4071                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4072                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4073                                 }
4074                         }
4075                 }
4076                 macro_rules! mid_update_fulfill_dance {
4077                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4078                                 {
4079                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4080                                         check_added_monitors!($node, 1);
4081                                         let new_next_msgs = if $new_msgs {
4082                                                 get_next_msgs!($node)
4083                                         } else {
4084                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4085                                                 None
4086                                         };
4087                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4088                                         next_msgs = new_next_msgs;
4089                                 }
4090                         }
4091                 }
4092
4093                 let mut prev_node = expected_route.last().unwrap();
4094                 for (idx, node) in expected_route.iter().rev().enumerate() {
4095                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4096                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4097                         if next_msgs.is_some() {
4098                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4099                         } else if update_next_msgs {
4100                                 next_msgs = get_next_msgs!(node);
4101                         } else {
4102                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4103                         }
4104                         if !skip_last && idx == expected_route.len() - 1 {
4105                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4106                         }
4107
4108                         prev_node = node;
4109                 }
4110
4111                 if !skip_last {
4112                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4113                         let events = origin_node.node.get_and_clear_pending_events();
4114                         assert_eq!(events.len(), 1);
4115                         match events[0] {
4116                                 Event::PaymentSent { payment_preimage } => {
4117                                         assert_eq!(payment_preimage, our_payment_preimage);
4118                                 },
4119                                 _ => panic!("Unexpected event"),
4120                         }
4121                 }
4122         }
4123
4124         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: [u8; 32]) {
4125                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4126         }
4127
4128         const TEST_FINAL_CLTV: u32 = 32;
4129
4130         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
4131                 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();
4132                 assert_eq!(route.hops.len(), expected_route.len());
4133                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4134                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4135                 }
4136
4137                 send_along_route(origin_node, route, expected_route, recv_value)
4138         }
4139
4140         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4141                 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();
4142                 assert_eq!(route.hops.len(), expected_route.len());
4143                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4144                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4145                 }
4146
4147                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4148
4149                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4150                 match err {
4151                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4152                         _ => panic!("Unknown error variants"),
4153                 };
4154         }
4155
4156         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4157                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4158                 claim_payment(&origin, expected_route, our_payment_preimage);
4159         }
4160
4161         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: [u8; 32]) {
4162                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
4163                 check_added_monitors!(expected_route.last().unwrap(), 1);
4164
4165                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4166                 macro_rules! update_fail_dance {
4167                         ($node: expr, $prev_node: expr, $last_node: expr) => {
4168                                 {
4169                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4170                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4171                                 }
4172                         }
4173                 }
4174
4175                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4176                 let mut prev_node = expected_route.last().unwrap();
4177                 for (idx, node) in expected_route.iter().rev().enumerate() {
4178                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4179                         if next_msgs.is_some() {
4180                                 // We may be the "last node" for the purpose of the commitment dance if we're
4181                                 // skipping the last node (implying it is disconnected) and we're the
4182                                 // second-to-last node!
4183                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4184                         }
4185
4186                         let events = node.node.get_and_clear_pending_msg_events();
4187                         if !skip_last || idx != expected_route.len() - 1 {
4188                                 assert_eq!(events.len(), 1);
4189                                 match events[0] {
4190                                         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 } } => {
4191                                                 assert!(update_add_htlcs.is_empty());
4192                                                 assert!(update_fulfill_htlcs.is_empty());
4193                                                 assert_eq!(update_fail_htlcs.len(), 1);
4194                                                 assert!(update_fail_malformed_htlcs.is_empty());
4195                                                 assert!(update_fee.is_none());
4196                                                 expected_next_node = node_id.clone();
4197                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4198                                         },
4199                                         _ => panic!("Unexpected event"),
4200                                 }
4201                         } else {
4202                                 assert!(events.is_empty());
4203                         }
4204                         if !skip_last && idx == expected_route.len() - 1 {
4205                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4206                         }
4207
4208                         prev_node = node;
4209                 }
4210
4211                 if !skip_last {
4212                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4213
4214                         let events = origin_node.node.get_and_clear_pending_events();
4215                         assert_eq!(events.len(), 1);
4216                         match events[0] {
4217                                 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
4218                                         assert_eq!(payment_hash, our_payment_hash);
4219                                         assert!(rejected_by_dest);
4220                                 },
4221                                 _ => panic!("Unexpected event"),
4222                         }
4223                 }
4224         }
4225
4226         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: [u8; 32]) {
4227                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4228         }
4229
4230         fn create_network(node_count: usize) -> Vec<Node> {
4231                 let mut nodes = Vec::new();
4232                 let mut rng = thread_rng();
4233                 let secp_ctx = Secp256k1::new();
4234                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
4235
4236                 let chan_count = Rc::new(RefCell::new(0));
4237                 let payment_count = Rc::new(RefCell::new(0));
4238
4239                 for _ in 0..node_count {
4240                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4241                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4242                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4243                         let mut seed = [0; 32];
4244                         rng.fill_bytes(&mut seed);
4245                         let keys_manager = Arc::new(keysinterface::KeysManager::new(&seed, Network::Testnet, Arc::clone(&logger)));
4246                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4247                         let mut config = UserConfig::new();
4248                         config.channel_options.announced_channel = true;
4249                         config.channel_limits.force_announced_channel_preference = false;
4250                         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();
4251                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4252                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, node_seed: seed,
4253                                 network_payment_count: payment_count.clone(),
4254                                 network_chan_count: chan_count.clone(),
4255                         });
4256                 }
4257
4258                 nodes
4259         }
4260
4261         #[test]
4262         fn test_async_inbound_update_fee() {
4263                 let mut nodes = create_network(2);
4264                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4265                 let channel_id = chan.2;
4266
4267                 // balancing
4268                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4269
4270                 // A                                        B
4271                 // update_fee                            ->
4272                 // send (1) commitment_signed            -.
4273                 //                                       <- update_add_htlc/commitment_signed
4274                 // send (2) RAA (awaiting remote revoke) -.
4275                 // (1) commitment_signed is delivered    ->
4276                 //                                       .- send (3) RAA (awaiting remote revoke)
4277                 // (2) RAA is delivered                  ->
4278                 //                                       .- send (4) commitment_signed
4279                 //                                       <- (3) RAA is delivered
4280                 // send (5) commitment_signed            -.
4281                 //                                       <- (4) commitment_signed is delivered
4282                 // send (6) RAA                          -.
4283                 // (5) commitment_signed is delivered    ->
4284                 //                                       <- RAA
4285                 // (6) RAA is delivered                  ->
4286
4287                 // First nodes[0] generates an update_fee
4288                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4289                 check_added_monitors!(nodes[0], 1);
4290
4291                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4292                 assert_eq!(events_0.len(), 1);
4293                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4294                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4295                                 (update_fee.as_ref(), commitment_signed)
4296                         },
4297                         _ => panic!("Unexpected event"),
4298                 };
4299
4300                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4301
4302                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4303                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4304                 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();
4305                 check_added_monitors!(nodes[1], 1);
4306
4307                 let payment_event = {
4308                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4309                         assert_eq!(events_1.len(), 1);
4310                         SendEvent::from_event(events_1.remove(0))
4311                 };
4312                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4313                 assert_eq!(payment_event.msgs.len(), 1);
4314
4315                 // ...now when the messages get delivered everyone should be happy
4316                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4317                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4318                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4319                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4320                 check_added_monitors!(nodes[0], 1);
4321
4322                 // deliver(1), generate (3):
4323                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4324                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4325                 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4326                 check_added_monitors!(nodes[1], 1);
4327
4328                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4329                 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4330                 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4331                 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4332                 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4333                 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4334                 assert!(bs_update.update_fee.is_none()); // (4)
4335                 check_added_monitors!(nodes[1], 1);
4336
4337                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4338                 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4339                 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4340                 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4341                 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4342                 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4343                 assert!(as_update.update_fee.is_none()); // (5)
4344                 check_added_monitors!(nodes[0], 1);
4345
4346                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4347                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4348                 // only (6) so get_event_msg's assert(len == 1) passes
4349                 check_added_monitors!(nodes[0], 1);
4350
4351                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4352                 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4353                 check_added_monitors!(nodes[1], 1);
4354
4355                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4356                 check_added_monitors!(nodes[0], 1);
4357
4358                 let events_2 = nodes[0].node.get_and_clear_pending_events();
4359                 assert_eq!(events_2.len(), 1);
4360                 match events_2[0] {
4361                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4362                         _ => panic!("Unexpected event"),
4363                 }
4364
4365                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4366                 check_added_monitors!(nodes[1], 1);
4367         }
4368
4369         #[test]
4370         fn test_update_fee_unordered_raa() {
4371                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4372                 // crash in an earlier version of the update_fee patch)
4373                 let mut nodes = create_network(2);
4374                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4375                 let channel_id = chan.2;
4376
4377                 // balancing
4378                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4379
4380                 // First nodes[0] generates an update_fee
4381                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4382                 check_added_monitors!(nodes[0], 1);
4383
4384                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4385                 assert_eq!(events_0.len(), 1);
4386                 let update_msg = match events_0[0] { // (1)
4387                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4388                                 update_fee.as_ref()
4389                         },
4390                         _ => panic!("Unexpected event"),
4391                 };
4392
4393                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4394
4395                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4396                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4397                 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();
4398                 check_added_monitors!(nodes[1], 1);
4399
4400                 let payment_event = {
4401                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4402                         assert_eq!(events_1.len(), 1);
4403                         SendEvent::from_event(events_1.remove(0))
4404                 };
4405                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4406                 assert_eq!(payment_event.msgs.len(), 1);
4407
4408                 // ...now when the messages get delivered everyone should be happy
4409                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4410                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4411                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4412                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4413                 check_added_monitors!(nodes[0], 1);
4414
4415                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4416                 check_added_monitors!(nodes[1], 1);
4417
4418                 // We can't continue, sadly, because our (1) now has a bogus signature
4419         }
4420
4421         #[test]
4422         fn test_multi_flight_update_fee() {
4423                 let nodes = create_network(2);
4424                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4425                 let channel_id = chan.2;
4426
4427                 // A                                        B
4428                 // update_fee/commitment_signed          ->
4429                 //                                       .- send (1) RAA and (2) commitment_signed
4430                 // update_fee (never committed)          ->
4431                 // (3) update_fee                        ->
4432                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4433                 // don't track which updates correspond to which revoke_and_ack responses so we're in
4434                 // AwaitingRAA mode and will not generate the update_fee yet.
4435                 //                                       <- (1) RAA delivered
4436                 // (3) is generated and send (4) CS      -.
4437                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4438                 // know the per_commitment_point to use for it.
4439                 //                                       <- (2) commitment_signed delivered
4440                 // revoke_and_ack                        ->
4441                 //                                          B should send no response here
4442                 // (4) commitment_signed delivered       ->
4443                 //                                       <- RAA/commitment_signed delivered
4444                 // revoke_and_ack                        ->
4445
4446                 // First nodes[0] generates an update_fee
4447                 let initial_feerate = get_feerate!(nodes[0], channel_id);
4448                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4449                 check_added_monitors!(nodes[0], 1);
4450
4451                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4452                 assert_eq!(events_0.len(), 1);
4453                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4454                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4455                                 (update_fee.as_ref().unwrap(), commitment_signed)
4456                         },
4457                         _ => panic!("Unexpected event"),
4458                 };
4459
4460                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4461                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4462                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4463                 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4464                 check_added_monitors!(nodes[1], 1);
4465
4466                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4467                 // transaction:
4468                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4469                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4470                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4471
4472                 // Create the (3) update_fee message that nodes[0] will generate before it does...
4473                 let mut update_msg_2 = msgs::UpdateFee {
4474                         channel_id: update_msg_1.channel_id.clone(),
4475                         feerate_per_kw: (initial_feerate + 30) as u32,
4476                 };
4477
4478                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4479
4480                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4481                 // Deliver (3)
4482                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4483
4484                 // Deliver (1), generating (3) and (4)
4485                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4486                 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4487                 check_added_monitors!(nodes[0], 1);
4488                 assert!(as_second_update.update_add_htlcs.is_empty());
4489                 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4490                 assert!(as_second_update.update_fail_htlcs.is_empty());
4491                 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4492                 // Check that the update_fee newly generated matches what we delivered:
4493                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4494                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4495
4496                 // Deliver (2) commitment_signed
4497                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4498                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4499                 check_added_monitors!(nodes[0], 1);
4500                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4501
4502                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4503                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4504                 check_added_monitors!(nodes[1], 1);
4505
4506                 // Delever (4)
4507                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4508                 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4509                 check_added_monitors!(nodes[1], 1);
4510
4511                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4512                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4513                 check_added_monitors!(nodes[0], 1);
4514
4515                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4516                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4517                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4518                 check_added_monitors!(nodes[0], 1);
4519
4520                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4521                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4522                 check_added_monitors!(nodes[1], 1);
4523         }
4524
4525         #[test]
4526         fn test_update_fee_vanilla() {
4527                 let nodes = create_network(2);
4528                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4529                 let channel_id = chan.2;
4530
4531                 let feerate = get_feerate!(nodes[0], channel_id);
4532                 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4533                 check_added_monitors!(nodes[0], 1);
4534
4535                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4536                 assert_eq!(events_0.len(), 1);
4537                 let (update_msg, commitment_signed) = match events_0[0] {
4538                                 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 } } => {
4539                                 (update_fee.as_ref(), commitment_signed)
4540                         },
4541                         _ => panic!("Unexpected event"),
4542                 };
4543                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4544
4545                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4546                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4547                 check_added_monitors!(nodes[1], 1);
4548
4549                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4550                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4551                 check_added_monitors!(nodes[0], 1);
4552
4553                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4554                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4555                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4556                 check_added_monitors!(nodes[0], 1);
4557
4558                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4559                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4560                 check_added_monitors!(nodes[1], 1);
4561         }
4562
4563         #[test]
4564         fn test_update_fee_that_funder_cannot_afford() {
4565                 let nodes = create_network(2);
4566                 let channel_value = 1888;
4567                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4568                 let channel_id = chan.2;
4569
4570                 let feerate = 260;
4571                 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4572                 check_added_monitors!(nodes[0], 1);
4573                 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4574
4575                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4576
4577                 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4578
4579                 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4580                 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4581                 {
4582                         let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4583                         let chan = chan_lock.by_id.get(&channel_id).unwrap();
4584
4585                         //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4586                         let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4587                         let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4588                         let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4589                         actual_fee = channel_value - actual_fee;
4590                         assert_eq!(total_fee, actual_fee);
4591                 } //drop the mutex
4592
4593                 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4594                 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4595                 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4596                 check_added_monitors!(nodes[0], 1);
4597
4598                 let update2_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(), &update2_msg.update_fee.unwrap()).unwrap();
4601
4602                 //While producing the commitment_signed response after handling a received update_fee request the
4603                 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4604                 //Should produce and error.
4605                 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4606
4607                 assert!(match err.err {
4608                         "Funding remote cannot afford proposed new fee" => true,
4609                         _ => false,
4610                 });
4611
4612                 //clear the message we could not handle
4613                 nodes[1].node.get_and_clear_pending_msg_events();
4614         }
4615
4616         #[test]
4617         fn test_update_fee_with_fundee_update_add_htlc() {
4618                 let mut nodes = create_network(2);
4619                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4620                 let channel_id = chan.2;
4621
4622                 // balancing
4623                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4624
4625                 let feerate = get_feerate!(nodes[0], channel_id);
4626                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4627                 check_added_monitors!(nodes[0], 1);
4628
4629                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4630                 assert_eq!(events_0.len(), 1);
4631                 let (update_msg, commitment_signed) = match events_0[0] {
4632                                 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 } } => {
4633                                 (update_fee.as_ref(), commitment_signed)
4634                         },
4635                         _ => panic!("Unexpected event"),
4636                 };
4637                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4638                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4639                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4640                 check_added_monitors!(nodes[1], 1);
4641
4642                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4643
4644                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4645
4646                 // nothing happens since node[1] is in AwaitingRemoteRevoke
4647                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4648                 {
4649                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4650                         assert_eq!(added_monitors.len(), 0);
4651                         added_monitors.clear();
4652                 }
4653                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4654                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4655                 // node[1] has nothing to do
4656
4657                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4658                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4659                 check_added_monitors!(nodes[0], 1);
4660
4661                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4662                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4663                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4664                 check_added_monitors!(nodes[0], 1);
4665                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4666                 check_added_monitors!(nodes[1], 1);
4667                 // AwaitingRemoteRevoke ends here
4668
4669                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4670                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4671                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4672                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4673                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4674                 assert_eq!(commitment_update.update_fee.is_none(), true);
4675
4676                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4677                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4678                 check_added_monitors!(nodes[0], 1);
4679                 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4680
4681                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4682                 check_added_monitors!(nodes[1], 1);
4683                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4684
4685                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4686                 check_added_monitors!(nodes[1], 1);
4687                 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4688                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4689
4690                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4691                 check_added_monitors!(nodes[0], 1);
4692                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4693
4694                 let events = nodes[0].node.get_and_clear_pending_events();
4695                 assert_eq!(events.len(), 1);
4696                 match events[0] {
4697                         Event::PendingHTLCsForwardable { .. } => { },
4698                         _ => panic!("Unexpected event"),
4699                 };
4700                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4701                 nodes[0].node.process_pending_htlc_forwards();
4702
4703                 let events = nodes[0].node.get_and_clear_pending_events();
4704                 assert_eq!(events.len(), 1);
4705                 match events[0] {
4706                         Event::PaymentReceived { .. } => { },
4707                         _ => panic!("Unexpected event"),
4708                 };
4709
4710                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4711
4712                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4713                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4714                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4715         }
4716
4717         #[test]
4718         fn test_update_fee() {
4719                 let nodes = create_network(2);
4720                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4721                 let channel_id = chan.2;
4722
4723                 // A                                        B
4724                 // (1) update_fee/commitment_signed      ->
4725                 //                                       <- (2) revoke_and_ack
4726                 //                                       .- send (3) commitment_signed
4727                 // (4) update_fee/commitment_signed      ->
4728                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4729                 //                                       <- (3) commitment_signed delivered
4730                 // send (6) revoke_and_ack               -.
4731                 //                                       <- (5) deliver revoke_and_ack
4732                 // (6) deliver revoke_and_ack            ->
4733                 //                                       .- send (7) commitment_signed in response to (4)
4734                 //                                       <- (7) deliver commitment_signed
4735                 // revoke_and_ack                        ->
4736
4737                 // Create and deliver (1)...
4738                 let feerate = get_feerate!(nodes[0], channel_id);
4739                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4740                 check_added_monitors!(nodes[0], 1);
4741
4742                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4743                 assert_eq!(events_0.len(), 1);
4744                 let (update_msg, commitment_signed) = match events_0[0] {
4745                                 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 } } => {
4746                                 (update_fee.as_ref(), commitment_signed)
4747                         },
4748                         _ => panic!("Unexpected event"),
4749                 };
4750                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4751
4752                 // Generate (2) and (3):
4753                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4754                 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4755                 check_added_monitors!(nodes[1], 1);
4756
4757                 // Deliver (2):
4758                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4759                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4760                 check_added_monitors!(nodes[0], 1);
4761
4762                 // Create and deliver (4)...
4763                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4764                 check_added_monitors!(nodes[0], 1);
4765                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4766                 assert_eq!(events_0.len(), 1);
4767                 let (update_msg, commitment_signed) = match events_0[0] {
4768                                 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 } } => {
4769                                 (update_fee.as_ref(), commitment_signed)
4770                         },
4771                         _ => panic!("Unexpected event"),
4772                 };
4773
4774                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4775                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4776                 check_added_monitors!(nodes[1], 1);
4777                 // ... creating (5)
4778                 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4779                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4780
4781                 // Handle (3), creating (6):
4782                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4783                 check_added_monitors!(nodes[0], 1);
4784                 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4785                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4786
4787                 // Deliver (5):
4788                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4789                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4790                 check_added_monitors!(nodes[0], 1);
4791
4792                 // Deliver (6), creating (7):
4793                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4794                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4795                 assert!(commitment_update.update_add_htlcs.is_empty());
4796                 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4797                 assert!(commitment_update.update_fail_htlcs.is_empty());
4798                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4799                 assert!(commitment_update.update_fee.is_none());
4800                 check_added_monitors!(nodes[1], 1);
4801
4802                 // Deliver (7)
4803                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4804                 check_added_monitors!(nodes[0], 1);
4805                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4806                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4807
4808                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4809                 check_added_monitors!(nodes[1], 1);
4810                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4811
4812                 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4813                 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4814                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4815         }
4816
4817         #[test]
4818         fn pre_funding_lock_shutdown_test() {
4819                 // Test sending a shutdown prior to funding_locked after funding generation
4820                 let nodes = create_network(2);
4821                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4822                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4823                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4824                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4825
4826                 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4827                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4828                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4829                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4830                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4831
4832                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4833                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4834                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4835                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4836                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4837                 assert!(node_0_none.is_none());
4838
4839                 assert!(nodes[0].node.list_channels().is_empty());
4840                 assert!(nodes[1].node.list_channels().is_empty());
4841         }
4842
4843         #[test]
4844         fn updates_shutdown_wait() {
4845                 // Test sending a shutdown with outstanding updates pending
4846                 let mut nodes = create_network(3);
4847                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4848                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4849                 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4850                 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4851
4852                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4853
4854                 nodes[0].node.close_channel(&chan_1.2).unwrap();
4855                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4856                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4857                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4858                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4859
4860                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4861                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4862
4863                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4864                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4865                 else { panic!("New sends should fail!") };
4866                 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4867                 else { panic!("New sends should fail!") };
4868
4869                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4870                 check_added_monitors!(nodes[2], 1);
4871                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4872                 assert!(updates.update_add_htlcs.is_empty());
4873                 assert!(updates.update_fail_htlcs.is_empty());
4874                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4875                 assert!(updates.update_fee.is_none());
4876                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4877                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4878                 check_added_monitors!(nodes[1], 1);
4879                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4880                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4881
4882                 assert!(updates_2.update_add_htlcs.is_empty());
4883                 assert!(updates_2.update_fail_htlcs.is_empty());
4884                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4885                 assert!(updates_2.update_fee.is_none());
4886                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4887                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4888                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4889
4890                 let events = nodes[0].node.get_and_clear_pending_events();
4891                 assert_eq!(events.len(), 1);
4892                 match events[0] {
4893                         Event::PaymentSent { ref payment_preimage } => {
4894                                 assert_eq!(our_payment_preimage, *payment_preimage);
4895                         },
4896                         _ => panic!("Unexpected event"),
4897                 }
4898
4899                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4900                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4901                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4902                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4903                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4904                 assert!(node_0_none.is_none());
4905
4906                 assert!(nodes[0].node.list_channels().is_empty());
4907
4908                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4909                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4910                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4911                 assert!(nodes[1].node.list_channels().is_empty());
4912                 assert!(nodes[2].node.list_channels().is_empty());
4913         }
4914
4915         #[test]
4916         fn htlc_fail_async_shutdown() {
4917                 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4918                 let mut nodes = create_network(3);
4919                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4920                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4921
4922                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4923                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4924                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4925                 check_added_monitors!(nodes[0], 1);
4926                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4927                 assert_eq!(updates.update_add_htlcs.len(), 1);
4928                 assert!(updates.update_fulfill_htlcs.is_empty());
4929                 assert!(updates.update_fail_htlcs.is_empty());
4930                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4931                 assert!(updates.update_fee.is_none());
4932
4933                 nodes[1].node.close_channel(&chan_1.2).unwrap();
4934                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4935                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4936                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4937
4938                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
4939                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
4940                 check_added_monitors!(nodes[1], 1);
4941                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4942                 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
4943
4944                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4945                 assert!(updates_2.update_add_htlcs.is_empty());
4946                 assert!(updates_2.update_fulfill_htlcs.is_empty());
4947                 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
4948                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4949                 assert!(updates_2.update_fee.is_none());
4950
4951                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
4952                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4953
4954                 let events = nodes[0].node.get_and_clear_pending_events();
4955                 assert_eq!(events.len(), 1);
4956                 match events[0] {
4957                         Event::PaymentFailed { ref payment_hash, ref rejected_by_dest } => {
4958                                 assert_eq!(our_payment_hash, *payment_hash);
4959                                 assert!(!rejected_by_dest);
4960                         },
4961                         _ => panic!("Unexpected event"),
4962                 }
4963
4964                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4965                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4966                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4967                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4968                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4969                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4970                 assert!(node_0_none.is_none());
4971
4972                 assert!(nodes[0].node.list_channels().is_empty());
4973
4974                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4975                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4976                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4977                 assert!(nodes[1].node.list_channels().is_empty());
4978                 assert!(nodes[2].node.list_channels().is_empty());
4979         }
4980
4981         #[test]
4982         fn update_fee_async_shutdown() {
4983                 // Test update_fee works after shutdown start if messages are delivered out-of-order
4984                 let nodes = create_network(2);
4985                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4986
4987                 let starting_feerate = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().get_feerate();
4988                 nodes[0].node.update_fee(chan_1.2.clone(), starting_feerate + 20).unwrap();
4989                 check_added_monitors!(nodes[0], 1);
4990                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4991                 assert!(updates.update_add_htlcs.is_empty());
4992                 assert!(updates.update_fulfill_htlcs.is_empty());
4993                 assert!(updates.update_fail_htlcs.is_empty());
4994                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4995                 assert!(updates.update_fee.is_some());
4996
4997                 nodes[1].node.close_channel(&chan_1.2).unwrap();
4998                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4999                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5000                 // Note that we don't actually test normative behavior here. The spec indicates we could
5001                 // actually send a closing_signed here, but is kinda unclear and could possibly be amended
5002                 // to require waiting on the full commitment dance before doing so (see
5003                 // https://github.com/lightningnetwork/lightning-rfc/issues/499). In any case, to avoid
5004                 // ambiguity, we should wait until after the full commitment dance to send closing_signed.
5005                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5006
5007                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &updates.update_fee.unwrap()).unwrap();
5008                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
5009                 check_added_monitors!(nodes[1], 1);
5010                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5011                 let node_0_closing_signed = commitment_signed_dance!(nodes[1], nodes[0], (), false, true, true);
5012
5013                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5014                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), match node_0_closing_signed.unwrap() {
5015                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
5016                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5017                                 msg
5018                         },
5019                         _ => panic!("Unexpected event"),
5020                 }).unwrap();
5021                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5022                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5023                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5024                 assert!(node_0_none.is_none());
5025         }
5026
5027         fn do_test_shutdown_rebroadcast(recv_count: u8) {
5028                 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5029                 // messages delivered prior to disconnect
5030                 let nodes = create_network(3);
5031                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5032                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5033
5034                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5035
5036                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5037                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5038                 if recv_count > 0 {
5039                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5040                         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5041                         if recv_count > 1 {
5042                                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5043                         }
5044                 }
5045
5046                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5047                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5048
5049                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5050                 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5051                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5052                 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5053
5054                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5055                 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5056                 assert!(node_1_shutdown == node_1_2nd_shutdown);
5057
5058                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5059                 let node_0_2nd_shutdown = if recv_count > 0 {
5060                         let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5061                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5062                         node_0_2nd_shutdown
5063                 } else {
5064                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5065                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5066                         get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5067                 };
5068                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5069
5070                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5071                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5072
5073                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5074                 check_added_monitors!(nodes[2], 1);
5075                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5076                 assert!(updates.update_add_htlcs.is_empty());
5077                 assert!(updates.update_fail_htlcs.is_empty());
5078                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5079                 assert!(updates.update_fee.is_none());
5080                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5081                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5082                 check_added_monitors!(nodes[1], 1);
5083                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5084                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5085
5086                 assert!(updates_2.update_add_htlcs.is_empty());
5087                 assert!(updates_2.update_fail_htlcs.is_empty());
5088                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5089                 assert!(updates_2.update_fee.is_none());
5090                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5091                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5092                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5093
5094                 let events = nodes[0].node.get_and_clear_pending_events();
5095                 assert_eq!(events.len(), 1);
5096                 match events[0] {
5097                         Event::PaymentSent { ref payment_preimage } => {
5098                                 assert_eq!(our_payment_preimage, *payment_preimage);
5099                         },
5100                         _ => panic!("Unexpected event"),
5101                 }
5102
5103                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5104                 if recv_count > 0 {
5105                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5106                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5107                         assert!(node_1_closing_signed.is_some());
5108                 }
5109
5110                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5111                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5112
5113                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5114                 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5115                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5116                 if recv_count == 0 {
5117                         // If all closing_signeds weren't delivered we can just resume where we left off...
5118                         let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5119
5120                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5121                         let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5122                         assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5123
5124                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5125                         let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5126                         assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5127
5128                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5129                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5130
5131                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5132                         let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5133                         assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5134
5135                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5136                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5137                         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5138                         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5139                         assert!(node_0_none.is_none());
5140                 } else {
5141                         // If one node, however, received + responded with an identical closing_signed we end
5142                         // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5143                         // There isn't really anything better we can do simply, but in the future we might
5144                         // explore storing a set of recently-closed channels that got disconnected during
5145                         // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5146                         // give our counterparty enough time to (potentially) broadcast a cooperative closing
5147                         // transaction.
5148                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5149
5150                         if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5151                                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5152                                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5153                                 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5154                                 assert_eq!(*channel_id, chan_1.2);
5155                         } else { panic!("Needed SendErrorMessage close"); }
5156
5157                         // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5158                         // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5159                         // closing_signed so we do it ourselves
5160                         let events = nodes[0].node.get_and_clear_pending_msg_events();
5161                         assert_eq!(events.len(), 1);
5162                         match events[0] {
5163                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5164                                         assert_eq!(msg.contents.flags & 2, 2);
5165                                 },
5166                                 _ => panic!("Unexpected event"),
5167                         }
5168                 }
5169
5170                 assert!(nodes[0].node.list_channels().is_empty());
5171
5172                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5173                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5174                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5175                 assert!(nodes[1].node.list_channels().is_empty());
5176                 assert!(nodes[2].node.list_channels().is_empty());
5177         }
5178
5179         #[test]
5180         fn test_shutdown_rebroadcast() {
5181                 do_test_shutdown_rebroadcast(0);
5182                 do_test_shutdown_rebroadcast(1);
5183                 do_test_shutdown_rebroadcast(2);
5184         }
5185
5186         #[test]
5187         fn fake_network_test() {
5188                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5189                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5190                 let nodes = create_network(4);
5191
5192                 // Create some initial channels
5193                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5194                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5195                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5196
5197                 // Rebalance the network a bit by relaying one payment through all the channels...
5198                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5199                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5200                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5201                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5202
5203                 // Send some more payments
5204                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5205                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5206                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5207
5208                 // Test failure packets
5209                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5210                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5211
5212                 // Add a new channel that skips 3
5213                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5214
5215                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5216                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5217                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5218                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5219                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5220                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5221                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5222
5223                 // Do some rebalance loop payments, simultaneously
5224                 let mut hops = Vec::with_capacity(3);
5225                 hops.push(RouteHop {
5226                         pubkey: nodes[2].node.get_our_node_id(),
5227                         short_channel_id: chan_2.0.contents.short_channel_id,
5228                         fee_msat: 0,
5229                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5230                 });
5231                 hops.push(RouteHop {
5232                         pubkey: nodes[3].node.get_our_node_id(),
5233                         short_channel_id: chan_3.0.contents.short_channel_id,
5234                         fee_msat: 0,
5235                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5236                 });
5237                 hops.push(RouteHop {
5238                         pubkey: nodes[1].node.get_our_node_id(),
5239                         short_channel_id: chan_4.0.contents.short_channel_id,
5240                         fee_msat: 1000000,
5241                         cltv_expiry_delta: TEST_FINAL_CLTV,
5242                 });
5243                 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;
5244                 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;
5245                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5246
5247                 let mut hops = Vec::with_capacity(3);
5248                 hops.push(RouteHop {
5249                         pubkey: nodes[3].node.get_our_node_id(),
5250                         short_channel_id: chan_4.0.contents.short_channel_id,
5251                         fee_msat: 0,
5252                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5253                 });
5254                 hops.push(RouteHop {
5255                         pubkey: nodes[2].node.get_our_node_id(),
5256                         short_channel_id: chan_3.0.contents.short_channel_id,
5257                         fee_msat: 0,
5258                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5259                 });
5260                 hops.push(RouteHop {
5261                         pubkey: nodes[1].node.get_our_node_id(),
5262                         short_channel_id: chan_2.0.contents.short_channel_id,
5263                         fee_msat: 1000000,
5264                         cltv_expiry_delta: TEST_FINAL_CLTV,
5265                 });
5266                 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;
5267                 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;
5268                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5269
5270                 // Claim the rebalances...
5271                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5272                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5273
5274                 // Add a duplicate new channel from 2 to 4
5275                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5276
5277                 // Send some payments across both channels
5278                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5279                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5280                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5281
5282                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5283
5284                 //TODO: Test that routes work again here as we've been notified that the channel is full
5285
5286                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5287                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5288                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5289
5290                 // Close down the channels...
5291                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5292                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5293                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5294                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5295                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5296         }
5297
5298         #[test]
5299         fn duplicate_htlc_test() {
5300                 // Test that we accept duplicate payment_hash HTLCs across the network and that
5301                 // claiming/failing them are all separate and don't effect each other
5302                 let mut nodes = create_network(6);
5303
5304                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5305                 create_announced_chan_between_nodes(&nodes, 0, 3);
5306                 create_announced_chan_between_nodes(&nodes, 1, 3);
5307                 create_announced_chan_between_nodes(&nodes, 2, 3);
5308                 create_announced_chan_between_nodes(&nodes, 3, 4);
5309                 create_announced_chan_between_nodes(&nodes, 3, 5);
5310
5311                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5312
5313                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5314                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5315
5316                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5317                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5318
5319                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5320                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5321                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5322         }
5323
5324         #[derive(PartialEq)]
5325         enum HTLCType { NONE, TIMEOUT, SUCCESS }
5326         /// Tests that the given node has broadcast transactions for the given Channel
5327         ///
5328         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5329         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5330         /// broadcast and the revoked outputs were claimed.
5331         ///
5332         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5333         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5334         ///
5335         /// All broadcast transactions must be accounted for in one of the above three types of we'll
5336         /// also fail.
5337         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5338                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5339                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5340
5341                 let mut res = Vec::with_capacity(2);
5342                 node_txn.retain(|tx| {
5343                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5344                                 check_spends!(tx, chan.3.clone());
5345                                 if commitment_tx.is_none() {
5346                                         res.push(tx.clone());
5347                                 }
5348                                 false
5349                         } else { true }
5350                 });
5351                 if let Some(explicit_tx) = commitment_tx {
5352                         res.push(explicit_tx.clone());
5353                 }
5354
5355                 assert_eq!(res.len(), 1);
5356
5357                 if has_htlc_tx != HTLCType::NONE {
5358                         node_txn.retain(|tx| {
5359                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5360                                         check_spends!(tx, res[0].clone());
5361                                         if has_htlc_tx == HTLCType::TIMEOUT {
5362                                                 assert!(tx.lock_time != 0);
5363                                         } else {
5364                                                 assert!(tx.lock_time == 0);
5365                                         }
5366                                         res.push(tx.clone());
5367                                         false
5368                                 } else { true }
5369                         });
5370                         assert_eq!(res.len(), 2);
5371                 }
5372
5373                 assert!(node_txn.is_empty());
5374                 res
5375         }
5376
5377         /// Tests that the given node has broadcast a claim transaction against the provided revoked
5378         /// HTLC transaction.
5379         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5380                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5381                 assert_eq!(node_txn.len(), 1);
5382                 node_txn.retain(|tx| {
5383                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5384                                 check_spends!(tx, revoked_tx.clone());
5385                                 false
5386                         } else { true }
5387                 });
5388                 assert!(node_txn.is_empty());
5389         }
5390
5391         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5392                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5393
5394                 assert!(node_txn.len() >= 1);
5395                 assert_eq!(node_txn[0].input.len(), 1);
5396                 let mut found_prev = false;
5397
5398                 for tx in prev_txn {
5399                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
5400                                 check_spends!(node_txn[0], tx.clone());
5401                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5402                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5403
5404                                 found_prev = true;
5405                                 break;
5406                         }
5407                 }
5408                 assert!(found_prev);
5409
5410                 let mut res = Vec::new();
5411                 mem::swap(&mut *node_txn, &mut res);
5412                 res
5413         }
5414
5415         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5416                 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5417                 assert_eq!(events_1.len(), 1);
5418                 let as_update = match events_1[0] {
5419                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5420                                 msg.clone()
5421                         },
5422                         _ => panic!("Unexpected event"),
5423                 };
5424
5425                 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5426                 assert_eq!(events_2.len(), 1);
5427                 let bs_update = match events_2[0] {
5428                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5429                                 msg.clone()
5430                         },
5431                         _ => panic!("Unexpected event"),
5432                 };
5433
5434                 for node in nodes {
5435                         node.router.handle_channel_update(&as_update).unwrap();
5436                         node.router.handle_channel_update(&bs_update).unwrap();
5437                 }
5438         }
5439
5440         macro_rules! expect_pending_htlcs_forwardable {
5441                 ($node: expr) => {{
5442                         let events = $node.node.get_and_clear_pending_events();
5443                         assert_eq!(events.len(), 1);
5444                         match events[0] {
5445                                 Event::PendingHTLCsForwardable { .. } => { },
5446                                 _ => panic!("Unexpected event"),
5447                         };
5448                         $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5449                         $node.node.process_pending_htlc_forwards();
5450                 }}
5451         }
5452
5453         fn do_channel_reserve_test(test_recv: bool) {
5454                 use util::rng;
5455                 use std::sync::atomic::Ordering;
5456                 use ln::msgs::HandleError;
5457
5458                 macro_rules! get_channel_value_stat {
5459                         ($node: expr, $channel_id: expr) => {{
5460                                 let chan_lock = $node.node.channel_state.lock().unwrap();
5461                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5462                                 chan.get_value_stat()
5463                         }}
5464                 }
5465
5466                 let mut nodes = create_network(3);
5467                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5468                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5469
5470                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5471                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5472
5473                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5474                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5475
5476                 macro_rules! get_route_and_payment_hash {
5477                         ($recv_value: expr) => {{
5478                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5479                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5480                                 (route, payment_hash, payment_preimage)
5481                         }}
5482                 };
5483
5484                 macro_rules! expect_forward {
5485                         ($node: expr) => {{
5486                                 let mut events = $node.node.get_and_clear_pending_msg_events();
5487                                 assert_eq!(events.len(), 1);
5488                                 check_added_monitors!($node, 1);
5489                                 let payment_event = SendEvent::from_event(events.remove(0));
5490                                 payment_event
5491                         }}
5492                 }
5493
5494                 macro_rules! expect_payment_received {
5495                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5496                                 let events = $node.node.get_and_clear_pending_events();
5497                                 assert_eq!(events.len(), 1);
5498                                 match events[0] {
5499                                         Event::PaymentReceived { ref payment_hash, amt } => {
5500                                                 assert_eq!($expected_payment_hash, *payment_hash);
5501                                                 assert_eq!($expected_recv_value, amt);
5502                                         },
5503                                         _ => panic!("Unexpected event"),
5504                                 }
5505                         }
5506                 };
5507
5508                 let feemsat = 239; // somehow we know?
5509                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5510
5511                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5512
5513                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5514                 {
5515                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5516                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5517                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5518                         match err {
5519                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5520                                 _ => panic!("Unknown error variants"),
5521                         }
5522                 }
5523
5524                 let mut htlc_id = 0;
5525                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5526                 // nodes[0]'s wealth
5527                 loop {
5528                         let amt_msat = recv_value_0 + total_fee_msat;
5529                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5530                                 break;
5531                         }
5532                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5533                         htlc_id += 1;
5534
5535                         let (stat01_, stat11_, stat12_, stat22_) = (
5536                                 get_channel_value_stat!(nodes[0], chan_1.2),
5537                                 get_channel_value_stat!(nodes[1], chan_1.2),
5538                                 get_channel_value_stat!(nodes[1], chan_2.2),
5539                                 get_channel_value_stat!(nodes[2], chan_2.2),
5540                         );
5541
5542                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5543                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5544                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5545                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5546                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5547                 }
5548
5549                 {
5550                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5551                         // attempt to get channel_reserve violation
5552                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5553                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5554                         match err {
5555                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5556                                 _ => panic!("Unknown error variants"),
5557                         }
5558                 }
5559
5560                 // adding pending output
5561                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5562                 let amt_msat_1 = recv_value_1 + total_fee_msat;
5563
5564                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5565                 let payment_event_1 = {
5566                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5567                         check_added_monitors!(nodes[0], 1);
5568
5569                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5570                         assert_eq!(events.len(), 1);
5571                         SendEvent::from_event(events.remove(0))
5572                 };
5573                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5574
5575                 // channel reserve test with htlc pending output > 0
5576                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5577                 {
5578                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5579                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5580                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5581                                 _ => panic!("Unknown error variants"),
5582                         }
5583                 }
5584
5585                 {
5586                         // test channel_reserve test on nodes[1] side
5587                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5588
5589                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5590                         let secp_ctx = Secp256k1::new();
5591                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
5592                                 let mut session_key = [0; 32];
5593                                 rng::fill_bytes(&mut session_key);
5594                                 session_key
5595                         }).expect("RNG is bad!");
5596
5597                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5598                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5599                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5600                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5601                         let msg = msgs::UpdateAddHTLC {
5602                                 channel_id: chan_1.2,
5603                                 htlc_id,
5604                                 amount_msat: htlc_msat,
5605                                 payment_hash: our_payment_hash,
5606                                 cltv_expiry: htlc_cltv,
5607                                 onion_routing_packet: onion_packet,
5608                         };
5609
5610                         if test_recv {
5611                                 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5612                                 match err {
5613                                         HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5614                                 }
5615                                 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5616                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5617                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5618                                 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5619                                 assert_eq!(channel_close_broadcast.len(), 1);
5620                                 match channel_close_broadcast[0] {
5621                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5622                                                 assert_eq!(msg.contents.flags & 2, 2);
5623                                         },
5624                                         _ => panic!("Unexpected event"),
5625                                 }
5626                                 return;
5627                         }
5628                 }
5629
5630                 // split the rest to test holding cell
5631                 let recv_value_21 = recv_value_2/2;
5632                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5633                 {
5634                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5635                         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);
5636                 }
5637
5638                 // now see if they go through on both sides
5639                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5640                 // but this will stuck in the holding cell
5641                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5642                 check_added_monitors!(nodes[0], 0);
5643                 let events = nodes[0].node.get_and_clear_pending_events();
5644                 assert_eq!(events.len(), 0);
5645
5646                 // test with outbound holding cell amount > 0
5647                 {
5648                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5649                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5650                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5651                                 _ => panic!("Unknown error variants"),
5652                         }
5653                 }
5654
5655                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5656                 // this will also stuck in the holding cell
5657                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5658                 check_added_monitors!(nodes[0], 0);
5659                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5660                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5661
5662                 // flush the pending htlc
5663                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5664                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5665                 check_added_monitors!(nodes[1], 1);
5666
5667                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5668                 check_added_monitors!(nodes[0], 1);
5669                 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5670
5671                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5672                 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5673                 // No commitment_signed so get_event_msg's assert(len == 1) passes
5674                 check_added_monitors!(nodes[0], 1);
5675
5676                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5677                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5678                 check_added_monitors!(nodes[1], 1);
5679
5680                 expect_pending_htlcs_forwardable!(nodes[1]);
5681
5682                 let ref payment_event_11 = expect_forward!(nodes[1]);
5683                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5684                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5685
5686                 expect_pending_htlcs_forwardable!(nodes[2]);
5687                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5688
5689                 // flush the htlcs in the holding cell
5690                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5691                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5692                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5693                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5694                 expect_pending_htlcs_forwardable!(nodes[1]);
5695
5696                 let ref payment_event_3 = expect_forward!(nodes[1]);
5697                 assert_eq!(payment_event_3.msgs.len(), 2);
5698                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5699                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5700
5701                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5702                 expect_pending_htlcs_forwardable!(nodes[2]);
5703
5704                 let events = nodes[2].node.get_and_clear_pending_events();
5705                 assert_eq!(events.len(), 2);
5706                 match events[0] {
5707                         Event::PaymentReceived { ref payment_hash, amt } => {
5708                                 assert_eq!(our_payment_hash_21, *payment_hash);
5709                                 assert_eq!(recv_value_21, amt);
5710                         },
5711                         _ => panic!("Unexpected event"),
5712                 }
5713                 match events[1] {
5714                         Event::PaymentReceived { ref payment_hash, amt } => {
5715                                 assert_eq!(our_payment_hash_22, *payment_hash);
5716                                 assert_eq!(recv_value_22, amt);
5717                         },
5718                         _ => panic!("Unexpected event"),
5719                 }
5720
5721                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5722                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5723                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5724
5725                 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);
5726                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5727                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5728                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5729
5730                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5731                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5732         }
5733
5734         #[test]
5735         fn channel_reserve_test() {
5736                 do_channel_reserve_test(false);
5737                 do_channel_reserve_test(true);
5738         }
5739
5740         #[test]
5741         fn channel_monitor_network_test() {
5742                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5743                 // tests that ChannelMonitor is able to recover from various states.
5744                 let nodes = create_network(5);
5745
5746                 // Create some initial channels
5747                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5748                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5749                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5750                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5751
5752                 // Rebalance the network a bit by relaying one payment through all the channels...
5753                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5754                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5755                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5756                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5757
5758                 // Simple case with no pending HTLCs:
5759                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5760                 {
5761                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5762                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5763                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5764                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5765                 }
5766                 get_announce_close_broadcast_events(&nodes, 0, 1);
5767                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5768                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5769
5770                 // One pending HTLC is discarded by the force-close:
5771                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5772
5773                 // Simple case of one pending HTLC to HTLC-Timeout
5774                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5775                 {
5776                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5777                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5778                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5779                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5780                 }
5781                 get_announce_close_broadcast_events(&nodes, 1, 2);
5782                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5783                 assert_eq!(nodes[2].node.list_channels().len(), 1);
5784
5785                 macro_rules! claim_funds {
5786                         ($node: expr, $prev_node: expr, $preimage: expr) => {
5787                                 {
5788                                         assert!($node.node.claim_funds($preimage));
5789                                         check_added_monitors!($node, 1);
5790
5791                                         let events = $node.node.get_and_clear_pending_msg_events();
5792                                         assert_eq!(events.len(), 1);
5793                                         match events[0] {
5794                                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5795                                                         assert!(update_add_htlcs.is_empty());
5796                                                         assert!(update_fail_htlcs.is_empty());
5797                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5798                                                 },
5799                                                 _ => panic!("Unexpected event"),
5800                                         };
5801                                 }
5802                         }
5803                 }
5804
5805                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5806                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5807                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5808                 {
5809                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5810
5811                         // Claim the payment on nodes[3], giving it knowledge of the preimage
5812                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5813
5814                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5815                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5816
5817                         check_preimage_claim(&nodes[3], &node_txn);
5818                 }
5819                 get_announce_close_broadcast_events(&nodes, 2, 3);
5820                 assert_eq!(nodes[2].node.list_channels().len(), 0);
5821                 assert_eq!(nodes[3].node.list_channels().len(), 1);
5822
5823                 { // Cheat and reset nodes[4]'s height to 1
5824                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5825                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5826                 }
5827
5828                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5829                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5830                 // One pending HTLC to time out:
5831                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5832                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5833                 // buffer space).
5834
5835                 {
5836                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5837                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5838                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5839                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5840                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5841                         }
5842
5843                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5844
5845                         // Claim the payment on nodes[4], giving it knowledge of the preimage
5846                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5847
5848                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5849                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5850                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5851                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5852                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5853                         }
5854
5855                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5856
5857                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5858                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5859
5860                         check_preimage_claim(&nodes[4], &node_txn);
5861                 }
5862                 get_announce_close_broadcast_events(&nodes, 3, 4);
5863                 assert_eq!(nodes[3].node.list_channels().len(), 0);
5864                 assert_eq!(nodes[4].node.list_channels().len(), 0);
5865         }
5866
5867         #[test]
5868         fn test_justice_tx() {
5869                 // Test justice txn built on revoked HTLC-Success tx, against both sides
5870
5871                 let nodes = create_network(2);
5872                 // Create some new channels:
5873                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5874
5875                 // A pending HTLC which will be revoked:
5876                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5877                 // Get the will-be-revoked local txn from nodes[0]
5878                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5879                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5880                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5881                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5882                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5883                 assert_eq!(revoked_local_txn[1].input.len(), 1);
5884                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5885                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), 133); // HTLC-Timeout
5886                 // Revoke the old state
5887                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5888
5889                 {
5890                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5891                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5892                         {
5893                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5894                                 assert_eq!(node_txn.len(), 3);
5895                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5896                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5897
5898                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5899                                 node_txn.swap_remove(0);
5900                         }
5901                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5902
5903                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5904                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5905                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5906                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5907                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5908                 }
5909                 get_announce_close_broadcast_events(&nodes, 0, 1);
5910
5911                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5912                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5913
5914                 // We test justice_tx build by A on B's revoked HTLC-Success tx
5915                 // Create some new channels:
5916                 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5917
5918                 // A pending HTLC which will be revoked:
5919                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5920                 // Get the will-be-revoked local txn from B
5921                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5922                 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5923                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5924                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5925                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5926                 // Revoke the old state
5927                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5928                 {
5929                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5930                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5931                         {
5932                                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5933                                 assert_eq!(node_txn.len(), 3);
5934                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5935                                 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5936
5937                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5938                                 node_txn.swap_remove(0);
5939                         }
5940                         test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5941
5942                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5943                         let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5944                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5945                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5946                         test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5947                 }
5948                 get_announce_close_broadcast_events(&nodes, 0, 1);
5949                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5950                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5951         }
5952
5953         #[test]
5954         fn revoked_output_claim() {
5955                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5956                 // transaction is broadcast by its counterparty
5957                 let nodes = create_network(2);
5958                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5959                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5960                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5961                 assert_eq!(revoked_local_txn.len(), 1);
5962                 // Only output is the full channel value back to nodes[0]:
5963                 assert_eq!(revoked_local_txn[0].output.len(), 1);
5964                 // Send a payment through, updating everyone's latest commitment txn
5965                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5966
5967                 // Inform nodes[1] that nodes[0] broadcast a stale tx
5968                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5969                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5970                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5971                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
5972
5973                 assert_eq!(node_txn[0], node_txn[2]);
5974
5975                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5976                 check_spends!(node_txn[1], chan_1.3.clone());
5977
5978                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
5979                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5980                 get_announce_close_broadcast_events(&nodes, 0, 1);
5981         }
5982
5983         #[test]
5984         fn claim_htlc_outputs_shared_tx() {
5985                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
5986                 let nodes = create_network(2);
5987
5988                 // Create some new channel:
5989                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5990
5991                 // Rebalance the network to generate htlc in the two directions
5992                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5993                 // 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
5994                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5995                 let _payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
5996
5997                 // Get the will-be-revoked local txn from node[0]
5998                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5999                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6000                 assert_eq!(revoked_local_txn[0].input.len(), 1);
6001                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6002                 assert_eq!(revoked_local_txn[1].input.len(), 1);
6003                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6004                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), 133); // HTLC-Timeout
6005                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6006
6007                 //Revoke the old state
6008                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6009
6010                 {
6011                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6012
6013                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6014
6015                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6016                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6017                         assert_eq!(node_txn.len(), 4);
6018
6019                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6020                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
6021
6022                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6023
6024                         let mut witness_lens = BTreeSet::new();
6025                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6026                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6027                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6028                         assert_eq!(witness_lens.len(), 3);
6029                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6030                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), 133); // revoked offered HTLC
6031                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), 138); // revoked received HTLC
6032
6033                         // Next nodes[1] broadcasts its current local tx state:
6034                         assert_eq!(node_txn[1].input.len(), 1);
6035                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6036
6037                         assert_eq!(node_txn[2].input.len(), 1);
6038                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6039                         assert_eq!(witness_script.len(), 133); //Spending an offered htlc output
6040                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6041                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6042                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6043                 }
6044                 get_announce_close_broadcast_events(&nodes, 0, 1);
6045                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6046                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6047         }
6048
6049         #[test]
6050         fn claim_htlc_outputs_single_tx() {
6051                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6052                 let nodes = create_network(2);
6053
6054                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6055
6056                 // Rebalance the network to generate htlc in the two directions
6057                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6058                 // 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
6059                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6060                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6061                 let _payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
6062
6063                 // Get the will-be-revoked local txn from node[0]
6064                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6065
6066                 //Revoke the old state
6067                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6068
6069                 {
6070                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6071
6072                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6073
6074                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6075                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6076                         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)
6077
6078                         assert_eq!(node_txn[0], node_txn[7]);
6079                         assert_eq!(node_txn[1], node_txn[8]);
6080                         assert_eq!(node_txn[2], node_txn[9]);
6081                         assert_eq!(node_txn[3], node_txn[10]);
6082                         assert_eq!(node_txn[4], node_txn[11]);
6083                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6084                         assert_eq!(node_txn[4], node_txn[6]);
6085
6086                         assert_eq!(node_txn[0].input.len(), 1);
6087                         assert_eq!(node_txn[1].input.len(), 1);
6088                         assert_eq!(node_txn[2].input.len(), 1);
6089
6090                         let mut revoked_tx_map = HashMap::new();
6091                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6092                         node_txn[0].verify(&revoked_tx_map).unwrap();
6093                         node_txn[1].verify(&revoked_tx_map).unwrap();
6094                         node_txn[2].verify(&revoked_tx_map).unwrap();
6095
6096                         let mut witness_lens = BTreeSet::new();
6097                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6098                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6099                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6100                         assert_eq!(witness_lens.len(), 3);
6101                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6102                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), 133); // revoked offered HTLC
6103                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), 138); // revoked received HTLC
6104
6105                         assert_eq!(node_txn[3].input.len(), 1);
6106                         check_spends!(node_txn[3], chan_1.3.clone());
6107
6108                         assert_eq!(node_txn[4].input.len(), 1);
6109                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
6110                         assert_eq!(witness_script.len(), 133); //Spending an offered htlc output
6111                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6112                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6113                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6114                 }
6115                 get_announce_close_broadcast_events(&nodes, 0, 1);
6116                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6117                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6118         }
6119
6120         #[test]
6121         fn test_htlc_ignore_latest_remote_commitment() {
6122                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6123                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6124                 let nodes = create_network(2);
6125                 create_announced_chan_between_nodes(&nodes, 0, 1);
6126
6127                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6128                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6129                 {
6130                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6131                         assert_eq!(events.len(), 1);
6132                         match events[0] {
6133                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6134                                         assert_eq!(flags & 0b10, 0b10);
6135                                 },
6136                                 _ => panic!("Unexpected event"),
6137                         }
6138                 }
6139
6140                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6141                 assert_eq!(node_txn.len(), 2);
6142
6143                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6144                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6145
6146                 {
6147                         let events = nodes[1].node.get_and_clear_pending_msg_events();
6148                         assert_eq!(events.len(), 1);
6149                         match events[0] {
6150                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6151                                         assert_eq!(flags & 0b10, 0b10);
6152                                 },
6153                                 _ => panic!("Unexpected event"),
6154                         }
6155                 }
6156
6157                 // Duplicate the block_connected call since this may happen due to other listeners
6158                 // registering new transactions
6159                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6160         }
6161
6162         #[test]
6163         fn test_force_close_fail_back() {
6164                 // Check which HTLCs are failed-backwards on channel force-closure
6165                 let mut nodes = create_network(3);
6166                 create_announced_chan_between_nodes(&nodes, 0, 1);
6167                 create_announced_chan_between_nodes(&nodes, 1, 2);
6168
6169                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6170
6171                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6172
6173                 let mut payment_event = {
6174                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6175                         check_added_monitors!(nodes[0], 1);
6176
6177                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6178                         assert_eq!(events.len(), 1);
6179                         SendEvent::from_event(events.remove(0))
6180                 };
6181
6182                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6183                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6184
6185                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6186                 assert_eq!(events_1.len(), 1);
6187                 match events_1[0] {
6188                         Event::PendingHTLCsForwardable { .. } => { },
6189                         _ => panic!("Unexpected event"),
6190                 };
6191
6192                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6193                 nodes[1].node.process_pending_htlc_forwards();
6194
6195                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6196                 assert_eq!(events_2.len(), 1);
6197                 payment_event = SendEvent::from_event(events_2.remove(0));
6198                 assert_eq!(payment_event.msgs.len(), 1);
6199
6200                 check_added_monitors!(nodes[1], 1);
6201                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6202                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6203                 check_added_monitors!(nodes[2], 1);
6204                 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6205
6206                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6207                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6208                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6209
6210                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6211                 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6212                 assert_eq!(events_3.len(), 1);
6213                 match events_3[0] {
6214                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6215                                 assert_eq!(flags & 0b10, 0b10);
6216                         },
6217                         _ => panic!("Unexpected event"),
6218                 }
6219
6220                 let tx = {
6221                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6222                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6223                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6224                         // back to nodes[1] upon timeout otherwise.
6225                         assert_eq!(node_txn.len(), 1);
6226                         node_txn.remove(0)
6227                 };
6228
6229                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6230                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6231
6232                 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6233                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6234                 assert_eq!(events_4.len(), 1);
6235                 match events_4[0] {
6236                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6237                                 assert_eq!(flags & 0b10, 0b10);
6238                         },
6239                         _ => panic!("Unexpected event"),
6240                 }
6241
6242                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6243                 {
6244                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6245                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6246                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6247                 }
6248                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6249                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6250                 assert_eq!(node_txn.len(), 1);
6251                 assert_eq!(node_txn[0].input.len(), 1);
6252                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6253                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6254                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6255
6256                 check_spends!(node_txn[0], tx);
6257         }
6258
6259         #[test]
6260         fn test_unconf_chan() {
6261                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6262                 let nodes = create_network(2);
6263                 create_announced_chan_between_nodes(&nodes, 0, 1);
6264
6265                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6266                 assert_eq!(channel_state.by_id.len(), 1);
6267                 assert_eq!(channel_state.short_to_id.len(), 1);
6268                 mem::drop(channel_state);
6269
6270                 let mut headers = Vec::new();
6271                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6272                 headers.push(header.clone());
6273                 for _i in 2..100 {
6274                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6275                         headers.push(header.clone());
6276                 }
6277                 while !headers.is_empty() {
6278                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
6279                 }
6280                 {
6281                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6282                         assert_eq!(events.len(), 1);
6283                         match events[0] {
6284                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6285                                         assert_eq!(flags & 0b10, 0b10);
6286                                 },
6287                                 _ => panic!("Unexpected event"),
6288                         }
6289                 }
6290                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6291                 assert_eq!(channel_state.by_id.len(), 0);
6292                 assert_eq!(channel_state.short_to_id.len(), 0);
6293         }
6294
6295         macro_rules! get_chan_reestablish_msgs {
6296                 ($src_node: expr, $dst_node: expr) => {
6297                         {
6298                                 let mut res = Vec::with_capacity(1);
6299                                 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6300                                         if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6301                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6302                                                 res.push(msg.clone());
6303                                         } else {
6304                                                 panic!("Unexpected event")
6305                                         }
6306                                 }
6307                                 res
6308                         }
6309                 }
6310         }
6311
6312         macro_rules! handle_chan_reestablish_msgs {
6313                 ($src_node: expr, $dst_node: expr) => {
6314                         {
6315                                 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6316                                 let mut idx = 0;
6317                                 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6318                                         idx += 1;
6319                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6320                                         Some(msg.clone())
6321                                 } else {
6322                                         None
6323                                 };
6324
6325                                 let mut revoke_and_ack = None;
6326                                 let mut commitment_update = None;
6327                                 let order = if let Some(ev) = msg_events.get(idx) {
6328                                         idx += 1;
6329                                         match ev {
6330                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6331                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6332                                                         revoke_and_ack = Some(msg.clone());
6333                                                         RAACommitmentOrder::RevokeAndACKFirst
6334                                                 },
6335                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6336                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6337                                                         commitment_update = Some(updates.clone());
6338                                                         RAACommitmentOrder::CommitmentFirst
6339                                                 },
6340                                                 _ => panic!("Unexpected event"),
6341                                         }
6342                                 } else {
6343                                         RAACommitmentOrder::CommitmentFirst
6344                                 };
6345
6346                                 if let Some(ev) = msg_events.get(idx) {
6347                                         match ev {
6348                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6349                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6350                                                         assert!(revoke_and_ack.is_none());
6351                                                         revoke_and_ack = Some(msg.clone());
6352                                                 },
6353                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6354                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6355                                                         assert!(commitment_update.is_none());
6356                                                         commitment_update = Some(updates.clone());
6357                                                 },
6358                                                 _ => panic!("Unexpected event"),
6359                                         }
6360                                 }
6361
6362                                 (funding_locked, revoke_and_ack, commitment_update, order)
6363                         }
6364                 }
6365         }
6366
6367         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6368         /// for claims/fails they are separated out.
6369         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)) {
6370                 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6371                 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6372                 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6373                 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6374
6375                 if send_funding_locked.0 {
6376                         // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6377                         // from b
6378                         for reestablish in reestablish_1.iter() {
6379                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6380                         }
6381                 }
6382                 if send_funding_locked.1 {
6383                         // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6384                         // from a
6385                         for reestablish in reestablish_2.iter() {
6386                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6387                         }
6388                 }
6389                 if send_funding_locked.0 || send_funding_locked.1 {
6390                         // If we expect any funding_locked's, both sides better have set
6391                         // next_local_commitment_number to 1
6392                         for reestablish in reestablish_1.iter() {
6393                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6394                         }
6395                         for reestablish in reestablish_2.iter() {
6396                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6397                         }
6398                 }
6399
6400                 let mut resp_1 = Vec::new();
6401                 for msg in reestablish_1 {
6402                         node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
6403                         resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
6404                 }
6405                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6406                         check_added_monitors!(node_b, 1);
6407                 } else {
6408                         check_added_monitors!(node_b, 0);
6409                 }
6410
6411                 let mut resp_2 = Vec::new();
6412                 for msg in reestablish_2 {
6413                         node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
6414                         resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
6415                 }
6416                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
6417                         check_added_monitors!(node_a, 1);
6418                 } else {
6419                         check_added_monitors!(node_a, 0);
6420                 }
6421
6422                 // We dont yet support both needing updates, as that would require a different commitment dance:
6423                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
6424                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
6425
6426                 for chan_msgs in resp_1.drain(..) {
6427                         if send_funding_locked.0 {
6428                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
6429                                 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
6430                                 if !announcement_event.is_empty() {
6431                                         assert_eq!(announcement_event.len(), 1);
6432                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
6433                                                 //TODO: Test announcement_sigs re-sending
6434                                         } else { panic!("Unexpected event!"); }
6435                                 }
6436                         } else {
6437                                 assert!(chan_msgs.0.is_none());
6438                         }
6439                         if pending_raa.0 {
6440                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
6441                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
6442                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
6443                                 check_added_monitors!(node_a, 1);
6444                         } else {
6445                                 assert!(chan_msgs.1.is_none());
6446                         }
6447                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6448                                 let commitment_update = chan_msgs.2.unwrap();
6449                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
6450                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
6451                                 } else {
6452                                         assert!(commitment_update.update_add_htlcs.is_empty());
6453                                 }
6454                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
6455                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
6456                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
6457                                 for update_add in commitment_update.update_add_htlcs {
6458                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
6459                                 }
6460                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
6461                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
6462                                 }
6463                                 for update_fail in commitment_update.update_fail_htlcs {
6464                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
6465                                 }
6466
6467                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
6468                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
6469                                 } else {
6470                                         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
6471                                         check_added_monitors!(node_a, 1);
6472                                         let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
6473                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
6474                                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6475                                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
6476                                         check_added_monitors!(node_b, 1);
6477                                 }
6478                         } else {
6479                                 assert!(chan_msgs.2.is_none());
6480                         }
6481                 }
6482
6483                 for chan_msgs in resp_2.drain(..) {
6484                         if send_funding_locked.1 {
6485                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
6486                                 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
6487                                 if !announcement_event.is_empty() {
6488                                         assert_eq!(announcement_event.len(), 1);
6489                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
6490                                                 //TODO: Test announcement_sigs re-sending
6491                                         } else { panic!("Unexpected event!"); }
6492                                 }
6493                         } else {
6494                                 assert!(chan_msgs.0.is_none());
6495                         }
6496                         if pending_raa.1 {
6497                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
6498                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
6499                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
6500                                 check_added_monitors!(node_b, 1);
6501                         } else {
6502                                 assert!(chan_msgs.1.is_none());
6503                         }
6504                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
6505                                 let commitment_update = chan_msgs.2.unwrap();
6506                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
6507                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
6508                                 }
6509                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
6510                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
6511                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
6512                                 for update_add in commitment_update.update_add_htlcs {
6513                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
6514                                 }
6515                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
6516                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
6517                                 }
6518                                 for update_fail in commitment_update.update_fail_htlcs {
6519                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
6520                                 }
6521
6522                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
6523                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
6524                                 } else {
6525                                         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
6526                                         check_added_monitors!(node_b, 1);
6527                                         let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
6528                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
6529                                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6530                                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
6531                                         check_added_monitors!(node_a, 1);
6532                                 }
6533                         } else {
6534                                 assert!(chan_msgs.2.is_none());
6535                         }
6536                 }
6537         }
6538
6539         #[test]
6540         fn test_simple_peer_disconnect() {
6541                 // Test that we can reconnect when there are no lost messages
6542                 let nodes = create_network(3);
6543                 create_announced_chan_between_nodes(&nodes, 0, 1);
6544                 create_announced_chan_between_nodes(&nodes, 1, 2);
6545
6546                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6547                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6548                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6549
6550                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
6551                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
6552                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
6553                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
6554
6555                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6556                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6557                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6558
6559                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
6560                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
6561                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
6562                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
6563
6564                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6565                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6566
6567                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
6568                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
6569
6570                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
6571                 {
6572                         let events = nodes[0].node.get_and_clear_pending_events();
6573                         assert_eq!(events.len(), 2);
6574                         match events[0] {
6575                                 Event::PaymentSent { payment_preimage } => {
6576                                         assert_eq!(payment_preimage, payment_preimage_3);
6577                                 },
6578                                 _ => panic!("Unexpected event"),
6579                         }
6580                         match events[1] {
6581                                 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
6582                                         assert_eq!(payment_hash, payment_hash_5);
6583                                         assert!(rejected_by_dest);
6584                                 },
6585                                 _ => panic!("Unexpected event"),
6586                         }
6587                 }
6588
6589                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
6590                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
6591         }
6592
6593         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
6594                 // Test that we can reconnect when in-flight HTLC updates get dropped
6595                 let mut nodes = create_network(2);
6596                 if messages_delivered == 0 {
6597                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
6598                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
6599                 } else {
6600                         create_announced_chan_between_nodes(&nodes, 0, 1);
6601                 }
6602
6603                 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();
6604                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6605
6606                 let payment_event = {
6607                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
6608                         check_added_monitors!(nodes[0], 1);
6609
6610                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6611                         assert_eq!(events.len(), 1);
6612                         SendEvent::from_event(events.remove(0))
6613                 };
6614                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
6615
6616                 if messages_delivered < 2 {
6617                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
6618                 } else {
6619                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6620                         if messages_delivered >= 3 {
6621                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6622                                 check_added_monitors!(nodes[1], 1);
6623                                 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6624
6625                                 if messages_delivered >= 4 {
6626                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6627                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6628                                         check_added_monitors!(nodes[0], 1);
6629
6630                                         if messages_delivered >= 5 {
6631                                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
6632                                                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
6633                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
6634                                                 check_added_monitors!(nodes[0], 1);
6635
6636                                                 if messages_delivered >= 6 {
6637                                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6638                                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6639                                                         check_added_monitors!(nodes[1], 1);
6640                                                 }
6641                                         }
6642                                 }
6643                         }
6644                 }
6645
6646                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6647                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6648                 if messages_delivered < 3 {
6649                         // Even if the funding_locked messages get exchanged, as long as nothing further was
6650                         // received on either side, both sides will need to resend them.
6651                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
6652                 } else if messages_delivered == 3 {
6653                         // nodes[0] still wants its RAA + commitment_signed
6654                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
6655                 } else if messages_delivered == 4 {
6656                         // nodes[0] still wants its commitment_signed
6657                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
6658                 } else if messages_delivered == 5 {
6659                         // nodes[1] still wants its final RAA
6660                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
6661                 } else if messages_delivered == 6 {
6662                         // Everything was delivered...
6663                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6664                 }
6665
6666                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6667                 assert_eq!(events_1.len(), 1);
6668                 match events_1[0] {
6669                         Event::PendingHTLCsForwardable { .. } => { },
6670                         _ => panic!("Unexpected event"),
6671                 };
6672
6673                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6674                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6675                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6676
6677                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6678                 nodes[1].node.process_pending_htlc_forwards();
6679
6680                 let events_2 = nodes[1].node.get_and_clear_pending_events();
6681                 assert_eq!(events_2.len(), 1);
6682                 match events_2[0] {
6683                         Event::PaymentReceived { ref payment_hash, amt } => {
6684                                 assert_eq!(payment_hash_1, *payment_hash);
6685                                 assert_eq!(amt, 1000000);
6686                         },
6687                         _ => panic!("Unexpected event"),
6688                 }
6689
6690                 nodes[1].node.claim_funds(payment_preimage_1);
6691                 check_added_monitors!(nodes[1], 1);
6692
6693                 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
6694                 assert_eq!(events_3.len(), 1);
6695                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
6696                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6697                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
6698                                 assert!(updates.update_add_htlcs.is_empty());
6699                                 assert!(updates.update_fail_htlcs.is_empty());
6700                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6701                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6702                                 assert!(updates.update_fee.is_none());
6703                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
6704                         },
6705                         _ => panic!("Unexpected event"),
6706                 };
6707
6708                 if messages_delivered >= 1 {
6709                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
6710
6711                         let events_4 = nodes[0].node.get_and_clear_pending_events();
6712                         assert_eq!(events_4.len(), 1);
6713                         match events_4[0] {
6714                                 Event::PaymentSent { ref payment_preimage } => {
6715                                         assert_eq!(payment_preimage_1, *payment_preimage);
6716                                 },
6717                                 _ => panic!("Unexpected event"),
6718                         }
6719
6720                         if messages_delivered >= 2 {
6721                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
6722                                 check_added_monitors!(nodes[0], 1);
6723                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6724
6725                                 if messages_delivered >= 3 {
6726                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6727                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6728                                         check_added_monitors!(nodes[1], 1);
6729
6730                                         if messages_delivered >= 4 {
6731                                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6732                                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6733                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
6734                                                 check_added_monitors!(nodes[1], 1);
6735
6736                                                 if messages_delivered >= 5 {
6737                                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6738                                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6739                                                         check_added_monitors!(nodes[0], 1);
6740                                                 }
6741                                         }
6742                                 }
6743                         }
6744                 }
6745
6746                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6747                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6748                 if messages_delivered < 2 {
6749                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
6750                         //TODO: Deduplicate PaymentSent events, then enable this if:
6751                         //if messages_delivered < 1 {
6752                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
6753                                 assert_eq!(events_4.len(), 1);
6754                                 match events_4[0] {
6755                                         Event::PaymentSent { ref payment_preimage } => {
6756                                                 assert_eq!(payment_preimage_1, *payment_preimage);
6757                                         },
6758                                         _ => panic!("Unexpected event"),
6759                                 }
6760                         //}
6761                 } else if messages_delivered == 2 {
6762                         // nodes[0] still wants its RAA + commitment_signed
6763                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
6764                 } else if messages_delivered == 3 {
6765                         // nodes[0] still wants its commitment_signed
6766                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
6767                 } else if messages_delivered == 4 {
6768                         // nodes[1] still wants its final RAA
6769                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
6770                 } else if messages_delivered == 5 {
6771                         // Everything was delivered...
6772                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6773                 }
6774
6775                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6776                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6777                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6778
6779                 // Channel should still work fine...
6780                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
6781                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
6782         }
6783
6784         #[test]
6785         fn test_drop_messages_peer_disconnect_a() {
6786                 do_test_drop_messages_peer_disconnect(0);
6787                 do_test_drop_messages_peer_disconnect(1);
6788                 do_test_drop_messages_peer_disconnect(2);
6789                 do_test_drop_messages_peer_disconnect(3);
6790         }
6791
6792         #[test]
6793         fn test_drop_messages_peer_disconnect_b() {
6794                 do_test_drop_messages_peer_disconnect(4);
6795                 do_test_drop_messages_peer_disconnect(5);
6796                 do_test_drop_messages_peer_disconnect(6);
6797         }
6798
6799         #[test]
6800         fn test_funding_peer_disconnect() {
6801                 // Test that we can lock in our funding tx while disconnected
6802                 let nodes = create_network(2);
6803                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
6804
6805                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6806                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6807
6808                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
6809                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
6810                 assert_eq!(events_1.len(), 1);
6811                 match events_1[0] {
6812                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
6813                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6814                         },
6815                         _ => panic!("Unexpected event"),
6816                 }
6817
6818                 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6819
6820                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6821                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6822
6823                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
6824                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6825                 assert_eq!(events_2.len(), 2);
6826                 match events_2[0] {
6827                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
6828                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
6829                         },
6830                         _ => panic!("Unexpected event"),
6831                 }
6832                 match events_2[1] {
6833                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
6834                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
6835                         },
6836                         _ => panic!("Unexpected event"),
6837                 }
6838
6839                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6840
6841                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
6842                 // rebroadcasting announcement_signatures upon reconnect.
6843
6844                 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();
6845                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
6846                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
6847         }
6848
6849         #[test]
6850         fn test_drop_messages_peer_disconnect_dual_htlc() {
6851                 // Test that we can handle reconnecting when both sides of a channel have pending
6852                 // commitment_updates when we disconnect.
6853                 let mut nodes = create_network(2);
6854                 create_announced_chan_between_nodes(&nodes, 0, 1);
6855
6856                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6857
6858                 // Now try to send a second payment which will fail to send
6859                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6860                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6861
6862                 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
6863                 check_added_monitors!(nodes[0], 1);
6864
6865                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
6866                 assert_eq!(events_1.len(), 1);
6867                 match events_1[0] {
6868                         MessageSendEvent::UpdateHTLCs { .. } => {},
6869                         _ => panic!("Unexpected event"),
6870                 }
6871
6872                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
6873                 check_added_monitors!(nodes[1], 1);
6874
6875                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6876                 assert_eq!(events_2.len(), 1);
6877                 match events_2[0] {
6878                         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 } } => {
6879                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
6880                                 assert!(update_add_htlcs.is_empty());
6881                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6882                                 assert!(update_fail_htlcs.is_empty());
6883                                 assert!(update_fail_malformed_htlcs.is_empty());
6884                                 assert!(update_fee.is_none());
6885
6886                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
6887                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
6888                                 assert_eq!(events_3.len(), 1);
6889                                 match events_3[0] {
6890                                         Event::PaymentSent { ref payment_preimage } => {
6891                                                 assert_eq!(*payment_preimage, payment_preimage_1);
6892                                         },
6893                                         _ => panic!("Unexpected event"),
6894                                 }
6895
6896                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6897                                 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
6898                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
6899                                 check_added_monitors!(nodes[0], 1);
6900                         },
6901                         _ => panic!("Unexpected event"),
6902                 }
6903
6904                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6905                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6906
6907                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
6908                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6909                 assert_eq!(reestablish_1.len(), 1);
6910                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
6911                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6912                 assert_eq!(reestablish_2.len(), 1);
6913
6914                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
6915                 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6916                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
6917                 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6918
6919                 assert!(as_resp.0.is_none());
6920                 assert!(bs_resp.0.is_none());
6921
6922                 assert!(bs_resp.1.is_none());
6923                 assert!(bs_resp.2.is_none());
6924
6925                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
6926
6927                 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
6928                 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
6929                 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
6930                 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
6931                 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
6932                 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();
6933                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
6934                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6935                 // No commitment_signed so get_event_msg's assert(len == 1) passes
6936                 check_added_monitors!(nodes[1], 1);
6937
6938                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
6939                 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6940                 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
6941                 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
6942                 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
6943                 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
6944                 assert!(bs_second_commitment_signed.update_fee.is_none());
6945                 check_added_monitors!(nodes[1], 1);
6946
6947                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6948                 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6949                 assert!(as_commitment_signed.update_add_htlcs.is_empty());
6950                 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
6951                 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
6952                 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
6953                 assert!(as_commitment_signed.update_fee.is_none());
6954                 check_added_monitors!(nodes[0], 1);
6955
6956                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
6957                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
6958                 // No commitment_signed so get_event_msg's assert(len == 1) passes
6959                 check_added_monitors!(nodes[0], 1);
6960
6961                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
6962                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6963                 // No commitment_signed so get_event_msg's assert(len == 1) passes
6964                 check_added_monitors!(nodes[1], 1);
6965
6966                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6967                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6968                 check_added_monitors!(nodes[1], 1);
6969
6970                 let events_4 = nodes[1].node.get_and_clear_pending_events();
6971                 assert_eq!(events_4.len(), 1);
6972                 match events_4[0] {
6973                         Event::PendingHTLCsForwardable { .. } => { },
6974                         _ => panic!("Unexpected event"),
6975                 };
6976
6977                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6978                 nodes[1].node.process_pending_htlc_forwards();
6979
6980                 let events_5 = nodes[1].node.get_and_clear_pending_events();
6981                 assert_eq!(events_5.len(), 1);
6982                 match events_5[0] {
6983                         Event::PaymentReceived { ref payment_hash, amt: _ } => {
6984                                 assert_eq!(payment_hash_2, *payment_hash);
6985                         },
6986                         _ => panic!("Unexpected event"),
6987                 }
6988
6989                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
6990                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6991                 check_added_monitors!(nodes[0], 1);
6992
6993                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
6994         }
6995
6996         #[test]
6997         fn test_simple_monitor_permanent_update_fail() {
6998                 // Test that we handle a simple permanent monitor update failure
6999                 let mut nodes = create_network(2);
7000                 create_announced_chan_between_nodes(&nodes, 0, 1);
7001
7002                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7003                 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7004
7005                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7006                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7007                 check_added_monitors!(nodes[0], 1);
7008
7009                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7010                 assert_eq!(events_1.len(), 2);
7011                 match events_1[0] {
7012                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7013                         _ => panic!("Unexpected event"),
7014                 };
7015                 match events_1[1] {
7016                         MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7017                         _ => panic!("Unexpected event"),
7018                 };
7019
7020                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7021                 // PaymentFailed event
7022
7023                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7024         }
7025
7026         fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7027                 // Test that we can recover from a simple temporary monitor update failure optionally with
7028                 // a disconnect in between
7029                 let mut nodes = create_network(2);
7030                 create_announced_chan_between_nodes(&nodes, 0, 1);
7031
7032                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7033                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7034
7035                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7036                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7037                 check_added_monitors!(nodes[0], 1);
7038
7039                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7040                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7041                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7042
7043                 if disconnect {
7044                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7045                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7046                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7047                 }
7048
7049                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7050                 nodes[0].node.test_restore_channel_monitor();
7051                 check_added_monitors!(nodes[0], 1);
7052
7053                 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7054                 assert_eq!(events_2.len(), 1);
7055                 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7056                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7057                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7058                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7059
7060                 expect_pending_htlcs_forwardable!(nodes[1]);
7061
7062                 let events_3 = nodes[1].node.get_and_clear_pending_events();
7063                 assert_eq!(events_3.len(), 1);
7064                 match events_3[0] {
7065                         Event::PaymentReceived { ref payment_hash, amt } => {
7066                                 assert_eq!(payment_hash_1, *payment_hash);
7067                                 assert_eq!(amt, 1000000);
7068                         },
7069                         _ => panic!("Unexpected event"),
7070                 }
7071
7072                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7073
7074                 // Now set it to failed again...
7075                 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7076                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7077                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7078                 check_added_monitors!(nodes[0], 1);
7079
7080                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7081                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7082                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7083
7084                 if disconnect {
7085                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7086                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7087                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7088                 }
7089
7090                 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7091                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7092                 nodes[0].node.test_restore_channel_monitor();
7093                 check_added_monitors!(nodes[0], 1);
7094
7095                 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7096                 assert_eq!(events_5.len(), 1);
7097                 match events_5[0] {
7098                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7099                         _ => panic!("Unexpected event"),
7100                 }
7101
7102                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7103                 // PaymentFailed event
7104
7105                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7106         }
7107
7108         #[test]
7109         fn test_simple_monitor_temporary_update_fail() {
7110                 do_test_simple_monitor_temporary_update_fail(false);
7111                 do_test_simple_monitor_temporary_update_fail(true);
7112         }
7113
7114         fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7115                 let disconnect_flags = 8 | 16;
7116
7117                 // Test that we can recover from a temporary monitor update failure with some in-flight
7118                 // HTLCs going on at the same time potentially with some disconnection thrown in.
7119                 // * First we route a payment, then get a temporary monitor update failure when trying to
7120                 //   route a second payment. We then claim the first payment.
7121                 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7122                 //   TemporaryFailure likely indicates net disconnect which resulted in failing to update
7123                 //   the ChannelMonitor on a watchtower).
7124                 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7125                 //   immediately, otherwise we wait sconnect and deliver them via the reconnect
7126                 //   channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7127                 //   disconnect_count & !disconnect_flags is 0).
7128                 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7129                 //   through message sending, potentially disconnect/reconnecting multiple times based on
7130                 //   disconnect_count, to get the update_fulfill_htlc through.
7131                 // * We then walk through more message exchanges to get the original update_add_htlc
7132                 //   through, swapping message ordering based on disconnect_count & 8 and optionally
7133                 //   disconnect/reconnecting based on disconnect_count.
7134                 let mut nodes = create_network(2);
7135                 create_announced_chan_between_nodes(&nodes, 0, 1);
7136
7137                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7138
7139                 // Now try to send a second payment which will fail to send
7140                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7141                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7142
7143                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7144                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7145                 check_added_monitors!(nodes[0], 1);
7146
7147                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7148                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7149                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7150
7151                 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7152                 // but nodes[0] won't respond since it is frozen.
7153                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7154                 check_added_monitors!(nodes[1], 1);
7155                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7156                 assert_eq!(events_2.len(), 1);
7157                 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7158                         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 } } => {
7159                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7160                                 assert!(update_add_htlcs.is_empty());
7161                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7162                                 assert!(update_fail_htlcs.is_empty());
7163                                 assert!(update_fail_malformed_htlcs.is_empty());
7164                                 assert!(update_fee.is_none());
7165
7166                                 if (disconnect_count & 16) == 0 {
7167                                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7168                                         let events_3 = nodes[0].node.get_and_clear_pending_events();
7169                                         assert_eq!(events_3.len(), 1);
7170                                         match events_3[0] {
7171                                                 Event::PaymentSent { ref payment_preimage } => {
7172                                                         assert_eq!(*payment_preimage, payment_preimage_1);
7173                                                 },
7174                                                 _ => panic!("Unexpected event"),
7175                                         }
7176
7177                                         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) {
7178                                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7179                                         } else { panic!(); }
7180                                 }
7181
7182                                 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7183                         },
7184                         _ => panic!("Unexpected event"),
7185                 };
7186
7187                 if disconnect_count & !disconnect_flags > 0 {
7188                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7189                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7190                 }
7191
7192                 // Now fix monitor updating...
7193                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7194                 nodes[0].node.test_restore_channel_monitor();
7195                 check_added_monitors!(nodes[0], 1);
7196
7197                 macro_rules! disconnect_reconnect_peers { () => { {
7198                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7199                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7200
7201                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7202                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7203                         assert_eq!(reestablish_1.len(), 1);
7204                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7205                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7206                         assert_eq!(reestablish_2.len(), 1);
7207
7208                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7209                         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7210                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7211                         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7212
7213                         assert!(as_resp.0.is_none());
7214                         assert!(bs_resp.0.is_none());
7215
7216                         (reestablish_1, reestablish_2, as_resp, bs_resp)
7217                 } } }
7218
7219                 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7220                         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7221                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7222
7223                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7224                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7225                         assert_eq!(reestablish_1.len(), 1);
7226                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7227                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7228                         assert_eq!(reestablish_2.len(), 1);
7229
7230                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7231                         check_added_monitors!(nodes[0], 0);
7232                         let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7233                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7234                         check_added_monitors!(nodes[1], 0);
7235                         let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7236
7237                         assert!(as_resp.0.is_none());
7238                         assert!(bs_resp.0.is_none());
7239
7240                         assert!(bs_resp.1.is_none());
7241                         if (disconnect_count & 16) == 0 {
7242                                 assert!(bs_resp.2.is_none());
7243
7244                                 assert!(as_resp.1.is_some());
7245                                 assert!(as_resp.2.is_some());
7246                                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7247                         } else {
7248                                 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7249                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7250                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7251                                 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7252                                 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7253                                 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7254
7255                                 assert!(as_resp.1.is_none());
7256
7257                                 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();
7258                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7259                                 assert_eq!(events_3.len(), 1);
7260                                 match events_3[0] {
7261                                         Event::PaymentSent { ref payment_preimage } => {
7262                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7263                                         },
7264                                         _ => panic!("Unexpected event"),
7265                                 }
7266
7267                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7268                                 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7269                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7270                                 check_added_monitors!(nodes[0], 1);
7271
7272                                 as_resp.1 = Some(as_resp_raa);
7273                                 bs_resp.2 = None;
7274                         }
7275
7276                         if disconnect_count & !disconnect_flags > 1 {
7277                                 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7278
7279                                 if (disconnect_count & 16) == 0 {
7280                                         assert!(reestablish_1 == second_reestablish_1);
7281                                         assert!(reestablish_2 == second_reestablish_2);
7282                                 }
7283                                 assert!(as_resp == second_as_resp);
7284                                 assert!(bs_resp == second_bs_resp);
7285                         }
7286
7287                         (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7288                 } else {
7289                         let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7290                         assert_eq!(events_4.len(), 2);
7291                         (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7292                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7293                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7294                                         msg.clone()
7295                                 },
7296                                 _ => panic!("Unexpected event"),
7297                         })
7298                 };
7299
7300                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7301
7302                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7303                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7304                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7305                 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7306                 check_added_monitors!(nodes[1], 1);
7307
7308                 if disconnect_count & !disconnect_flags > 2 {
7309                         let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7310
7311                         assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7312                         assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7313
7314                         assert!(as_resp.2.is_none());
7315                         assert!(bs_resp.2.is_none());
7316                 }
7317
7318                 let as_commitment_update;
7319                 let bs_second_commitment_update;
7320
7321                 macro_rules! handle_bs_raa { () => {
7322                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7323                         as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7324                         assert!(as_commitment_update.update_add_htlcs.is_empty());
7325                         assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7326                         assert!(as_commitment_update.update_fail_htlcs.is_empty());
7327                         assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7328                         assert!(as_commitment_update.update_fee.is_none());
7329                         check_added_monitors!(nodes[0], 1);
7330                 } }
7331
7332                 macro_rules! handle_initial_raa { () => {
7333                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7334                         bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7335                         assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7336                         assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7337                         assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7338                         assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7339                         assert!(bs_second_commitment_update.update_fee.is_none());
7340                         check_added_monitors!(nodes[1], 1);
7341                 } }
7342
7343                 if (disconnect_count & 8) == 0 {
7344                         handle_bs_raa!();
7345
7346                         if disconnect_count & !disconnect_flags > 3 {
7347                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7348
7349                                 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7350                                 assert!(bs_resp.1.is_none());
7351
7352                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7353                                 assert!(bs_resp.2.is_none());
7354
7355                                 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7356                         }
7357
7358                         handle_initial_raa!();
7359
7360                         if disconnect_count & !disconnect_flags > 4 {
7361                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7362
7363                                 assert!(as_resp.1.is_none());
7364                                 assert!(bs_resp.1.is_none());
7365
7366                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7367                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7368                         }
7369                 } else {
7370                         handle_initial_raa!();
7371
7372                         if disconnect_count & !disconnect_flags > 3 {
7373                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7374
7375                                 assert!(as_resp.1.is_none());
7376                                 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7377
7378                                 assert!(as_resp.2.is_none());
7379                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7380
7381                                 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7382                         }
7383
7384                         handle_bs_raa!();
7385
7386                         if disconnect_count & !disconnect_flags > 4 {
7387                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7388
7389                                 assert!(as_resp.1.is_none());
7390                                 assert!(bs_resp.1.is_none());
7391
7392                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7393                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7394                         }
7395                 }
7396
7397                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
7398                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7399                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7400                 check_added_monitors!(nodes[0], 1);
7401
7402                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
7403                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7404                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7405                 check_added_monitors!(nodes[1], 1);
7406
7407                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7408                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7409                 check_added_monitors!(nodes[1], 1);
7410
7411                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7412                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7413                 check_added_monitors!(nodes[0], 1);
7414
7415                 expect_pending_htlcs_forwardable!(nodes[1]);
7416
7417                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7418                 assert_eq!(events_5.len(), 1);
7419                 match events_5[0] {
7420                         Event::PaymentReceived { ref payment_hash, amt } => {
7421                                 assert_eq!(payment_hash_2, *payment_hash);
7422                                 assert_eq!(amt, 1000000);
7423                         },
7424                         _ => panic!("Unexpected event"),
7425                 }
7426
7427                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7428         }
7429
7430         #[test]
7431         fn test_monitor_temporary_update_fail_a() {
7432                 do_test_monitor_temporary_update_fail(0);
7433                 do_test_monitor_temporary_update_fail(1);
7434                 do_test_monitor_temporary_update_fail(2);
7435                 do_test_monitor_temporary_update_fail(3);
7436                 do_test_monitor_temporary_update_fail(4);
7437                 do_test_monitor_temporary_update_fail(5);
7438         }
7439
7440         #[test]
7441         fn test_monitor_temporary_update_fail_b() {
7442                 do_test_monitor_temporary_update_fail(2 | 8);
7443                 do_test_monitor_temporary_update_fail(3 | 8);
7444                 do_test_monitor_temporary_update_fail(4 | 8);
7445                 do_test_monitor_temporary_update_fail(5 | 8);
7446         }
7447
7448         #[test]
7449         fn test_monitor_temporary_update_fail_c() {
7450                 do_test_monitor_temporary_update_fail(1 | 16);
7451                 do_test_monitor_temporary_update_fail(2 | 16);
7452                 do_test_monitor_temporary_update_fail(3 | 16);
7453                 do_test_monitor_temporary_update_fail(2 | 8 | 16);
7454                 do_test_monitor_temporary_update_fail(3 | 8 | 16);
7455         }
7456
7457         #[test]
7458         fn test_invalid_channel_announcement() {
7459                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
7460                 let secp_ctx = Secp256k1::new();
7461                 let nodes = create_network(2);
7462
7463                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
7464
7465                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
7466                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
7467                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
7468                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
7469
7470                 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 } );
7471
7472                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
7473                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
7474
7475                 let as_network_key = nodes[0].node.get_our_node_id();
7476                 let bs_network_key = nodes[1].node.get_our_node_id();
7477
7478                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
7479
7480                 let mut chan_announcement;
7481
7482                 macro_rules! dummy_unsigned_msg {
7483                         () => {
7484                                 msgs::UnsignedChannelAnnouncement {
7485                                         features: msgs::GlobalFeatures::new(),
7486                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
7487                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
7488                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
7489                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
7490                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
7491                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
7492                                         excess_data: Vec::new(),
7493                                 };
7494                         }
7495                 }
7496
7497                 macro_rules! sign_msg {
7498                         ($unsigned_msg: expr) => {
7499                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
7500                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
7501                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
7502                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
7503                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
7504                                 chan_announcement = msgs::ChannelAnnouncement {
7505                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
7506                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
7507                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
7508                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
7509                                         contents: $unsigned_msg
7510                                 }
7511                         }
7512                 }
7513
7514                 let unsigned_msg = dummy_unsigned_msg!();
7515                 sign_msg!(unsigned_msg);
7516                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
7517                 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 } );
7518
7519                 // Configured with Network::Testnet
7520                 let mut unsigned_msg = dummy_unsigned_msg!();
7521                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
7522                 sign_msg!(unsigned_msg);
7523                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
7524
7525                 let mut unsigned_msg = dummy_unsigned_msg!();
7526                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
7527                 sign_msg!(unsigned_msg);
7528                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
7529         }
7530
7531         struct VecWriter(Vec<u8>);
7532         impl Writer for VecWriter {
7533                 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
7534                         self.0.extend_from_slice(buf);
7535                         Ok(())
7536                 }
7537                 fn size_hint(&mut self, size: usize) {
7538                         self.0.reserve_exact(size);
7539                 }
7540         }
7541
7542         #[test]
7543         fn test_no_txn_manager_serialize_deserialize() {
7544                 let mut nodes = create_network(2);
7545
7546                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7547
7548                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7549
7550                 let nodes_0_serialized = nodes[0].node.encode();
7551                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
7552                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
7553
7554                 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())));
7555                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
7556                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
7557                 assert!(chan_0_monitor_read.is_empty());
7558
7559                 let mut nodes_0_read = &nodes_0_serialized[..];
7560                 let config = UserConfig::new();
7561                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
7562                 let (_, nodes_0_deserialized) = {
7563                         let mut channel_monitors = HashMap::new();
7564                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
7565                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
7566                                 default_config: config,
7567                                 keys_manager,
7568                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
7569                                 monitor: nodes[0].chan_monitor.clone(),
7570                                 chain_monitor: nodes[0].chain_monitor.clone(),
7571                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
7572                                 logger: Arc::new(test_utils::TestLogger::new()),
7573                                 channel_monitors: &channel_monitors,
7574                         }).unwrap()
7575                 };
7576                 assert!(nodes_0_read.is_empty());
7577
7578                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
7579                 nodes[0].node = Arc::new(nodes_0_deserialized);
7580                 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
7581                 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
7582                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7583                 check_added_monitors!(nodes[0], 1);
7584
7585                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7586                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7587                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7588                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7589
7590                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7591                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7592                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7593                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7594
7595                 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
7596                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
7597                 for node in nodes.iter() {
7598                         assert!(node.router.handle_channel_announcement(&announcement).unwrap());
7599                         node.router.handle_channel_update(&as_update).unwrap();
7600                         node.router.handle_channel_update(&bs_update).unwrap();
7601                 }
7602
7603                 send_payment(&nodes[0], &[&nodes[1]], 1000000);
7604         }
7605
7606         #[test]
7607         fn test_simple_manager_serialize_deserialize() {
7608                 let mut nodes = create_network(2);
7609                 create_announced_chan_between_nodes(&nodes, 0, 1);
7610
7611                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7612                 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7613
7614                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7615
7616                 let nodes_0_serialized = nodes[0].node.encode();
7617                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
7618                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
7619
7620                 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())));
7621                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
7622                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
7623                 assert!(chan_0_monitor_read.is_empty());
7624
7625                 let mut nodes_0_read = &nodes_0_serialized[..];
7626                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
7627                 let (_, nodes_0_deserialized) = {
7628                         let mut channel_monitors = HashMap::new();
7629                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
7630                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
7631                                 default_config: UserConfig::new(),
7632                                 keys_manager,
7633                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
7634                                 monitor: nodes[0].chan_monitor.clone(),
7635                                 chain_monitor: nodes[0].chain_monitor.clone(),
7636                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
7637                                 logger: Arc::new(test_utils::TestLogger::new()),
7638                                 channel_monitors: &channel_monitors,
7639                         }).unwrap()
7640                 };
7641                 assert!(nodes_0_read.is_empty());
7642
7643                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
7644                 nodes[0].node = Arc::new(nodes_0_deserialized);
7645                 check_added_monitors!(nodes[0], 1);
7646
7647                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7648
7649                 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
7650                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
7651         }
7652
7653         #[test]
7654         fn test_manager_serialize_deserialize_inconsistent_monitor() {
7655                 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
7656                 let mut nodes = create_network(4);
7657                 create_announced_chan_between_nodes(&nodes, 0, 1);
7658                 create_announced_chan_between_nodes(&nodes, 2, 0);
7659                 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
7660
7661                 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
7662
7663                 // Serialize the ChannelManager here, but the monitor we keep up-to-date
7664                 let nodes_0_serialized = nodes[0].node.encode();
7665
7666                 route_payment(&nodes[0], &[&nodes[3]], 1000000);
7667                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7668                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7669                 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7670
7671                 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
7672                 // nodes[3])
7673                 let mut node_0_monitors_serialized = Vec::new();
7674                 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
7675                         let mut writer = VecWriter(Vec::new());
7676                         monitor.1.write_for_disk(&mut writer).unwrap();
7677                         node_0_monitors_serialized.push(writer.0);
7678                 }
7679
7680                 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())));
7681                 let mut node_0_monitors = Vec::new();
7682                 for serialized in node_0_monitors_serialized.iter() {
7683                         let mut read = &serialized[..];
7684                         let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
7685                         assert!(read.is_empty());
7686                         node_0_monitors.push(monitor);
7687                 }
7688
7689                 let mut nodes_0_read = &nodes_0_serialized[..];
7690                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
7691                 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
7692                         default_config: UserConfig::new(),
7693                         keys_manager,
7694                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
7695                         monitor: nodes[0].chan_monitor.clone(),
7696                         chain_monitor: nodes[0].chain_monitor.clone(),
7697                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
7698                         logger: Arc::new(test_utils::TestLogger::new()),
7699                         channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
7700                 }).unwrap();
7701                 assert!(nodes_0_read.is_empty());
7702
7703                 { // Channel close should result in a commitment tx and an HTLC tx
7704                         let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7705                         assert_eq!(txn.len(), 2);
7706                         assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
7707                         assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
7708                 }
7709
7710                 for monitor in node_0_monitors.drain(..) {
7711                         assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
7712                         check_added_monitors!(nodes[0], 1);
7713                 }
7714                 nodes[0].node = Arc::new(nodes_0_deserialized);
7715
7716                 // nodes[1] and nodes[2] have no lost state with nodes[0]...
7717                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7718                 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7719                 //... and we can even still claim the payment!
7720                 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
7721
7722                 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
7723                 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7724                 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
7725                 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) {
7726                         assert_eq!(msg.channel_id, channel_id);
7727                 } else { panic!("Unexpected result"); }
7728         }
7729
7730         macro_rules! check_spendable_outputs {
7731                 ($node: expr, $der_idx: expr) => {
7732                         {
7733                                 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
7734                                 let mut txn = Vec::new();
7735                                 for event in events {
7736                                         match event {
7737                                                 Event::SpendableOutputs { ref outputs } => {
7738                                                         for outp in outputs {
7739                                                                 match *outp {
7740                                                                         SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
7741                                                                                 let input = TxIn {
7742                                                                                         previous_output: outpoint.clone(),
7743                                                                                         script_sig: Script::new(),
7744                                                                                         sequence: 0,
7745                                                                                         witness: Vec::new(),
7746                                                                                 };
7747                                                                                 let outp = TxOut {
7748                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
7749                                                                                         value: output.value,
7750                                                                                 };
7751                                                                                 let mut spend_tx = Transaction {
7752                                                                                         version: 2,
7753                                                                                         lock_time: 0,
7754                                                                                         input: vec![input],
7755                                                                                         output: vec![outp],
7756                                                                                 };
7757                                                                                 let secp_ctx = Secp256k1::new();
7758                                                                                 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
7759                                                                                 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
7760                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
7761                                                                                 let remotesig = secp_ctx.sign(&sighash, key);
7762                                                                                 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
7763                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
7764                                                                                 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
7765                                                                                 txn.push(spend_tx);
7766                                                                         },
7767                                                                         SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
7768                                                                                 let input = TxIn {
7769                                                                                         previous_output: outpoint.clone(),
7770                                                                                         script_sig: Script::new(),
7771                                                                                         sequence: *to_self_delay as u32,
7772                                                                                         witness: Vec::new(),
7773                                                                                 };
7774                                                                                 let outp = TxOut {
7775                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
7776                                                                                         value: output.value,
7777                                                                                 };
7778                                                                                 let mut spend_tx = Transaction {
7779                                                                                         version: 2,
7780                                                                                         lock_time: 0,
7781                                                                                         input: vec![input],
7782                                                                                         output: vec![outp],
7783                                                                                 };
7784                                                                                 let secp_ctx = Secp256k1::new();
7785                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
7786                                                                                 let local_delaysig = secp_ctx.sign(&sighash, key);
7787                                                                                 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
7788                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
7789                                                                                 spend_tx.input[0].witness.push(vec!(0));
7790                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
7791                                                                                 txn.push(spend_tx);
7792                                                                         },
7793                                                                         SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
7794                                                                                 let secp_ctx = Secp256k1::new();
7795                                                                                 let input = TxIn {
7796                                                                                         previous_output: outpoint.clone(),
7797                                                                                         script_sig: Script::new(),
7798                                                                                         sequence: 0,
7799                                                                                         witness: Vec::new(),
7800                                                                                 };
7801                                                                                 let outp = TxOut {
7802                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
7803                                                                                         value: output.value,
7804                                                                                 };
7805                                                                                 let mut spend_tx = Transaction {
7806                                                                                         version: 2,
7807                                                                                         lock_time: 0,
7808                                                                                         input: vec![input],
7809                                                                                         output: vec![outp.clone()],
7810                                                                                 };
7811                                                                                 let secret = {
7812                                                                                         match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
7813                                                                                                 Ok(master_key) => {
7814                                                                                                         match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
7815                                                                                                                 Ok(key) => key,
7816                                                                                                                 Err(_) => panic!("Your RNG is busted"),
7817                                                                                                         }
7818                                                                                                 }
7819                                                                                                 Err(_) => panic!("Your rng is busted"),
7820                                                                                         }
7821                                                                                 };
7822                                                                                 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
7823                                                                                 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
7824                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
7825                                                                                 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
7826                                                                                 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
7827                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
7828                                                                                 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
7829                                                                                 txn.push(spend_tx);
7830                                                                         },
7831                                                                 }
7832                                                         }
7833                                                 },
7834                                                 _ => panic!("Unexpected event"),
7835                                         };
7836                                 }
7837                                 txn
7838                         }
7839                 }
7840         }
7841
7842         #[test]
7843         fn test_claim_sizeable_push_msat() {
7844                 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
7845                 let nodes = create_network(2);
7846
7847                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
7848                 nodes[1].node.force_close_channel(&chan.2);
7849                 let events = nodes[1].node.get_and_clear_pending_msg_events();
7850                 match events[0] {
7851                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7852                         _ => panic!("Unexpected event"),
7853                 }
7854                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7855                 assert_eq!(node_txn.len(), 1);
7856                 check_spends!(node_txn[0], chan.3.clone());
7857                 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
7858
7859                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7860                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
7861                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
7862                 assert_eq!(spend_txn.len(), 1);
7863                 check_spends!(spend_txn[0], node_txn[0].clone());
7864         }
7865
7866         #[test]
7867         fn test_claim_on_remote_sizeable_push_msat() {
7868                 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
7869                 // to_remote output is encumbered by a P2WPKH
7870
7871                 let nodes = create_network(2);
7872
7873                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
7874                 nodes[0].node.force_close_channel(&chan.2);
7875                 let events = nodes[0].node.get_and_clear_pending_msg_events();
7876                 match events[0] {
7877                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7878                         _ => panic!("Unexpected event"),
7879                 }
7880                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7881                 assert_eq!(node_txn.len(), 1);
7882                 check_spends!(node_txn[0], chan.3.clone());
7883                 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
7884
7885                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7886                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
7887                 let events = nodes[1].node.get_and_clear_pending_msg_events();
7888                 match events[0] {
7889                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7890                         _ => panic!("Unexpected event"),
7891                 }
7892                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
7893                 assert_eq!(spend_txn.len(), 2);
7894                 assert_eq!(spend_txn[0], spend_txn[1]);
7895                 check_spends!(spend_txn[0], node_txn[0].clone());
7896         }
7897
7898         #[test]
7899         fn test_claim_on_remote_revoked_sizeable_push_msat() {
7900                 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
7901                 // to_remote output is encumbered by a P2WPKH
7902
7903                 let nodes = create_network(2);
7904
7905                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
7906                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7907                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
7908                 assert_eq!(revoked_local_txn[0].input.len(), 1);
7909                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7910
7911                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7912                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7913                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7914                 let events = nodes[1].node.get_and_clear_pending_msg_events();
7915                 match events[0] {
7916                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7917                         _ => panic!("Unexpected event"),
7918                 }
7919                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7920                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
7921                 assert_eq!(spend_txn.len(), 4);
7922                 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
7923                 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
7924                 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
7925                 check_spends!(spend_txn[1], node_txn[0].clone());
7926         }
7927
7928         #[test]
7929         fn test_static_spendable_outputs_preimage_tx() {
7930                 let nodes = create_network(2);
7931
7932                 // Create some initial channels
7933                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
7934
7935                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7936
7937                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
7938                 assert_eq!(commitment_tx[0].input.len(), 1);
7939                 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
7940
7941                 // Settle A's commitment tx on B's chain
7942                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7943                 assert!(nodes[1].node.claim_funds(payment_preimage));
7944                 check_added_monitors!(nodes[1], 1);
7945                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
7946                 let events = nodes[1].node.get_and_clear_pending_msg_events();
7947                 match events[0] {
7948                         MessageSendEvent::UpdateHTLCs { .. } => {},
7949                         _ => panic!("Unexpected event"),
7950                 }
7951                 match events[1] {
7952                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7953                         _ => panic!("Unexepected event"),
7954                 }
7955
7956                 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
7957                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
7958                 check_spends!(node_txn[0], commitment_tx[0].clone());
7959                 assert_eq!(node_txn[0], node_txn[2]);
7960                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 133);
7961                 check_spends!(node_txn[1], chan_1.3.clone());
7962
7963                 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
7964                 assert_eq!(spend_txn.len(), 2);
7965                 assert_eq!(spend_txn[0], spend_txn[1]);
7966                 check_spends!(spend_txn[0], node_txn[0].clone());
7967         }
7968
7969         #[test]
7970         fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
7971                 let nodes = create_network(2);
7972
7973                 // Create some initial channels
7974                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
7975
7976                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7977                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
7978                 assert_eq!(revoked_local_txn[0].input.len(), 1);
7979                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
7980
7981                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7982
7983                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7984                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7985                 let events = nodes[1].node.get_and_clear_pending_msg_events();
7986                 match events[0] {
7987                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7988                         _ => panic!("Unexpected event"),
7989                 }
7990                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7991                 assert_eq!(node_txn.len(), 3);
7992                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
7993                 assert_eq!(node_txn[0].input.len(), 2);
7994                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
7995
7996                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
7997                 assert_eq!(spend_txn.len(), 2);
7998                 assert_eq!(spend_txn[0], spend_txn[1]);
7999                 check_spends!(spend_txn[0], node_txn[0].clone());
8000         }
8001
8002         #[test]
8003         fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
8004                 let nodes = create_network(2);
8005
8006                 // Create some initial channels
8007                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8008
8009                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8010                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8011                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8012                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8013
8014                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8015
8016                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8017                 // A will generate HTLC-Timeout from revoked commitment tx
8018                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8019                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8020                 match events[0] {
8021                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8022                         _ => panic!("Unexpected event"),
8023                 }
8024                 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8025                 assert_eq!(revoked_htlc_txn.len(), 2);
8026                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
8027                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), 133);
8028                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
8029
8030                 // B will generate justice tx from A's revoked commitment/HTLC tx
8031                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
8032                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8033                 match events[0] {
8034                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8035                         _ => panic!("Unexpected event"),
8036                 }
8037
8038                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8039                 assert_eq!(node_txn.len(), 4);
8040                 assert_eq!(node_txn[3].input.len(), 1);
8041                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
8042
8043                 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
8044                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8045                 assert_eq!(spend_txn.len(), 3);
8046                 assert_eq!(spend_txn[0], spend_txn[1]);
8047                 check_spends!(spend_txn[0], node_txn[0].clone());
8048                 check_spends!(spend_txn[2], node_txn[3].clone());
8049         }
8050
8051         #[test]
8052         fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
8053                 let nodes = create_network(2);
8054
8055                 // Create some initial channels
8056                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8057
8058                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8059                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8060                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8061                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8062
8063                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8064
8065                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8066                 // B will generate HTLC-Success from revoked commitment tx
8067                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8068                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8069                 match events[0] {
8070                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8071                         _ => panic!("Unexpected event"),
8072                 }
8073                 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8074
8075                 assert_eq!(revoked_htlc_txn.len(), 2);
8076                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
8077                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), 138);
8078                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
8079
8080                 // A will generate justice tx from B's revoked commitment/HTLC tx
8081                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
8082                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8083                 match events[0] {
8084                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8085                         _ => panic!("Unexpected event"),
8086                 }
8087
8088                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8089                 assert_eq!(node_txn.len(), 4);
8090                 assert_eq!(node_txn[3].input.len(), 1);
8091                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
8092
8093                 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
8094                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
8095                 assert_eq!(spend_txn.len(), 5);
8096                 assert_eq!(spend_txn[0], spend_txn[2]);
8097                 assert_eq!(spend_txn[1], spend_txn[3]);
8098                 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
8099                 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
8100                 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
8101         }
8102
8103         #[test]
8104         fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
8105                 let nodes = create_network(2);
8106
8107                 // Create some initial channels
8108                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8109
8110                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
8111                 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8112                 assert_eq!(local_txn[0].input.len(), 1);
8113                 check_spends!(local_txn[0], chan_1.3.clone());
8114
8115                 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
8116                 nodes[1].node.claim_funds(payment_preimage);
8117                 check_added_monitors!(nodes[1], 1);
8118                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8119                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
8120                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8121                 match events[0] {
8122                         MessageSendEvent::UpdateHTLCs { .. } => {},
8123                         _ => panic!("Unexpected event"),
8124                 }
8125                 match events[1] {
8126                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8127                         _ => panic!("Unexepected event"),
8128                 }
8129                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8130                 assert_eq!(node_txn[0].input.len(), 1);
8131                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 138);
8132                 check_spends!(node_txn[0], local_txn[0].clone());
8133
8134                 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
8135                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8136                 assert_eq!(spend_txn.len(), 1);
8137                 check_spends!(spend_txn[0], node_txn[0].clone());
8138         }
8139
8140         #[test]
8141         fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
8142                 let nodes = create_network(2);
8143
8144                 // Create some initial channels
8145                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8146
8147                 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
8148                 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8149                 assert_eq!(local_txn[0].input.len(), 1);
8150                 check_spends!(local_txn[0], chan_1.3.clone());
8151
8152                 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8153                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8154                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8155                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8156                 match events[0] {
8157                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8158                         _ => panic!("Unexepected event"),
8159                 }
8160                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8161                 assert_eq!(node_txn[0].input.len(), 1);
8162                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 133);
8163                 check_spends!(node_txn[0], local_txn[0].clone());
8164
8165                 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
8166                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
8167                 assert_eq!(spend_txn.len(), 4);
8168                 assert_eq!(spend_txn[0], spend_txn[2]);
8169                 assert_eq!(spend_txn[1], spend_txn[3]);
8170                 check_spends!(spend_txn[0], local_txn[0].clone());
8171                 check_spends!(spend_txn[1], node_txn[0].clone());
8172         }
8173
8174         #[test]
8175         fn test_static_output_closing_tx() {
8176                 let nodes = create_network(2);
8177
8178                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
8179
8180                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
8181                 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
8182
8183                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8184                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
8185                 let spend_txn = check_spendable_outputs!(nodes[0], 2);
8186                 assert_eq!(spend_txn.len(), 1);
8187                 check_spends!(spend_txn[0], closing_tx.clone());
8188
8189                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
8190                 let spend_txn = check_spendable_outputs!(nodes[1], 2);
8191                 assert_eq!(spend_txn.len(), 1);
8192                 check_spends!(spend_txn[0], closing_tx);
8193         }
8194 }