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