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