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