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