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