Move HTLCFailChannelUpdate handling out-of-band
[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, ChannelKeys};
26 use ln::channelmonitor::{ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
27 use ln::router::{Route,RouteHop};
28 use ln::msgs;
29 use ln::msgs::{HandleError,ChannelMessageHandler};
30 use util::{byte_utils, events, internal_traits, rng};
31 use util::sha2::Sha256;
32 use util::ser::{Readable, Writeable};
33 use util::chacha20poly1305rfc::ChaCha20;
34 use util::logger::Logger;
35 use util::errors::APIError;
36
37 use crypto;
38 use crypto::mac::{Mac,MacResult};
39 use crypto::hmac::Hmac;
40 use crypto::digest::Digest;
41 use crypto::symmetriccipher::SynchronousStreamCipher;
42
43 use std::{ptr, mem};
44 use std::collections::HashMap;
45 use std::collections::hash_map;
46 use std::io::Cursor;
47 use std::sync::{Mutex,MutexGuard,Arc};
48 use std::sync::atomic::{AtomicUsize, Ordering};
49 use std::time::{Instant,Duration};
50
51 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
52 ///
53 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
54 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
55 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
56 ///
57 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
58 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
59 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
60 /// the HTLC backwards along the relevant path).
61 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
62 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
63 mod channel_held_info {
64         use ln::msgs;
65         use ln::router::Route;
66         use secp256k1::key::SecretKey;
67         use secp256k1::ecdh::SharedSecret;
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: SharedSecret,
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: SharedSecret,
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 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
225 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
226 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
227 /// probably increase this significantly.
228 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
229
230 struct HTLCForwardInfo {
231         prev_short_channel_id: u64,
232         prev_htlc_id: u64,
233         forward_info: PendingForwardHTLCInfo,
234 }
235
236 struct ChannelHolder {
237         by_id: HashMap<[u8; 32], Channel>,
238         short_to_id: HashMap<u64, [u8; 32]>,
239         next_forward: Instant,
240         /// short channel id -> forward infos. Key of 0 means payments received
241         /// Note that while this is held in the same mutex as the channels themselves, no consistency
242         /// guarantees are made about there existing a channel with the short id here, nor the short
243         /// ids in the PendingForwardHTLCInfo!
244         forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
245         /// Note that while this is held in the same mutex as the channels themselves, no consistency
246         /// guarantees are made about the channels given here actually existing anymore by the time you
247         /// go to read them!
248         claimable_htlcs: HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
249 }
250 struct MutChannelHolder<'a> {
251         by_id: &'a mut HashMap<[u8; 32], Channel>,
252         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
253         next_forward: &'a mut Instant,
254         forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
255         claimable_htlcs: &'a mut HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
256 }
257 impl ChannelHolder {
258         fn borrow_parts(&mut self) -> MutChannelHolder {
259                 MutChannelHolder {
260                         by_id: &mut self.by_id,
261                         short_to_id: &mut self.short_to_id,
262                         next_forward: &mut self.next_forward,
263                         forward_htlcs: &mut self.forward_htlcs,
264                         claimable_htlcs: &mut self.claimable_htlcs,
265                 }
266         }
267 }
268
269 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
270 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
271
272 /// Manager which keeps track of a number of channels and sends messages to the appropriate
273 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
274 ///
275 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
276 /// to individual Channels.
277 pub struct ChannelManager {
278         genesis_hash: Sha256dHash,
279         fee_estimator: Arc<FeeEstimator>,
280         monitor: Arc<ManyChannelMonitor>,
281         chain_monitor: Arc<ChainWatchInterface>,
282         tx_broadcaster: Arc<BroadcasterInterface>,
283
284         announce_channels_publicly: bool,
285         fee_proportional_millionths: u32,
286         latest_block_height: AtomicUsize,
287         secp_ctx: Secp256k1<secp256k1::All>,
288
289         channel_state: Mutex<ChannelHolder>,
290         our_network_key: SecretKey,
291
292         pending_events: Mutex<Vec<events::Event>>,
293
294         logger: Arc<Logger>,
295 }
296
297 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
298 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
299 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
300 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
301 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
302 const CLTV_EXPIRY_DELTA: u16 = 6 * 24 * 2; //TODO?
303 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
304
305 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS, ie that
306 // if the next-hop peer fails the HTLC within HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have
307 // HTLC_FAIL_TIMEOUT_BLOCKS left to fail it backwards ourselves before hitting the
308 // CLTV_CLAIM_BUFFER point and failing the channel on-chain to time out the HTLC.
309 #[deny(const_err)]
310 #[allow(dead_code)]
311 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER;
312
313 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
314 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
315 #[deny(const_err)]
316 #[allow(dead_code)]
317 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
318
319 macro_rules! secp_call {
320         ( $res: expr, $err: expr ) => {
321                 match $res {
322                         Ok(key) => key,
323                         Err(_) => return Err($err),
324                 }
325         };
326 }
327
328 struct OnionKeys {
329         #[cfg(test)]
330         shared_secret: SharedSecret,
331         #[cfg(test)]
332         blinding_factor: [u8; 32],
333         ephemeral_pubkey: PublicKey,
334         rho: [u8; 32],
335         mu: [u8; 32],
336 }
337
338 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
339 pub struct ChannelDetails {
340         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
341         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
342         /// Note that this means this value is *not* persistent - it can change once during the
343         /// lifetime of the channel.
344         pub channel_id: [u8; 32],
345         /// The position of the funding transaction in the chain. None if the funding transaction has
346         /// not yet been confirmed and the channel fully opened.
347         pub short_channel_id: Option<u64>,
348         /// The node_id of our counterparty
349         pub remote_network_id: PublicKey,
350         /// The value, in satoshis, of this channel as appears in the funding output
351         pub channel_value_satoshis: u64,
352         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
353         pub user_id: u64,
354 }
355
356 impl ChannelManager {
357         /// Constructs a new ChannelManager to hold several channels and route between them.
358         ///
359         /// This is the main "logic hub" for all channel-related actions, and implements
360         /// ChannelMessageHandler.
361         ///
362         /// fee_proportional_millionths is an optional fee to charge any payments routed through us.
363         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
364         ///
365         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
366         pub fn new(our_network_key: SecretKey, fee_proportional_millionths: u32, announce_channels_publicly: bool, network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>) -> Result<Arc<ChannelManager>, secp256k1::Error> {
367                 let secp_ctx = Secp256k1::new();
368
369                 let res = Arc::new(ChannelManager {
370                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
371                         fee_estimator: feeest.clone(),
372                         monitor: monitor.clone(),
373                         chain_monitor,
374                         tx_broadcaster,
375
376                         announce_channels_publicly,
377                         fee_proportional_millionths,
378                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value (generally need to replay recent chain on chain_monitor registration)
379                         secp_ctx,
380
381                         channel_state: Mutex::new(ChannelHolder{
382                                 by_id: HashMap::new(),
383                                 short_to_id: HashMap::new(),
384                                 next_forward: Instant::now(),
385                                 forward_htlcs: HashMap::new(),
386                                 claimable_htlcs: HashMap::new(),
387                         }),
388                         our_network_key,
389
390                         pending_events: Mutex::new(Vec::new()),
391
392                         logger,
393                 });
394                 let weak_res = Arc::downgrade(&res);
395                 res.chain_monitor.register_listener(weak_res);
396                 Ok(res)
397         }
398
399         /// Creates a new outbound channel to the given remote node and with the given value.
400         ///
401         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
402         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
403         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
404         /// may wish to avoid using 0 for user_id here.
405         ///
406         /// If successful, will generate a SendOpenChannel event, so you should probably poll
407         /// PeerManager::process_events afterwards.
408         ///
409         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat being greater than channel_value_satoshis * 1k
410         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
411                 let chan_keys = if cfg!(feature = "fuzztarget") {
412                         ChannelKeys {
413                                 funding_key:               SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
414                                 revocation_base_key:       SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
415                                 payment_base_key:          SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
416                                 delayed_payment_base_key:  SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
417                                 htlc_base_key:             SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
418                                 channel_close_key:         SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
419                                 channel_monitor_claim_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
420                                 commitment_seed: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
421                         }
422                 } else {
423                         let mut key_seed = [0u8; 32];
424                         rng::fill_bytes(&mut key_seed);
425                         match ChannelKeys::new_from_seed(&key_seed) {
426                                 Ok(key) => key,
427                                 Err(_) => panic!("RNG is busted!")
428                         }
429                 };
430
431                 let channel = Channel::new_outbound(&*self.fee_estimator, chan_keys, their_network_key, channel_value_satoshis, push_msat, self.announce_channels_publicly, user_id, Arc::clone(&self.logger))?;
432                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
433                 let mut channel_state = self.channel_state.lock().unwrap();
434                 match channel_state.by_id.entry(channel.channel_id()) {
435                         hash_map::Entry::Occupied(_) => {
436                                 if cfg!(feature = "fuzztarget") {
437                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
438                                 } else {
439                                         panic!("RNG is bad???");
440                                 }
441                         },
442                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
443                 }
444
445                 let mut events = self.pending_events.lock().unwrap();
446                 events.push(events::Event::SendOpenChannel {
447                         node_id: their_network_key,
448                         msg: res,
449                 });
450                 Ok(())
451         }
452
453         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
454         /// more information.
455         pub fn list_channels(&self) -> Vec<ChannelDetails> {
456                 let channel_state = self.channel_state.lock().unwrap();
457                 let mut res = Vec::with_capacity(channel_state.by_id.len());
458                 for (channel_id, channel) in channel_state.by_id.iter() {
459                         res.push(ChannelDetails {
460                                 channel_id: (*channel_id).clone(),
461                                 short_channel_id: channel.get_short_channel_id(),
462                                 remote_network_id: channel.get_their_node_id(),
463                                 channel_value_satoshis: channel.get_value_satoshis(),
464                                 user_id: channel.get_user_id(),
465                         });
466                 }
467                 res
468         }
469
470         /// Gets the list of usable channels, in random order. Useful as an argument to
471         /// Router::get_route to ensure non-announced channels are used.
472         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
473                 let channel_state = self.channel_state.lock().unwrap();
474                 let mut res = Vec::with_capacity(channel_state.by_id.len());
475                 for (channel_id, channel) in channel_state.by_id.iter() {
476                         // Note we use is_live here instead of usable which leads to somewhat confused
477                         // internal/external nomenclature, but that's ok cause that's probably what the user
478                         // really wanted anyway.
479                         if channel.is_live() {
480                                 res.push(ChannelDetails {
481                                         channel_id: (*channel_id).clone(),
482                                         short_channel_id: channel.get_short_channel_id(),
483                                         remote_network_id: channel.get_their_node_id(),
484                                         channel_value_satoshis: channel.get_value_satoshis(),
485                                         user_id: channel.get_user_id(),
486                                 });
487                         }
488                 }
489                 res
490         }
491
492         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
493         /// will be accepted on the given channel, and after additional timeout/the closing of all
494         /// pending HTLCs, the channel will be closed on chain.
495         ///
496         /// May generate a SendShutdown event on success, which should be relayed.
497         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
498                 let (mut res, node_id, chan_option) = {
499                         let mut channel_state_lock = self.channel_state.lock().unwrap();
500                         let channel_state = channel_state_lock.borrow_parts();
501                         match channel_state.by_id.entry(channel_id.clone()) {
502                                 hash_map::Entry::Occupied(mut chan_entry) => {
503                                         let res = chan_entry.get_mut().get_shutdown()?;
504                                         if chan_entry.get().is_shutdown() {
505                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
506                                                         channel_state.short_to_id.remove(&short_id);
507                                                 }
508                                                 (res, chan_entry.get().get_their_node_id(), Some(chan_entry.remove_entry().1))
509                                         } else { (res, chan_entry.get().get_their_node_id(), None) }
510                                 },
511                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
512                         }
513                 };
514                 for htlc_source in res.1.drain(..) {
515                         // unknown_next_peer...I dunno who that is anymore....
516                         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() });
517                 }
518                 let chan_update = if let Some(chan) = chan_option {
519                         if let Ok(update) = self.get_channel_update(&chan) {
520                                 Some(update)
521                         } else { None }
522                 } else { None };
523
524                 let mut events = self.pending_events.lock().unwrap();
525                 if let Some(update) = chan_update {
526                         events.push(events::Event::BroadcastChannelUpdate {
527                                 msg: update
528                         });
529                 }
530                 events.push(events::Event::SendShutdown {
531                         node_id,
532                         msg: res.0
533                 });
534
535                 Ok(())
536         }
537
538         #[inline]
539         fn finish_force_close_channel(&self, shutdown_res: (Vec<Transaction>, Vec<(HTLCSource, [u8; 32])>)) {
540                 let (local_txn, mut failed_htlcs) = shutdown_res;
541                 for htlc_source in failed_htlcs.drain(..) {
542                         // unknown_next_peer...I dunno who that is anymore....
543                         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() });
544                 }
545                 for tx in local_txn {
546                         self.tx_broadcaster.broadcast_transaction(&tx);
547                 }
548                 //TODO: We need to have a way where outbound HTLC claims can result in us claiming the
549                 //now-on-chain HTLC output for ourselves (and, thereafter, passing the HTLC backwards).
550                 //TODO: We need to handle monitoring of pending offered HTLCs which just hit the chain and
551                 //may be claimed, resulting in us claiming the inbound HTLCs (and back-failing after
552                 //timeouts are hit and our claims confirm).
553                 //TODO: In any case, we need to make sure we remove any pending htlc tracking (via
554                 //fail_backwards or claim_funds) eventually for all HTLCs that were in the channel
555         }
556
557         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
558         /// the chain and rejecting new HTLCs on the given channel.
559         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
560                 let mut chan = {
561                         let mut channel_state_lock = self.channel_state.lock().unwrap();
562                         let channel_state = channel_state_lock.borrow_parts();
563                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
564                                 if let Some(short_id) = chan.get_short_channel_id() {
565                                         channel_state.short_to_id.remove(&short_id);
566                                 }
567                                 chan
568                         } else {
569                                 return;
570                         }
571                 };
572                 self.finish_force_close_channel(chan.force_shutdown());
573                 let mut events = self.pending_events.lock().unwrap();
574                 if let Ok(update) = self.get_channel_update(&chan) {
575                         events.push(events::Event::BroadcastChannelUpdate {
576                                 msg: update
577                         });
578                 }
579         }
580
581         /// Force close all channels, immediately broadcasting the latest local commitment transaction
582         /// for each to the chain and rejecting new HTLCs on each.
583         pub fn force_close_all_channels(&self) {
584                 for chan in self.list_channels() {
585                         self.force_close_channel(&chan.channel_id);
586                 }
587         }
588
589         #[inline]
590         fn gen_rho_mu_from_shared_secret(shared_secret: &SharedSecret) -> ([u8; 32], [u8; 32]) {
591                 ({
592                         let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
593                         hmac.input(&shared_secret[..]);
594                         let mut res = [0; 32];
595                         hmac.raw_result(&mut res);
596                         res
597                 },
598                 {
599                         let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
600                         hmac.input(&shared_secret[..]);
601                         let mut res = [0; 32];
602                         hmac.raw_result(&mut res);
603                         res
604                 })
605         }
606
607         #[inline]
608         fn gen_um_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
609                 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
610                 hmac.input(&shared_secret[..]);
611                 let mut res = [0; 32];
612                 hmac.raw_result(&mut res);
613                 res
614         }
615
616         #[inline]
617         fn gen_ammag_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
618                 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
619                 hmac.input(&shared_secret[..]);
620                 let mut res = [0; 32];
621                 hmac.raw_result(&mut res);
622                 res
623         }
624
625         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
626         #[inline]
627         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> {
628                 let mut blinded_priv = session_priv.clone();
629                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
630
631                 for hop in route.hops.iter() {
632                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
633
634                         let mut sha = Sha256::new();
635                         sha.input(&blinded_pub.serialize()[..]);
636                         sha.input(&shared_secret[..]);
637                         let mut blinding_factor = [0u8; 32];
638                         sha.result(&mut blinding_factor);
639
640                         let ephemeral_pubkey = blinded_pub;
641
642                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
643                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
644
645                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
646                 }
647
648                 Ok(())
649         }
650
651         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
652         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
653                 let mut res = Vec::with_capacity(route.hops.len());
654
655                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
656                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
657
658                         res.push(OnionKeys {
659                                 #[cfg(test)]
660                                 shared_secret,
661                                 #[cfg(test)]
662                                 blinding_factor: _blinding_factor,
663                                 ephemeral_pubkey,
664                                 rho,
665                                 mu,
666                         });
667                 })?;
668
669                 Ok(res)
670         }
671
672         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
673         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
674                 let mut cur_value_msat = 0u64;
675                 let mut cur_cltv = starting_htlc_offset;
676                 let mut last_short_channel_id = 0;
677                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
678                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
679                 unsafe { res.set_len(route.hops.len()); }
680
681                 for (idx, hop) in route.hops.iter().enumerate().rev() {
682                         // First hop gets special values so that it can check, on receipt, that everything is
683                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
684                         // the intended recipient).
685                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
686                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
687                         res[idx] = msgs::OnionHopData {
688                                 realm: 0,
689                                 data: msgs::OnionRealm0HopData {
690                                         short_channel_id: last_short_channel_id,
691                                         amt_to_forward: value_msat,
692                                         outgoing_cltv_value: cltv,
693                                 },
694                                 hmac: [0; 32],
695                         };
696                         cur_value_msat += hop.fee_msat;
697                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
698                                 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
699                         }
700                         cur_cltv += hop.cltv_expiry_delta as u32;
701                         if cur_cltv >= 500000000 {
702                                 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
703                         }
704                         last_short_channel_id = hop.short_channel_id;
705                 }
706                 Ok((res, cur_value_msat, cur_cltv))
707         }
708
709         #[inline]
710         fn shift_arr_right(arr: &mut [u8; 20*65]) {
711                 unsafe {
712                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
713                 }
714                 for i in 0..65 {
715                         arr[i] = 0;
716                 }
717         }
718
719         #[inline]
720         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
721                 assert_eq!(dst.len(), src.len());
722
723                 for i in 0..dst.len() {
724                         dst[i] ^= src[i];
725                 }
726         }
727
728         const ZERO:[u8; 21*65] = [0; 21*65];
729         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &[u8; 32]) -> msgs::OnionPacket {
730                 let mut buf = Vec::with_capacity(21*65);
731                 buf.resize(21*65, 0);
732
733                 let filler = {
734                         let iters = payloads.len() - 1;
735                         let end_len = iters * 65;
736                         let mut res = Vec::with_capacity(end_len);
737                         res.resize(end_len, 0);
738
739                         for (i, keys) in onion_keys.iter().enumerate() {
740                                 if i == payloads.len() - 1 { continue; }
741                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
742                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
743                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
744                         }
745                         res
746                 };
747
748                 let mut packet_data = [0; 20*65];
749                 let mut hmac_res = [0; 32];
750
751                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
752                         ChannelManager::shift_arr_right(&mut packet_data);
753                         payload.hmac = hmac_res;
754                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
755
756                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
757                         chacha.process(&packet_data, &mut buf[0..20*65]);
758                         packet_data[..].copy_from_slice(&buf[0..20*65]);
759
760                         if i == 0 {
761                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
762                         }
763
764                         let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
765                         hmac.input(&packet_data);
766                         hmac.input(&associated_data[..]);
767                         hmac.raw_result(&mut hmac_res);
768                 }
769
770                 msgs::OnionPacket{
771                         version: 0,
772                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
773                         hop_data: packet_data,
774                         hmac: hmac_res,
775                 }
776         }
777
778         /// Encrypts a failure packet. raw_packet can either be a
779         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
780         fn encrypt_failure_packet(shared_secret: &SharedSecret, raw_packet: &[u8]) -> msgs::OnionErrorPacket {
781                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
782
783                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
784                 packet_crypted.resize(raw_packet.len(), 0);
785                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
786                 chacha.process(&raw_packet, &mut packet_crypted[..]);
787                 msgs::OnionErrorPacket {
788                         data: packet_crypted,
789                 }
790         }
791
792         fn build_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
793                 assert!(failure_data.len() <= 256 - 2);
794
795                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
796
797                 let failuremsg = {
798                         let mut res = Vec::with_capacity(2 + failure_data.len());
799                         res.push(((failure_type >> 8) & 0xff) as u8);
800                         res.push(((failure_type >> 0) & 0xff) as u8);
801                         res.extend_from_slice(&failure_data[..]);
802                         res
803                 };
804                 let pad = {
805                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
806                         res.resize(256 - 2 - failure_data.len(), 0);
807                         res
808                 };
809                 let mut packet = msgs::DecodedOnionErrorPacket {
810                         hmac: [0; 32],
811                         failuremsg: failuremsg,
812                         pad: pad,
813                 };
814
815                 let mut hmac = Hmac::new(Sha256::new(), &um);
816                 hmac.input(&packet.encode()[32..]);
817                 hmac.raw_result(&mut packet.hmac);
818
819                 packet
820         }
821
822         #[inline]
823         fn build_first_hop_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
824                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
825                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
826         }
827
828         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
829                 macro_rules! get_onion_hash {
830                         () => {
831                                 {
832                                         let mut sha = Sha256::new();
833                                         sha.input(&msg.onion_routing_packet.hop_data);
834                                         let mut onion_hash = [0; 32];
835                                         sha.result(&mut onion_hash);
836                                         onion_hash
837                                 }
838                         }
839                 }
840
841                 if let Err(_) = msg.onion_routing_packet.public_key {
842                         log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
843                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
844                                 channel_id: msg.channel_id,
845                                 htlc_id: msg.htlc_id,
846                                 sha256_of_onion: get_onion_hash!(),
847                                 failure_code: 0x8000 | 0x4000 | 6,
848                         })), self.channel_state.lock().unwrap());
849                 }
850
851                 let shared_secret = SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key);
852                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
853
854                 let mut channel_state = None;
855                 macro_rules! return_err {
856                         ($msg: expr, $err_code: expr, $data: expr) => {
857                                 {
858                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
859                                         if channel_state.is_none() {
860                                                 channel_state = Some(self.channel_state.lock().unwrap());
861                                         }
862                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
863                                                 channel_id: msg.channel_id,
864                                                 htlc_id: msg.htlc_id,
865                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
866                                         })), channel_state.unwrap());
867                                 }
868                         }
869                 }
870
871                 if msg.onion_routing_packet.version != 0 {
872                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
873                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
874                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
875                         //receiving node would have to brute force to figure out which version was put in the
876                         //packet by the node that send us the message, in the case of hashing the hop_data, the
877                         //node knows the HMAC matched, so they already know what is there...
878                         return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
879                 }
880
881                 let mut hmac = Hmac::new(Sha256::new(), &mu);
882                 hmac.input(&msg.onion_routing_packet.hop_data);
883                 hmac.input(&msg.payment_hash);
884                 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
885                         return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
886                 }
887
888                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
889                 let next_hop_data = {
890                         let mut decoded = [0; 65];
891                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
892                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
893                                 Err(err) => {
894                                         let error_code = match err {
895                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
896                                                 _ => 0x2000 | 2, // Should never happen
897                                         };
898                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
899                                 },
900                                 Ok(msg) => msg
901                         }
902                 };
903
904                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
905                                 // OUR PAYMENT!
906                                 // final_expiry_too_soon
907                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
908                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
909                                 }
910                                 // final_incorrect_htlc_amount
911                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
912                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
913                                 }
914                                 // final_incorrect_cltv_expiry
915                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
916                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
917                                 }
918
919                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
920                                 // message, however that would leak that we are the recipient of this payment, so
921                                 // instead we stay symmetric with the forwarding case, only responding (after a
922                                 // delay) once they've send us a commitment_signed!
923
924                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
925                                         onion_packet: None,
926                                         payment_hash: msg.payment_hash.clone(),
927                                         short_channel_id: 0,
928                                         incoming_shared_secret: shared_secret.clone(),
929                                         amt_to_forward: next_hop_data.data.amt_to_forward,
930                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
931                                 })
932                         } else {
933                                 let mut new_packet_data = [0; 20*65];
934                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
935                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
936
937                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
938
939                                 let blinding_factor = {
940                                         let mut sha = Sha256::new();
941                                         sha.input(&new_pubkey.serialize()[..]);
942                                         sha.input(&shared_secret[..]);
943                                         let mut res = [0u8; 32];
944                                         sha.result(&mut res);
945                                         match SecretKey::from_slice(&self.secp_ctx, &res) {
946                                                 Err(_) => {
947                                                         return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
948                                                 },
949                                                 Ok(key) => key
950                                         }
951                                 };
952
953                                 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
954                                         return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
955                                 }
956
957                                 let outgoing_packet = msgs::OnionPacket {
958                                         version: 0,
959                                         public_key: Ok(new_pubkey),
960                                         hop_data: new_packet_data,
961                                         hmac: next_hop_data.hmac.clone(),
962                                 };
963
964                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
965                                         onion_packet: Some(outgoing_packet),
966                                         payment_hash: msg.payment_hash.clone(),
967                                         short_channel_id: next_hop_data.data.short_channel_id,
968                                         incoming_shared_secret: shared_secret.clone(),
969                                         amt_to_forward: next_hop_data.data.amt_to_forward,
970                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
971                                 })
972                         };
973
974                 channel_state = Some(self.channel_state.lock().unwrap());
975                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
976                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
977                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
978                                 let forwarding_id = match id_option {
979                                         None => { // unknown_next_peer
980                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
981                                         },
982                                         Some(id) => id.clone(),
983                                 };
984                                 if let Some((err, code, chan_update)) = loop {
985                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
986
987                                         if !chan.is_live() { // channel_disabled
988                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
989                                         }
990                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
991                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
992                                         }
993                                         let fee = amt_to_forward.checked_mul(self.fee_proportional_millionths as u64).and_then(|prop_fee| { (prop_fee / 1000000).checked_add(chan.get_our_fee_base_msat(&*self.fee_estimator) as u64) });
994                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
995                                                 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())));
996                                         }
997                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
998                                                 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())));
999                                         }
1000                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1001                                         // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1002                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1003                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1004                                         }
1005                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1006                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1007                                         }
1008                                         break None;
1009                                 }
1010                                 {
1011                                         let mut res = Vec::with_capacity(8 + 128);
1012                                         if code == 0x1000 | 11 || code == 0x1000 | 12 {
1013                                                 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1014                                         }
1015                                         else if code == 0x1000 | 13 {
1016                                                 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1017                                         }
1018                                         if let Some(chan_update) = chan_update {
1019                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1020                                         }
1021                                         return_err!(err, code, &res[..]);
1022                                 }
1023                         }
1024                 }
1025
1026                 (pending_forward_info, channel_state.unwrap())
1027         }
1028
1029         /// only fails if the channel does not yet have an assigned short_id
1030         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1031                 let short_channel_id = match chan.get_short_channel_id() {
1032                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
1033                         Some(id) => id,
1034                 };
1035
1036                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1037
1038                 let unsigned = msgs::UnsignedChannelUpdate {
1039                         chain_hash: self.genesis_hash,
1040                         short_channel_id: short_channel_id,
1041                         timestamp: chan.get_channel_update_count(),
1042                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1043                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1044                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1045                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1046                         fee_proportional_millionths: self.fee_proportional_millionths,
1047                         excess_data: Vec::new(),
1048                 };
1049
1050                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1051                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1052
1053                 Ok(msgs::ChannelUpdate {
1054                         signature: sig,
1055                         contents: unsigned
1056                 })
1057         }
1058
1059         /// Sends a payment along a given route.
1060         ///
1061         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1062         /// fields for more info.
1063         ///
1064         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1065         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1066         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1067         /// specified in the last hop in the route! Thus, you should probably do your own
1068         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1069         /// payment") and prevent double-sends yourself.
1070         ///
1071         /// May generate a SendHTLCs event on success, which should be relayed.
1072         ///
1073         /// Raises APIError::RoutError when invalid route or forward parameter
1074         /// (cltv_delta, fee, node public key) is specified
1075         pub fn send_payment(&self, route: Route, payment_hash: [u8; 32]) -> Result<(), APIError> {
1076                 if route.hops.len() < 1 || route.hops.len() > 20 {
1077                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1078                 }
1079                 let our_node_id = self.get_our_node_id();
1080                 for (idx, hop) in route.hops.iter().enumerate() {
1081                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1082                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1083                         }
1084                 }
1085
1086                 let session_priv = SecretKey::from_slice(&self.secp_ctx, &{
1087                         let mut session_key = [0; 32];
1088                         rng::fill_bytes(&mut session_key);
1089                         session_key
1090                 }).expect("RNG is bad!");
1091
1092                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1093
1094                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1095                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1096                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1097                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1098
1099                 let (first_hop_node_id, (update_add, commitment_signed, chan_monitor)) = {
1100                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1101                         let channel_state = channel_state_lock.borrow_parts();
1102
1103                         let id = match channel_state.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1104                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1105                                 Some(id) => id.clone(),
1106                         };
1107
1108                         let res = {
1109                                 let chan = channel_state.by_id.get_mut(&id).unwrap();
1110                                 if chan.get_their_node_id() != route.hops.first().unwrap().pubkey {
1111                                         return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1112                                 }
1113                                 if !chan.is_live() {
1114                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected!"});
1115                                 }
1116                                 chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1117                                         route: route.clone(),
1118                                         session_priv: session_priv.clone(),
1119                                         first_hop_htlc_msat: htlc_msat,
1120                                 }, onion_packet).map_err(|he| APIError::ChannelUnavailable{err: he.err})?
1121                         };
1122
1123                         let first_hop_node_id = route.hops.first().unwrap().pubkey;
1124
1125                         match res {
1126                                 Some(msgs) => (first_hop_node_id, msgs),
1127                                 None => return Ok(()),
1128                         }
1129                 };
1130
1131                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1132                         unimplemented!();
1133                 }
1134
1135                 let mut events = self.pending_events.lock().unwrap();
1136                 events.push(events::Event::UpdateHTLCs {
1137                         node_id: first_hop_node_id,
1138                         updates: msgs::CommitmentUpdate {
1139                                 update_add_htlcs: vec![update_add],
1140                                 update_fulfill_htlcs: Vec::new(),
1141                                 update_fail_htlcs: Vec::new(),
1142                                 update_fail_malformed_htlcs: Vec::new(),
1143                                 update_fee: None,
1144                                 commitment_signed,
1145                         },
1146                 });
1147                 Ok(())
1148         }
1149
1150         /// Call this upon creation of a funding transaction for the given channel.
1151         ///
1152         /// Panics if a funding transaction has already been provided for this channel.
1153         ///
1154         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1155         /// be trivially prevented by using unique funding transaction keys per-channel).
1156         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1157                 macro_rules! add_pending_event {
1158                         ($event: expr) => {
1159                                 {
1160                                         let mut pending_events = self.pending_events.lock().unwrap();
1161                                         pending_events.push($event);
1162                                 }
1163                         }
1164                 }
1165
1166                 let (chan, msg, chan_monitor) = {
1167                         let mut channel_state = self.channel_state.lock().unwrap();
1168                         match channel_state.by_id.remove(temporary_channel_id) {
1169                                 Some(mut chan) => {
1170                                         match chan.get_outbound_funding_created(funding_txo) {
1171                                                 Ok(funding_msg) => {
1172                                                         (chan, funding_msg.0, funding_msg.1)
1173                                                 },
1174                                                 Err(e) => {
1175                                                         log_error!(self, "Got bad signatures: {}!", e.err);
1176                                                         mem::drop(channel_state);
1177                                                         add_pending_event!(events::Event::HandleError {
1178                                                                 node_id: chan.get_their_node_id(),
1179                                                                 action: e.action,
1180                                                         });
1181                                                         return;
1182                                                 },
1183                                         }
1184                                 },
1185                                 None => return
1186                         }
1187                 }; // Release channel lock for install_watch_outpoint call,
1188                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1189                         unimplemented!();
1190                 }
1191                 add_pending_event!(events::Event::SendFundingCreated {
1192                         node_id: chan.get_their_node_id(),
1193                         msg: msg,
1194                 });
1195
1196                 let mut channel_state = self.channel_state.lock().unwrap();
1197                 match channel_state.by_id.entry(chan.channel_id()) {
1198                         hash_map::Entry::Occupied(_) => {
1199                                 panic!("Generated duplicate funding txid?");
1200                         },
1201                         hash_map::Entry::Vacant(e) => {
1202                                 e.insert(chan);
1203                         }
1204                 }
1205         }
1206
1207         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1208                 if !chan.should_announce() { return None }
1209
1210                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1211                         Ok(res) => res,
1212                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1213                 };
1214                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1215                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1216
1217                 Some(msgs::AnnouncementSignatures {
1218                         channel_id: chan.channel_id(),
1219                         short_channel_id: chan.get_short_channel_id().unwrap(),
1220                         node_signature: our_node_sig,
1221                         bitcoin_signature: our_bitcoin_sig,
1222                 })
1223         }
1224
1225         /// Processes HTLCs which are pending waiting on random forward delay.
1226         ///
1227         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1228         /// Will likely generate further events.
1229         pub fn process_pending_htlc_forwards(&self) {
1230                 let mut new_events = Vec::new();
1231                 let mut failed_forwards = Vec::new();
1232                 {
1233                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1234                         let channel_state = channel_state_lock.borrow_parts();
1235
1236                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1237                                 return;
1238                         }
1239
1240                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1241                                 if short_chan_id != 0 {
1242                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1243                                                 Some(chan_id) => chan_id.clone(),
1244                                                 None => {
1245                                                         failed_forwards.reserve(pending_forwards.len());
1246                                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1247                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1248                                                                         short_channel_id: prev_short_channel_id,
1249                                                                         htlc_id: prev_htlc_id,
1250                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1251                                                                 });
1252                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1253                                                         }
1254                                                         continue;
1255                                                 }
1256                                         };
1257                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1258
1259                                         let mut add_htlc_msgs = Vec::new();
1260                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1261                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1262                                                         short_channel_id: prev_short_channel_id,
1263                                                         htlc_id: prev_htlc_id,
1264                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1265                                                 });
1266                                                 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()) {
1267                                                         Err(_e) => {
1268                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1269                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1270                                                                 continue;
1271                                                         },
1272                                                         Ok(update_add) => {
1273                                                                 match update_add {
1274                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1275                                                                         None => {
1276                                                                                 // Nothing to do here...we're waiting on a remote
1277                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1278                                                                                 // will automatically handle building the update_add_htlc and
1279                                                                                 // commitment_signed messages when we can.
1280                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1281                                                                                 // as we don't really want others relying on us relaying through
1282                                                                                 // this channel currently :/.
1283                                                                         }
1284                                                                 }
1285                                                         }
1286                                                 }
1287                                         }
1288
1289                                         if !add_htlc_msgs.is_empty() {
1290                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1291                                                         Ok(res) => res,
1292                                                         Err(e) => {
1293                                                                 if let &Some(msgs::ErrorAction::DisconnectPeer{msg: Some(ref _err_msg)}) = &e.action {
1294                                                                 } else if let &Some(msgs::ErrorAction::SendErrorMessage{msg: ref _err_msg}) = &e.action {
1295                                                                 } else {
1296                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1297                                                                 }
1298                                                                 //TODO: Handle...this is bad!
1299                                                                 continue;
1300                                                         },
1301                                                 };
1302                                                 new_events.push((Some(monitor), events::Event::UpdateHTLCs {
1303                                                         node_id: forward_chan.get_their_node_id(),
1304                                                         updates: msgs::CommitmentUpdate {
1305                                                                 update_add_htlcs: add_htlc_msgs,
1306                                                                 update_fulfill_htlcs: Vec::new(),
1307                                                                 update_fail_htlcs: Vec::new(),
1308                                                                 update_fail_malformed_htlcs: Vec::new(),
1309                                                                 update_fee: None,
1310                                                                 commitment_signed: commitment_msg,
1311                                                         },
1312                                                 }));
1313                                         }
1314                                 } else {
1315                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1316                                                 let prev_hop_data = HTLCPreviousHopData {
1317                                                         short_channel_id: prev_short_channel_id,
1318                                                         htlc_id: prev_htlc_id,
1319                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1320                                                 };
1321                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1322                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1323                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1324                                                 };
1325                                                 new_events.push((None, events::Event::PaymentReceived {
1326                                                         payment_hash: forward_info.payment_hash,
1327                                                         amt: forward_info.amt_to_forward,
1328                                                 }));
1329                                         }
1330                                 }
1331                         }
1332                 }
1333
1334                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1335                         match update {
1336                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1337                                 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() }),
1338                         };
1339                 }
1340
1341                 if new_events.is_empty() { return }
1342
1343                 new_events.retain(|event| {
1344                         if let &Some(ref monitor) = &event.0 {
1345                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor.clone()) {
1346                                         unimplemented!();// but def dont push the event...
1347                                 }
1348                         }
1349                         true
1350                 });
1351
1352                 let mut events = self.pending_events.lock().unwrap();
1353                 events.reserve(new_events.len());
1354                 for event in new_events.drain(..) {
1355                         events.push(event.1);
1356                 }
1357         }
1358
1359         /// Indicates that the preimage for payment_hash is unknown after a PaymentReceived event.
1360         pub fn fail_htlc_backwards(&self, payment_hash: &[u8; 32]) -> bool {
1361                 // TODO: Add ability to return 0x4000|16 (incorrect_payment_amount) if the amount we
1362                 // received is < expected or > 2*expected
1363                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1364                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1365                 if let Some(mut sources) = removed_source {
1366                         for htlc_with_hash in sources.drain(..) {
1367                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1368                                 self.fail_htlc_backwards_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: Vec::new() });
1369                         }
1370                         true
1371                 } else { false }
1372         }
1373
1374         /// Fails an HTLC backwards to the sender of it to us.
1375         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1376         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1377         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1378         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1379         /// still-available channels.
1380         fn fail_htlc_backwards_internal(&self, mut channel_state: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &[u8; 32], onion_error: HTLCFailReason) {
1381                 match source {
1382                         HTLCSource::OutboundRoute { .. } => {
1383                                 mem::drop(channel_state);
1384                                 if let &HTLCFailReason::ErrorPacket { ref err } = &onion_error {
1385                                         let (channel_update, payment_retryable) = self.process_onion_failure(&source, err.data.clone());
1386                                         let mut pending_events = self.pending_events.lock().unwrap();
1387                                         if let Some(channel_update) = channel_update {
1388                                                 pending_events.push(events::Event::PaymentFailureNetworkUpdate {
1389                                                         update: channel_update,
1390                                                 });
1391                                         }
1392                                         pending_events.push(events::Event::PaymentFailed {
1393                                                 payment_hash: payment_hash.clone(),
1394                                                 rejected_by_dest: !payment_retryable,
1395                                         });
1396                                 } else {
1397                                         panic!("should have onion error packet here");
1398                                 }
1399                         },
1400                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1401                                 let err_packet = match onion_error {
1402                                         HTLCFailReason::Reason { failure_code, data } => {
1403                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1404                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1405                                         },
1406                                         HTLCFailReason::ErrorPacket { err } => {
1407                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1408                                         }
1409                                 };
1410
1411                                 let (node_id, fail_msgs) = {
1412                                         let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1413                                                 Some(chan_id) => chan_id.clone(),
1414                                                 None => return
1415                                         };
1416
1417                                         let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1418                                         match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1419                                                 Ok(msg) => (chan.get_their_node_id(), msg),
1420                                                 Err(_e) => {
1421                                                         //TODO: Do something with e?
1422                                                         return;
1423                                                 },
1424                                         }
1425                                 };
1426
1427                                 match fail_msgs {
1428                                         Some((msg, commitment_msg, chan_monitor)) => {
1429                                                 mem::drop(channel_state);
1430
1431                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1432                                                         unimplemented!();// but def dont push the event...
1433                                                 }
1434
1435                                                 let mut pending_events = self.pending_events.lock().unwrap();
1436                                                 pending_events.push(events::Event::UpdateHTLCs {
1437                                                         node_id,
1438                                                         updates: msgs::CommitmentUpdate {
1439                                                                 update_add_htlcs: Vec::new(),
1440                                                                 update_fulfill_htlcs: Vec::new(),
1441                                                                 update_fail_htlcs: vec![msg],
1442                                                                 update_fail_malformed_htlcs: Vec::new(),
1443                                                                 update_fee: None,
1444                                                                 commitment_signed: commitment_msg,
1445                                                         },
1446                                                 });
1447                                         },
1448                                         None => {},
1449                                 }
1450                         },
1451                 }
1452         }
1453
1454         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1455         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1456         /// should probably kick the net layer to go send messages if this returns true!
1457         ///
1458         /// May panic if called except in response to a PaymentReceived event.
1459         pub fn claim_funds(&self, payment_preimage: [u8; 32]) -> bool {
1460                 let mut sha = Sha256::new();
1461                 sha.input(&payment_preimage);
1462                 let mut payment_hash = [0; 32];
1463                 sha.result(&mut payment_hash);
1464
1465                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1466                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1467                 if let Some(mut sources) = removed_source {
1468                         for htlc_with_hash in sources.drain(..) {
1469                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1470                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1471                         }
1472                         true
1473                 } else { false }
1474         }
1475         fn claim_funds_internal(&self, mut channel_state: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: [u8; 32]) {
1476                 match source {
1477                         HTLCSource::OutboundRoute { .. } => {
1478                                 mem::drop(channel_state);
1479                                 let mut pending_events = self.pending_events.lock().unwrap();
1480                                 pending_events.push(events::Event::PaymentSent {
1481                                         payment_preimage
1482                                 });
1483                         },
1484                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1485                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1486                                 let (node_id, fulfill_msgs) = {
1487                                         let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1488                                                 Some(chan_id) => chan_id.clone(),
1489                                                 None => {
1490                                                         // TODO: There is probably a channel manager somewhere that needs to
1491                                                         // learn the preimage as the channel already hit the chain and that's
1492                                                         // why its missing.
1493                                                         return
1494                                                 }
1495                                         };
1496
1497                                         let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1498                                         match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1499                                                 Ok(msg) => (chan.get_their_node_id(), msg),
1500                                                 Err(_e) => {
1501                                                         // TODO: There is probably a channel manager somewhere that needs to
1502                                                         // learn the preimage as the channel may be about to hit the chain.
1503                                                         //TODO: Do something with e?
1504                                                         return
1505                                                 },
1506                                         }
1507                                 };
1508
1509                                 mem::drop(channel_state);
1510                                 if let Some(chan_monitor) = fulfill_msgs.1 {
1511                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1512                                                 unimplemented!();// but def dont push the event...
1513                                         }
1514                                 }
1515
1516                                 if let Some((msg, commitment_msg)) = fulfill_msgs.0 {
1517                                         let mut pending_events = self.pending_events.lock().unwrap();
1518                                         pending_events.push(events::Event::UpdateHTLCs {
1519                                                 node_id: node_id,
1520                                                 updates: msgs::CommitmentUpdate {
1521                                                         update_add_htlcs: Vec::new(),
1522                                                         update_fulfill_htlcs: vec![msg],
1523                                                         update_fail_htlcs: Vec::new(),
1524                                                         update_fail_malformed_htlcs: Vec::new(),
1525                                                         update_fee: None,
1526                                                         commitment_signed: commitment_msg,
1527                                                 }
1528                                         });
1529                                 }
1530                         },
1531                 }
1532         }
1533
1534         /// Gets the node_id held by this ChannelManager
1535         pub fn get_our_node_id(&self) -> PublicKey {
1536                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1537         }
1538
1539         /// Used to restore channels to normal operation after a
1540         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1541         /// operation.
1542         pub fn test_restore_channel_monitor(&self) {
1543                 unimplemented!();
1544         }
1545
1546         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<msgs::AcceptChannel, MsgHandleErrInternal> {
1547                 if msg.chain_hash != self.genesis_hash {
1548                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1549                 }
1550                 let mut channel_state = self.channel_state.lock().unwrap();
1551                 if channel_state.by_id.contains_key(&msg.temporary_channel_id) {
1552                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone()));
1553                 }
1554
1555                 let chan_keys = if cfg!(feature = "fuzztarget") {
1556                         ChannelKeys {
1557                                 funding_key:               SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]).unwrap(),
1558                                 revocation_base_key:       SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0]).unwrap(),
1559                                 payment_base_key:          SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0]).unwrap(),
1560                                 delayed_payment_base_key:  SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0]).unwrap(),
1561                                 htlc_base_key:             SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0]).unwrap(),
1562                                 channel_close_key:         SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0]).unwrap(),
1563                                 channel_monitor_claim_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0]).unwrap(),
1564                                 commitment_seed: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1565                         }
1566                 } else {
1567                         let mut key_seed = [0u8; 32];
1568                         rng::fill_bytes(&mut key_seed);
1569                         match ChannelKeys::new_from_seed(&key_seed) {
1570                                 Ok(key) => key,
1571                                 Err(_) => panic!("RNG is busted!")
1572                         }
1573                 };
1574
1575                 let channel = Channel::new_from_req(&*self.fee_estimator, chan_keys, their_node_id.clone(), msg, 0, false, self.announce_channels_publicly, Arc::clone(&self.logger))
1576                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1577                 let accept_msg = channel.get_accept_channel();
1578                 channel_state.by_id.insert(channel.channel_id(), channel);
1579                 Ok(accept_msg)
1580         }
1581
1582         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1583                 let (value, output_script, user_id) = {
1584                         let mut channel_state = self.channel_state.lock().unwrap();
1585                         match channel_state.by_id.get_mut(&msg.temporary_channel_id) {
1586                                 Some(chan) => {
1587                                         if chan.get_their_node_id() != *their_node_id {
1588                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1589                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1590                                         }
1591                                         chan.accept_channel(&msg)
1592                                                 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.temporary_channel_id))?;
1593                                         (chan.get_value_satoshis(), chan.get_funding_redeemscript().to_v0_p2wsh(), chan.get_user_id())
1594                                 },
1595                                 //TODO: same as above
1596                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1597                         }
1598                 };
1599                 let mut pending_events = self.pending_events.lock().unwrap();
1600                 pending_events.push(events::Event::FundingGenerationReady {
1601                         temporary_channel_id: msg.temporary_channel_id,
1602                         channel_value_satoshis: value,
1603                         output_script: output_script,
1604                         user_channel_id: user_id,
1605                 });
1606                 Ok(())
1607         }
1608
1609         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<msgs::FundingSigned, MsgHandleErrInternal> {
1610                 let (chan, funding_msg, monitor_update) = {
1611                         let mut channel_state = self.channel_state.lock().unwrap();
1612                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1613                                 hash_map::Entry::Occupied(mut chan) => {
1614                                         if chan.get().get_their_node_id() != *their_node_id {
1615                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1616                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1617                                         }
1618                                         match chan.get_mut().funding_created(msg) {
1619                                                 Ok((funding_msg, monitor_update)) => {
1620                                                         (chan.remove(), funding_msg, monitor_update)
1621                                                 },
1622                                                 Err(e) => {
1623                                                         return Err(e).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1624                                                 }
1625                                         }
1626                                 },
1627                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1628                         }
1629                 }; // Release channel lock for install_watch_outpoint call,
1630                    // note that this means if the remote end is misbehaving and sends a message for the same
1631                    // channel back-to-back with funding_created, we'll end up thinking they sent a message
1632                    // for a bogus channel.
1633                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1634                         unimplemented!();
1635                 }
1636                 let mut channel_state = self.channel_state.lock().unwrap();
1637                 match channel_state.by_id.entry(funding_msg.channel_id) {
1638                         hash_map::Entry::Occupied(_) => {
1639                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1640                         },
1641                         hash_map::Entry::Vacant(e) => {
1642                                 e.insert(chan);
1643                         }
1644                 }
1645                 Ok(funding_msg)
1646         }
1647
1648         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1649                 let (funding_txo, user_id, monitor) = {
1650                         let mut channel_state = self.channel_state.lock().unwrap();
1651                         match channel_state.by_id.get_mut(&msg.channel_id) {
1652                                 Some(chan) => {
1653                                         if chan.get_their_node_id() != *their_node_id {
1654                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1655                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1656                                         }
1657                                         let chan_monitor = chan.funding_signed(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1658                                         (chan.get_funding_txo().unwrap(), chan.get_user_id(), chan_monitor)
1659                                 },
1660                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1661                         }
1662                 };
1663                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1664                         unimplemented!();
1665                 }
1666                 let mut pending_events = self.pending_events.lock().unwrap();
1667                 pending_events.push(events::Event::FundingBroadcastSafe {
1668                         funding_txo: funding_txo,
1669                         user_channel_id: user_id,
1670                 });
1671                 Ok(())
1672         }
1673
1674         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<Option<msgs::AnnouncementSignatures>, MsgHandleErrInternal> {
1675                 let mut channel_state = self.channel_state.lock().unwrap();
1676                 match channel_state.by_id.get_mut(&msg.channel_id) {
1677                         Some(chan) => {
1678                                 if chan.get_their_node_id() != *their_node_id {
1679                                         //TODO: here and below MsgHandleErrInternal, #153 case
1680                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1681                                 }
1682                                 chan.funding_locked(&msg)
1683                                         .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
1684                                 return Ok(self.get_announcement_sigs(chan));
1685                         },
1686                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1687                 };
1688         }
1689
1690         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>), MsgHandleErrInternal> {
1691                 let (mut res, chan_option) = {
1692                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1693                         let channel_state = channel_state_lock.borrow_parts();
1694
1695                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1696                                 hash_map::Entry::Occupied(mut chan_entry) => {
1697                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1698                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1699                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1700                                         }
1701                                         let res = chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1702                                         if chan_entry.get().is_shutdown() {
1703                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1704                                                         channel_state.short_to_id.remove(&short_id);
1705                                                 }
1706                                                 (res, Some(chan_entry.remove_entry().1))
1707                                         } else { (res, None) }
1708                                 },
1709                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1710                         }
1711                 };
1712                 for htlc_source in res.2.drain(..) {
1713                         // unknown_next_peer...I dunno who that is anymore....
1714                         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() });
1715                 }
1716                 if let Some(chan) = chan_option {
1717                         if let Ok(update) = self.get_channel_update(&chan) {
1718                                 let mut events = self.pending_events.lock().unwrap();
1719                                 events.push(events::Event::BroadcastChannelUpdate {
1720                                         msg: update
1721                                 });
1722                         }
1723                 }
1724                 Ok((res.0, res.1))
1725         }
1726
1727         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<Option<msgs::ClosingSigned>, MsgHandleErrInternal> {
1728                 let (res, chan_option) = {
1729                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1730                         let channel_state = channel_state_lock.borrow_parts();
1731                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1732                                 hash_map::Entry::Occupied(mut chan_entry) => {
1733                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1734                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1735                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1736                                         }
1737                                         let res = chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1738                                         if res.1.is_some() {
1739                                                 // We're done with this channel, we've got a signed closing transaction and
1740                                                 // will send the closing_signed back to the remote peer upon return. This
1741                                                 // also implies there are no pending HTLCs left on the channel, so we can
1742                                                 // fully delete it from tracking (the channel monitor is still around to
1743                                                 // watch for old state broadcasts)!
1744                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1745                                                         channel_state.short_to_id.remove(&short_id);
1746                                                 }
1747                                                 (res, Some(chan_entry.remove_entry().1))
1748                                         } else { (res, None) }
1749                                 },
1750                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1751                         }
1752                 };
1753                 if let Some(broadcast_tx) = res.1 {
1754                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
1755                 }
1756                 if let Some(chan) = chan_option {
1757                         if let Ok(update) = self.get_channel_update(&chan) {
1758                                 let mut events = self.pending_events.lock().unwrap();
1759                                 events.push(events::Event::BroadcastChannelUpdate {
1760                                         msg: update
1761                                 });
1762                         }
1763                 }
1764                 Ok(res.0)
1765         }
1766
1767         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
1768                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
1769                 //determine the state of the payment based on our response/if we forward anything/the time
1770                 //we take to respond. We should take care to avoid allowing such an attack.
1771                 //
1772                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
1773                 //us repeatedly garbled in different ways, and compare our error messages, which are
1774                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
1775                 //but we should prevent it anyway.
1776
1777                 let (pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
1778                 let channel_state = channel_state_lock.borrow_parts();
1779
1780                 match channel_state.by_id.get_mut(&msg.channel_id) {
1781                         Some(chan) => {
1782                                 if chan.get_their_node_id() != *their_node_id {
1783                                         //TODO: here MsgHandleErrInternal, #153 case
1784                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1785                                 }
1786                                 if !chan.is_usable() {
1787                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Channel not yet available for receiving HTLCs", action: Some(msgs::ErrorAction::IgnoreError)}));
1788                                 }
1789                                 chan.update_add_htlc(&msg, pending_forward_info).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1790                         },
1791                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1792                 }
1793         }
1794
1795         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
1796                 let mut channel_state = self.channel_state.lock().unwrap();
1797                 let htlc_source = match channel_state.by_id.get_mut(&msg.channel_id) {
1798                         Some(chan) => {
1799                                 if chan.get_their_node_id() != *their_node_id {
1800                                         //TODO: here and below MsgHandleErrInternal, #153 case
1801                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1802                                 }
1803                                 chan.update_fulfill_htlc(&msg)
1804                                         .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?.clone()
1805                         },
1806                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1807                 };
1808                 self.claim_funds_internal(channel_state, htlc_source, msg.payment_preimage.clone());
1809                 Ok(())
1810         }
1811
1812         // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
1813         // indicating that the payment itself failed
1814         fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool) {
1815                 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
1816                         macro_rules! onion_failure_log {
1817                                 ( $error_code_textual: expr, $error_code: expr, $reported_name: expr, $reported_value: expr ) => {
1818                                         log_trace!(self, "{}({:#x}) {}({})", $error_code_textual, $error_code, $reported_name, $reported_value);
1819                                 };
1820                                 ( $error_code_textual: expr, $error_code: expr ) => {
1821                                         log_trace!(self, "{}({})", $error_code_textual, $error_code);
1822                                 };
1823                         }
1824
1825                         const BADONION: u16 = 0x8000;
1826                         const PERM: u16 = 0x4000;
1827                         const UPDATE: u16 = 0x1000;
1828
1829                         let mut res = None;
1830                         let mut htlc_msat = *first_hop_htlc_msat;
1831
1832                         // Handle packed channel/node updates for passing back for the route handler
1833                         Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
1834                                 if res.is_some() { return; }
1835
1836                                 let incoming_htlc_msat = htlc_msat;
1837                                 let amt_to_forward = htlc_msat - route_hop.fee_msat;
1838                                 htlc_msat = amt_to_forward;
1839
1840                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
1841
1842                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
1843                                 decryption_tmp.resize(packet_decrypted.len(), 0);
1844                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
1845                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
1846                                 packet_decrypted = decryption_tmp;
1847
1848                                 let is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
1849
1850                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
1851                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
1852                                         let mut hmac = Hmac::new(Sha256::new(), &um);
1853                                         hmac.input(&err_packet.encode()[32..]);
1854                                         let mut calc_tag = [0u8; 32];
1855                                         hmac.raw_result(&mut calc_tag);
1856
1857                                         if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
1858                                                 if err_packet.failuremsg.len() < 2 {
1859                                                         // Useless packet that we can't use but it passed HMAC, so it
1860                                                         // definitely came from the peer in question
1861                                                         res = Some((None, !is_from_final_node));
1862                                                 } else {
1863                                                         let error_code = byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]);
1864
1865                                                         match error_code & 0xff {
1866                                                                 1|2|3 => {
1867                                                                         // either from an intermediate or final node
1868                                                                         //   invalid_realm(PERM|1),
1869                                                                         //   temporary_node_failure(NODE|2)
1870                                                                         //   permanent_node_failure(PERM|NODE|2)
1871                                                                         //   required_node_feature_mssing(PERM|NODE|3)
1872                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1873                                                                                 node_id: route_hop.pubkey,
1874                                                                                 is_permanent: error_code & PERM == PERM,
1875                                                                         }), !(error_code & PERM == PERM && is_from_final_node)));
1876                                                                         // node returning invalid_realm is removed from network_map,
1877                                                                         // although NODE flag is not set, TODO: or remove channel only?
1878                                                                         // retry payment when removed node is not a final node
1879                                                                         return;
1880                                                                 },
1881                                                                 _ => {}
1882                                                         }
1883
1884                                                         if is_from_final_node {
1885                                                                 let payment_retryable = match error_code {
1886                                                                         c if c == PERM|15 => false, // unknown_payment_hash
1887                                                                         c if c == PERM|16 => false, // incorrect_payment_amount
1888                                                                         17 => true, // final_expiry_too_soon
1889                                                                         18 if err_packet.failuremsg.len() == 6 => { // final_incorrect_cltv_expiry
1890                                                                                 let _reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
1891                                                                                 true
1892                                                                         },
1893                                                                         19 if err_packet.failuremsg.len() == 10 => { // final_incorrect_htlc_amount
1894                                                                                 let _reported_incoming_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
1895                                                                                 true
1896                                                                         },
1897                                                                         _ => {
1898                                                                                 // A final node has sent us either an invalid code or an error_code that
1899                                                                                 // MUST be sent from the processing node, or the formmat of failuremsg
1900                                                                                 // does not coform to the spec.
1901                                                                                 // Remove it from the network map and don't may retry payment
1902                                                                                 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1903                                                                                         node_id: route_hop.pubkey,
1904                                                                                         is_permanent: true,
1905                                                                                 }), false));
1906                                                                                 return;
1907                                                                         }
1908                                                                 };
1909                                                                 res = Some((None, payment_retryable));
1910                                                                 return;
1911                                                         }
1912
1913                                                         // now, error_code should be only from the intermediate nodes
1914                                                         match error_code {
1915                                                                 _c if error_code & PERM == PERM => {
1916                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
1917                                                                                 short_channel_id: route_hop.short_channel_id,
1918                                                                                 is_permanent: true,
1919                                                                         }), false));
1920                                                                 },
1921                                                                 _c if error_code & UPDATE == UPDATE => {
1922                                                                         let offset = match error_code {
1923                                                                                 c if c == UPDATE|7  => 0, // temporary_channel_failure
1924                                                                                 c if c == UPDATE|11 => 8, // amount_below_minimum
1925                                                                                 c if c == UPDATE|12 => 8, // fee_insufficient
1926                                                                                 c if c == UPDATE|13 => 4, // incorrect_cltv_expiry
1927                                                                                 c if c == UPDATE|14 => 0, // expiry_too_soon
1928                                                                                 c if c == UPDATE|20 => 2, // channel_disabled
1929                                                                                 _ =>  {
1930                                                                                         // node sending unknown code
1931                                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1932                                                                                                 node_id: route_hop.pubkey,
1933                                                                                                 is_permanent: true,
1934                                                                                         }), false));
1935                                                                                         return;
1936                                                                                 }
1937                                                                         };
1938
1939                                                                         if err_packet.failuremsg.len() >= offset + 2 {
1940                                                                                 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[offset+2..offset+4]) as usize;
1941                                                                                 if err_packet.failuremsg.len() >= offset + 4 + update_len {
1942                                                                                         if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&err_packet.failuremsg[offset + 4..offset + 4 + update_len])) {
1943                                                                                                 // if channel_update should NOT have caused the failure:
1944                                                                                                 // MAY treat the channel_update as invalid.
1945                                                                                                 let is_chan_update_invalid = match error_code {
1946                                                                                                         c if c == UPDATE|7 => { // temporary_channel_failure
1947                                                                                                                 false
1948                                                                                                         },
1949                                                                                                         c if c == UPDATE|11 => { // amount_below_minimum
1950                                                                                                                 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
1951                                                                                                                 onion_failure_log!("amount_below_minimum", UPDATE|11, "htlc_msat", reported_htlc_msat);
1952                                                                                                                 incoming_htlc_msat > chan_update.contents.htlc_minimum_msat
1953                                                                                                         },
1954                                                                                                         c if c == UPDATE|12 => { // fee_insufficient
1955                                                                                                                 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
1956                                                                                                                 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) });
1957                                                                                                                 onion_failure_log!("fee_insufficient", UPDATE|12, "htlc_msat", reported_htlc_msat);
1958                                                                                                                 new_fee.is_none() || incoming_htlc_msat >= new_fee.unwrap() && incoming_htlc_msat >= amt_to_forward + new_fee.unwrap()
1959                                                                                                         }
1960                                                                                                         c if c == UPDATE|13 => { // incorrect_cltv_expiry
1961                                                                                                                 let reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
1962                                                                                                                 onion_failure_log!("incorrect_cltv_expiry", UPDATE|13, "cltv_expiry", reported_cltv_expiry);
1963                                                                                                                 route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta
1964                                                                                                         },
1965                                                                                                         c if c == UPDATE|20 => { // channel_disabled
1966                                                                                                                 let reported_flags = byte_utils::slice_to_be16(&err_packet.failuremsg[2..2+2]);
1967                                                                                                                 onion_failure_log!("channel_disabled", UPDATE|20, "flags", reported_flags);
1968                                                                                                                 chan_update.contents.flags & 0x01 == 0x01
1969                                                                                                         },
1970                                                                                                         c if c == UPDATE|21 => true, // expiry_too_far
1971                                                                                                         _ => { unreachable!(); },
1972                                                                                                 };
1973
1974                                                                                                 let msg = if is_chan_update_invalid { None } else {
1975                                                                                                         Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
1976                                                                                                                 msg: chan_update,
1977                                                                                                         })
1978                                                                                                 };
1979                                                                                                 res = Some((msg, true));
1980                                                                                                 return;
1981                                                                                         }
1982                                                                                 }
1983                                                                         }
1984                                                                 },
1985                                                                 _c if error_code & BADONION == BADONION => {
1986                                                                         //TODO
1987                                                                 },
1988                                                                 14 => { // expiry_too_soon
1989                                                                         res = Some((None, true));
1990                                                                         return;
1991                                                                 }
1992                                                                 _ => {
1993                                                                         // node sending unknown code
1994                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1995                                                                                 node_id: route_hop.pubkey,
1996                                                                                 is_permanent: true,
1997                                                                         }), false));
1998                                                                         return;
1999                                                                 }
2000                                                         }
2001                                                 }
2002                                         }
2003                                 }
2004                         }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2005                         res.unwrap_or((None, true))
2006                 } else { ((None, true)) }
2007         }
2008
2009         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2010                 let mut channel_state = self.channel_state.lock().unwrap();
2011                 match channel_state.by_id.get_mut(&msg.channel_id) {
2012                         Some(chan) => {
2013                                 if chan.get_their_node_id() != *their_node_id {
2014                                         //TODO: here and below MsgHandleErrInternal, #153 case
2015                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2016                                 }
2017                                 chan.update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() })
2018                                         .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))
2019                         },
2020                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2021                 }?;
2022                 Ok(())
2023         }
2024
2025         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2026                 let mut channel_state = self.channel_state.lock().unwrap();
2027                 match channel_state.by_id.get_mut(&msg.channel_id) {
2028                         Some(chan) => {
2029                                 if chan.get_their_node_id() != *their_node_id {
2030                                         //TODO: here and below MsgHandleErrInternal, #153 case
2031                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2032                                 }
2033                                 if (msg.failure_code & 0x8000) != 0 {
2034                                         return Err(MsgHandleErrInternal::send_err_msg_close_chan("Got update_fail_malformed_htlc with BADONION set", msg.channel_id));
2035                                 }
2036                                 chan.update_fail_malformed_htlc(&msg, HTLCFailReason::Reason { failure_code: msg.failure_code, data: Vec::new() })
2037                                         .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
2038                                 Ok(())
2039                         },
2040                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2041                 }
2042         }
2043
2044         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(msgs::RevokeAndACK, Option<msgs::CommitmentSigned>), MsgHandleErrInternal> {
2045                 let (revoke_and_ack, commitment_signed, chan_monitor) = {
2046                         let mut channel_state = self.channel_state.lock().unwrap();
2047                         match channel_state.by_id.get_mut(&msg.channel_id) {
2048                                 Some(chan) => {
2049                                         if chan.get_their_node_id() != *their_node_id {
2050                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2051                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2052                                         }
2053                                         chan.commitment_signed(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?
2054                                 },
2055                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2056                         }
2057                 };
2058                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2059                         unimplemented!();
2060                 }
2061
2062                 Ok((revoke_and_ack, commitment_signed))
2063         }
2064
2065         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<Option<msgs::CommitmentUpdate>, MsgHandleErrInternal> {
2066                 let ((res, mut pending_forwards, mut pending_failures, chan_monitor), short_channel_id) = {
2067                         let mut channel_state = self.channel_state.lock().unwrap();
2068                         match channel_state.by_id.get_mut(&msg.channel_id) {
2069                                 Some(chan) => {
2070                                         if chan.get_their_node_id() != *their_node_id {
2071                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2072                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2073                                         }
2074                                         (chan.revoke_and_ack(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?, chan.get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2075                                 },
2076                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2077                         }
2078                 };
2079                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2080                         unimplemented!();
2081                 }
2082                 for failure in pending_failures.drain(..) {
2083                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2084                 }
2085
2086                 let mut forward_event = None;
2087                 if !pending_forwards.is_empty() {
2088                         let mut channel_state = self.channel_state.lock().unwrap();
2089                         if channel_state.forward_htlcs.is_empty() {
2090                                 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));
2091                                 channel_state.next_forward = forward_event.unwrap();
2092                         }
2093                         for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2094                                 match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2095                                         hash_map::Entry::Occupied(mut entry) => {
2096                                                 entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id: short_channel_id, prev_htlc_id, forward_info });
2097                                         },
2098                                         hash_map::Entry::Vacant(entry) => {
2099                                                 entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id: short_channel_id, prev_htlc_id, forward_info }));
2100                                         }
2101                                 }
2102                         }
2103                 }
2104                 match forward_event {
2105                         Some(time) => {
2106                                 let mut pending_events = self.pending_events.lock().unwrap();
2107                                 pending_events.push(events::Event::PendingHTLCsForwardable {
2108                                         time_forwardable: time
2109                                 });
2110                         }
2111                         None => {},
2112                 }
2113
2114                 Ok(res)
2115         }
2116
2117         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2118                 let mut channel_state = self.channel_state.lock().unwrap();
2119                 match channel_state.by_id.get_mut(&msg.channel_id) {
2120                         Some(chan) => {
2121                                 if chan.get_their_node_id() != *their_node_id {
2122                                         //TODO: here and below MsgHandleErrInternal, #153 case
2123                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2124                                 }
2125                                 chan.update_fee(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))
2126                         },
2127                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2128                 }
2129         }
2130
2131         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2132                 let (chan_announcement, chan_update) = {
2133                         let mut channel_state = self.channel_state.lock().unwrap();
2134                         match channel_state.by_id.get_mut(&msg.channel_id) {
2135                                 Some(chan) => {
2136                                         if chan.get_their_node_id() != *their_node_id {
2137                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2138                                         }
2139                                         if !chan.is_usable() {
2140                                                 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2141                                         }
2142
2143                                         let our_node_id = self.get_our_node_id();
2144                                         let (announcement, our_bitcoin_sig) = chan.get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone())
2145                                                 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
2146
2147                                         let were_node_one = announcement.node_id_1 == our_node_id;
2148                                         let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2149                                         let bad_sig_action = MsgHandleErrInternal::send_err_msg_close_chan("Bad announcement_signatures node_signature", msg.channel_id);
2150                                         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);
2151                                         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);
2152
2153                                         let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2154
2155                                         (msgs::ChannelAnnouncement {
2156                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2157                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2158                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2159                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2160                                                 contents: announcement,
2161                                         }, self.get_channel_update(chan).unwrap()) // can only fail if we're not in a ready state
2162                                 },
2163                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2164                         }
2165                 };
2166                 let mut pending_events = self.pending_events.lock().unwrap();
2167                 pending_events.push(events::Event::BroadcastChannelAnnouncement { msg: chan_announcement, update_msg: chan_update });
2168                 Ok(())
2169         }
2170
2171         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), MsgHandleErrInternal> {
2172                 let (res, chan_monitor) = {
2173                         let mut channel_state = self.channel_state.lock().unwrap();
2174                         match channel_state.by_id.get_mut(&msg.channel_id) {
2175                                 Some(chan) => {
2176                                         if chan.get_their_node_id() != *their_node_id {
2177                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2178                                         }
2179                                         let (funding_locked, revoke_and_ack, commitment_update, channel_monitor) = chan.channel_reestablish(msg)
2180                                                 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
2181                                         (Ok((funding_locked, revoke_and_ack, commitment_update)), channel_monitor)
2182                                 },
2183                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2184                         }
2185                 };
2186                 if let Some(monitor) = chan_monitor {
2187                         if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2188                                 unimplemented!();
2189                         }
2190                 }
2191                 res
2192         }
2193
2194         /// Begin Update fee process. Allowed only on an outbound channel.
2195         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2196         /// PeerManager::process_events afterwards.
2197         /// Note: This API is likely to change!
2198         #[doc(hidden)]
2199         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2200                 let mut channel_state = self.channel_state.lock().unwrap();
2201                 match channel_state.by_id.get_mut(&channel_id) {
2202                         None => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2203                         Some(chan) => {
2204                                 if !chan.is_outbound() {
2205                                         return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2206                                 }
2207                                 if !chan.is_live() {
2208                                         return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2209                                 }
2210                                 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})? {
2211                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2212                                                 unimplemented!();
2213                                         }
2214                                         let mut pending_events = self.pending_events.lock().unwrap();
2215                                         pending_events.push(events::Event::UpdateHTLCs {
2216                                                 node_id: chan.get_their_node_id(),
2217                                                 updates: msgs::CommitmentUpdate {
2218                                                         update_add_htlcs: Vec::new(),
2219                                                         update_fulfill_htlcs: Vec::new(),
2220                                                         update_fail_htlcs: Vec::new(),
2221                                                         update_fail_malformed_htlcs: Vec::new(),
2222                                                         update_fee: Some(update_fee),
2223                                                         commitment_signed,
2224                                                 },
2225                                         });
2226                                 }
2227                         },
2228                 }
2229                 Ok(())
2230         }
2231 }
2232
2233 impl events::EventsProvider for ChannelManager {
2234         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2235                 let mut pending_events = self.pending_events.lock().unwrap();
2236                 let mut ret = Vec::new();
2237                 mem::swap(&mut ret, &mut *pending_events);
2238                 ret
2239         }
2240 }
2241
2242 impl ChainListener for ChannelManager {
2243         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2244                 let mut new_events = Vec::new();
2245                 let mut failed_channels = Vec::new();
2246                 {
2247                         let mut channel_lock = self.channel_state.lock().unwrap();
2248                         let channel_state = channel_lock.borrow_parts();
2249                         let short_to_id = channel_state.short_to_id;
2250                         channel_state.by_id.retain(|_, channel| {
2251                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2252                                 if let Ok(Some(funding_locked)) = chan_res {
2253                                         let announcement_sigs = self.get_announcement_sigs(channel);
2254                                         new_events.push(events::Event::SendFundingLocked {
2255                                                 node_id: channel.get_their_node_id(),
2256                                                 msg: funding_locked,
2257                                                 announcement_sigs: announcement_sigs
2258                                         });
2259                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2260                                 } else if let Err(e) = chan_res {
2261                                         new_events.push(events::Event::HandleError {
2262                                                 node_id: channel.get_their_node_id(),
2263                                                 action: e.action,
2264                                         });
2265                                         if channel.is_shutdown() {
2266                                                 return false;
2267                                         }
2268                                 }
2269                                 if let Some(funding_txo) = channel.get_funding_txo() {
2270                                         for tx in txn_matched {
2271                                                 for inp in tx.input.iter() {
2272                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2273                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2274                                                                         short_to_id.remove(&short_id);
2275                                                                 }
2276                                                                 // It looks like our counterparty went on-chain. We go ahead and
2277                                                                 // broadcast our latest local state as well here, just in case its
2278                                                                 // some kind of SPV attack, though we expect these to be dropped.
2279                                                                 failed_channels.push(channel.force_shutdown());
2280                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2281                                                                         new_events.push(events::Event::BroadcastChannelUpdate {
2282                                                                                 msg: update
2283                                                                         });
2284                                                                 }
2285                                                                 return false;
2286                                                         }
2287                                                 }
2288                                         }
2289                                 }
2290                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2291                                         if let Some(short_id) = channel.get_short_channel_id() {
2292                                                 short_to_id.remove(&short_id);
2293                                         }
2294                                         failed_channels.push(channel.force_shutdown());
2295                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2296                                         // the latest local tx for us, so we should skip that here (it doesn't really
2297                                         // hurt anything, but does make tests a bit simpler).
2298                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2299                                         if let Ok(update) = self.get_channel_update(&channel) {
2300                                                 new_events.push(events::Event::BroadcastChannelUpdate {
2301                                                         msg: update
2302                                                 });
2303                                         }
2304                                         return false;
2305                                 }
2306                                 true
2307                         });
2308                 }
2309                 for failure in failed_channels.drain(..) {
2310                         self.finish_force_close_channel(failure);
2311                 }
2312                 let mut pending_events = self.pending_events.lock().unwrap();
2313                 for funding_locked in new_events.drain(..) {
2314                         pending_events.push(funding_locked);
2315                 }
2316                 self.latest_block_height.store(height as usize, Ordering::Release);
2317         }
2318
2319         /// We force-close the channel without letting our counterparty participate in the shutdown
2320         fn block_disconnected(&self, header: &BlockHeader) {
2321                 let mut new_events = Vec::new();
2322                 let mut failed_channels = Vec::new();
2323                 {
2324                         let mut channel_lock = self.channel_state.lock().unwrap();
2325                         let channel_state = channel_lock.borrow_parts();
2326                         let short_to_id = channel_state.short_to_id;
2327                         channel_state.by_id.retain(|_,  v| {
2328                                 if v.block_disconnected(header) {
2329                                         if let Some(short_id) = v.get_short_channel_id() {
2330                                                 short_to_id.remove(&short_id);
2331                                         }
2332                                         failed_channels.push(v.force_shutdown());
2333                                         if let Ok(update) = self.get_channel_update(&v) {
2334                                                 new_events.push(events::Event::BroadcastChannelUpdate {
2335                                                         msg: update
2336                                                 });
2337                                         }
2338                                         false
2339                                 } else {
2340                                         true
2341                                 }
2342                         });
2343                 }
2344                 for failure in failed_channels.drain(..) {
2345                         self.finish_force_close_channel(failure);
2346                 }
2347                 if !new_events.is_empty() {
2348                         let mut pending_events = self.pending_events.lock().unwrap();
2349                         for funding_locked in new_events.drain(..) {
2350                                 pending_events.push(funding_locked);
2351                         }
2352                 }
2353                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2354         }
2355 }
2356
2357 macro_rules! handle_error {
2358         ($self: ident, $internal: expr, $their_node_id: expr) => {
2359                 match $internal {
2360                         Ok(msg) => Ok(msg),
2361                         Err(MsgHandleErrInternal { err, needs_channel_force_close }) => {
2362                                 if needs_channel_force_close {
2363                                         match &err.action {
2364                                                 &Some(msgs::ErrorAction::DisconnectPeer { msg: Some(ref msg) }) => {
2365                                                         if msg.channel_id == [0; 32] {
2366                                                                 $self.peer_disconnected(&$their_node_id, true);
2367                                                         } else {
2368                                                                 $self.force_close_channel(&msg.channel_id);
2369                                                         }
2370                                                 },
2371                                                 &Some(msgs::ErrorAction::DisconnectPeer { msg: None }) => {},
2372                                                 &Some(msgs::ErrorAction::IgnoreError) => {},
2373                                                 &Some(msgs::ErrorAction::SendErrorMessage { ref msg }) => {
2374                                                         if msg.channel_id == [0; 32] {
2375                                                                 $self.peer_disconnected(&$their_node_id, true);
2376                                                         } else {
2377                                                                 $self.force_close_channel(&msg.channel_id);
2378                                                         }
2379                                                 },
2380                                                 &None => {},
2381                                         }
2382                                 }
2383                                 Err(err)
2384                         },
2385                 }
2386         }
2387 }
2388
2389 impl ChannelMessageHandler for ChannelManager {
2390         //TODO: Handle errors and close channel (or so)
2391         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<msgs::AcceptChannel, HandleError> {
2392                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2393         }
2394
2395         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2396                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2397         }
2398
2399         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<msgs::FundingSigned, HandleError> {
2400                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2401         }
2402
2403         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2404                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2405         }
2406
2407         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<Option<msgs::AnnouncementSignatures>, HandleError> {
2408                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2409         }
2410
2411         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>), HandleError> {
2412                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2413         }
2414
2415         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<Option<msgs::ClosingSigned>, HandleError> {
2416                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2417         }
2418
2419         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2420                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2421         }
2422
2423         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2424                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2425         }
2426
2427         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2428                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2429         }
2430
2431         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2432                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2433         }
2434
2435         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(msgs::RevokeAndACK, Option<msgs::CommitmentSigned>), HandleError> {
2436                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2437         }
2438
2439         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<Option<msgs::CommitmentUpdate>, HandleError> {
2440                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2441         }
2442
2443         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2444                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2445         }
2446
2447         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2448                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2449         }
2450
2451         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), HandleError> {
2452                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2453         }
2454
2455         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2456                 let mut new_events = Vec::new();
2457                 let mut failed_channels = Vec::new();
2458                 let mut failed_payments = Vec::new();
2459                 {
2460                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2461                         let channel_state = channel_state_lock.borrow_parts();
2462                         let short_to_id = channel_state.short_to_id;
2463                         if no_connection_possible {
2464                                 channel_state.by_id.retain(|_, chan| {
2465                                         if chan.get_their_node_id() == *their_node_id {
2466                                                 if let Some(short_id) = chan.get_short_channel_id() {
2467                                                         short_to_id.remove(&short_id);
2468                                                 }
2469                                                 failed_channels.push(chan.force_shutdown());
2470                                                 if let Ok(update) = self.get_channel_update(&chan) {
2471                                                         new_events.push(events::Event::BroadcastChannelUpdate {
2472                                                                 msg: update
2473                                                         });
2474                                                 }
2475                                                 false
2476                                         } else {
2477                                                 true
2478                                         }
2479                                 });
2480                         } else {
2481                                 channel_state.by_id.retain(|_, chan| {
2482                                         if chan.get_their_node_id() == *their_node_id {
2483                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2484                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2485                                                 if !failed_adds.is_empty() {
2486                                                         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
2487                                                         failed_payments.push((chan_update, failed_adds));
2488                                                 }
2489                                                 if chan.is_shutdown() {
2490                                                         if let Some(short_id) = chan.get_short_channel_id() {
2491                                                                 short_to_id.remove(&short_id);
2492                                                         }
2493                                                         return false;
2494                                                 }
2495                                         }
2496                                         true
2497                                 })
2498                         }
2499                 }
2500                 for failure in failed_channels.drain(..) {
2501                         self.finish_force_close_channel(failure);
2502                 }
2503                 if !new_events.is_empty() {
2504                         let mut pending_events = self.pending_events.lock().unwrap();
2505                         for event in new_events.drain(..) {
2506                                 pending_events.push(event);
2507                         }
2508                 }
2509                 for (chan_update, mut htlc_sources) in failed_payments {
2510                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2511                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2512                         }
2513                 }
2514         }
2515
2516         fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<msgs::ChannelReestablish> {
2517                 let mut res = Vec::new();
2518                 let mut channel_state = self.channel_state.lock().unwrap();
2519                 channel_state.by_id.retain(|_, chan| {
2520                         if chan.get_their_node_id() == *their_node_id {
2521                                 if !chan.have_received_message() {
2522                                         // If we created this (outbound) channel while we were disconnected from the
2523                                         // peer we probably failed to send the open_channel message, which is now
2524                                         // lost. We can't have had anything pending related to this channel, so we just
2525                                         // drop it.
2526                                         false
2527                                 } else {
2528                                         res.push(chan.get_channel_reestablish());
2529                                         true
2530                                 }
2531                         } else { true }
2532                 });
2533                 //TODO: Also re-broadcast announcement_signatures
2534                 res
2535         }
2536
2537         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2538                 if msg.channel_id == [0; 32] {
2539                         for chan in self.list_channels() {
2540                                 if chan.remote_network_id == *their_node_id {
2541                                         self.force_close_channel(&chan.channel_id);
2542                                 }
2543                         }
2544                 } else {
2545                         self.force_close_channel(&msg.channel_id);
2546                 }
2547         }
2548 }
2549
2550 #[cfg(test)]
2551 mod tests {
2552         use chain::chaininterface;
2553         use chain::transaction::OutPoint;
2554         use chain::chaininterface::ChainListener;
2555         use ln::channelmanager::{ChannelManager,OnionKeys};
2556         use ln::channelmonitor::{CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
2557         use ln::router::{Route, RouteHop, Router};
2558         use ln::msgs;
2559         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
2560         use util::test_utils;
2561         use util::events::{Event, EventsProvider};
2562         use util::errors::APIError;
2563         use util::logger::Logger;
2564         use util::ser::Writeable;
2565
2566         use bitcoin::util::hash::Sha256dHash;
2567         use bitcoin::blockdata::block::{Block, BlockHeader};
2568         use bitcoin::blockdata::transaction::{Transaction, TxOut};
2569         use bitcoin::blockdata::constants::genesis_block;
2570         use bitcoin::network::constants::Network;
2571         use bitcoin::network::serialize::serialize;
2572         use bitcoin::network::serialize::BitcoinHash;
2573
2574         use hex;
2575
2576         use secp256k1::{Secp256k1, Message};
2577         use secp256k1::key::{PublicKey,SecretKey};
2578
2579         use crypto::sha2::Sha256;
2580         use crypto::digest::Digest;
2581
2582         use rand::{thread_rng,Rng};
2583
2584         use std::cell::RefCell;
2585         use std::collections::{BTreeSet, HashMap};
2586         use std::default::Default;
2587         use std::rc::Rc;
2588         use std::sync::{Arc, Mutex};
2589         use std::sync::atomic::Ordering;
2590         use std::time::Instant;
2591         use std::mem;
2592
2593         fn build_test_onion_keys() -> Vec<OnionKeys> {
2594                 // Keys from BOLT 4, used in both test vector tests
2595                 let secp_ctx = Secp256k1::new();
2596
2597                 let route = Route {
2598                         hops: vec!(
2599                                         RouteHop {
2600                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
2601                                                 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
2602                                         },
2603                                         RouteHop {
2604                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
2605                                                 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
2606                                         },
2607                                         RouteHop {
2608                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
2609                                                 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
2610                                         },
2611                                         RouteHop {
2612                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
2613                                                 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
2614                                         },
2615                                         RouteHop {
2616                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
2617                                                 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
2618                                         },
2619                         ),
2620                 };
2621
2622                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
2623
2624                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
2625                 assert_eq!(onion_keys.len(), route.hops.len());
2626                 onion_keys
2627         }
2628
2629         #[test]
2630         fn onion_vectors() {
2631                 // Packet creation test vectors from BOLT 4
2632                 let onion_keys = build_test_onion_keys();
2633
2634                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
2635                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
2636                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
2637                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
2638                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
2639
2640                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
2641                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
2642                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
2643                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
2644                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
2645
2646                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
2647                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
2648                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
2649                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
2650                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
2651
2652                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
2653                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
2654                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
2655                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
2656                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
2657
2658                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
2659                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
2660                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
2661                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
2662                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
2663
2664                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
2665                 let payloads = vec!(
2666                         msgs::OnionHopData {
2667                                 realm: 0,
2668                                 data: msgs::OnionRealm0HopData {
2669                                         short_channel_id: 0,
2670                                         amt_to_forward: 0,
2671                                         outgoing_cltv_value: 0,
2672                                 },
2673                                 hmac: [0; 32],
2674                         },
2675                         msgs::OnionHopData {
2676                                 realm: 0,
2677                                 data: msgs::OnionRealm0HopData {
2678                                         short_channel_id: 0x0101010101010101,
2679                                         amt_to_forward: 0x0100000001,
2680                                         outgoing_cltv_value: 0,
2681                                 },
2682                                 hmac: [0; 32],
2683                         },
2684                         msgs::OnionHopData {
2685                                 realm: 0,
2686                                 data: msgs::OnionRealm0HopData {
2687                                         short_channel_id: 0x0202020202020202,
2688                                         amt_to_forward: 0x0200000002,
2689                                         outgoing_cltv_value: 0,
2690                                 },
2691                                 hmac: [0; 32],
2692                         },
2693                         msgs::OnionHopData {
2694                                 realm: 0,
2695                                 data: msgs::OnionRealm0HopData {
2696                                         short_channel_id: 0x0303030303030303,
2697                                         amt_to_forward: 0x0300000003,
2698                                         outgoing_cltv_value: 0,
2699                                 },
2700                                 hmac: [0; 32],
2701                         },
2702                         msgs::OnionHopData {
2703                                 realm: 0,
2704                                 data: msgs::OnionRealm0HopData {
2705                                         short_channel_id: 0x0404040404040404,
2706                                         amt_to_forward: 0x0400000004,
2707                                         outgoing_cltv_value: 0,
2708                                 },
2709                                 hmac: [0; 32],
2710                         },
2711                 );
2712
2713                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &[0x42; 32]);
2714                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
2715                 // anyway...
2716                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
2717         }
2718
2719         #[test]
2720         fn test_failure_packet_onion() {
2721                 // Returning Errors test vectors from BOLT 4
2722
2723                 let onion_keys = build_test_onion_keys();
2724                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret, 0x2002, &[0; 0]);
2725                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
2726
2727                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret, &onion_error.encode()[..]);
2728                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
2729
2730                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret, &onion_packet_1.data[..]);
2731                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
2732
2733                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret, &onion_packet_2.data[..]);
2734                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
2735
2736                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret, &onion_packet_3.data[..]);
2737                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
2738
2739                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret, &onion_packet_4.data[..]);
2740                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
2741         }
2742
2743         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
2744                 assert!(chain.does_match_tx(tx));
2745                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2746                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
2747                 for i in 2..100 {
2748                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2749                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
2750                 }
2751         }
2752
2753         struct Node {
2754                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
2755                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
2756                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
2757                 node: Arc<ChannelManager>,
2758                 router: Router,
2759                 network_payment_count: Rc<RefCell<u8>>,
2760                 network_chan_count: Rc<RefCell<u32>>,
2761         }
2762         impl Drop for Node {
2763                 fn drop(&mut self) {
2764                         if !::std::thread::panicking() {
2765                                 // Check that we processed all pending events
2766                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
2767                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
2768                         }
2769                 }
2770         }
2771
2772         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2773                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
2774         }
2775
2776         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) {
2777                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
2778                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
2779                 (announcement, as_update, bs_update, channel_id, tx)
2780         }
2781
2782         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
2783                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
2784
2785                 let events_1 = node_a.node.get_and_clear_pending_events();
2786                 assert_eq!(events_1.len(), 1);
2787                 let accept_chan = match events_1[0] {
2788                         Event::SendOpenChannel { ref node_id, ref msg } => {
2789                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
2790                                 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), msg).unwrap()
2791                         },
2792                         _ => panic!("Unexpected event"),
2793                 };
2794
2795                 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), &accept_chan).unwrap();
2796
2797                 let chan_id = *node_a.network_chan_count.borrow();
2798                 let tx;
2799                 let funding_output;
2800
2801                 let events_2 = node_a.node.get_and_clear_pending_events();
2802                 assert_eq!(events_2.len(), 1);
2803                 match events_2[0] {
2804                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
2805                                 assert_eq!(*channel_value_satoshis, channel_value);
2806                                 assert_eq!(user_channel_id, 42);
2807
2808                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
2809                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
2810                                 }]};
2811                                 funding_output = OutPoint::new(Sha256dHash::from_data(&serialize(&tx).unwrap()[..]), 0);
2812
2813                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
2814                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
2815                                 assert_eq!(added_monitors.len(), 1);
2816                                 assert_eq!(added_monitors[0].0, funding_output);
2817                                 added_monitors.clear();
2818                         },
2819                         _ => panic!("Unexpected event"),
2820                 }
2821
2822                 let events_3 = node_a.node.get_and_clear_pending_events();
2823                 assert_eq!(events_3.len(), 1);
2824                 let funding_signed = match events_3[0] {
2825                         Event::SendFundingCreated { ref node_id, ref msg } => {
2826                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
2827                                 let res = node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), msg).unwrap();
2828                                 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
2829                                 assert_eq!(added_monitors.len(), 1);
2830                                 assert_eq!(added_monitors[0].0, funding_output);
2831                                 added_monitors.clear();
2832                                 res
2833                         },
2834                         _ => panic!("Unexpected event"),
2835                 };
2836
2837                 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &funding_signed).unwrap();
2838                 {
2839                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
2840                         assert_eq!(added_monitors.len(), 1);
2841                         assert_eq!(added_monitors[0].0, funding_output);
2842                         added_monitors.clear();
2843                 }
2844
2845                 let events_4 = node_a.node.get_and_clear_pending_events();
2846                 assert_eq!(events_4.len(), 1);
2847                 match events_4[0] {
2848                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
2849                                 assert_eq!(user_channel_id, 42);
2850                                 assert_eq!(*funding_txo, funding_output);
2851                         },
2852                         _ => panic!("Unexpected event"),
2853                 };
2854
2855                 tx
2856         }
2857
2858         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
2859                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
2860                 let events_5 = node_b.node.get_and_clear_pending_events();
2861                 assert_eq!(events_5.len(), 1);
2862                 match events_5[0] {
2863                         Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
2864                                 assert_eq!(*node_id, node_a.node.get_our_node_id());
2865                                 assert!(announcement_sigs.is_none());
2866                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), msg).unwrap()
2867                         },
2868                         _ => panic!("Unexpected event"),
2869                 };
2870
2871                 let channel_id;
2872
2873                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
2874                 let events_6 = node_a.node.get_and_clear_pending_events();
2875                 assert_eq!(events_6.len(), 1);
2876                 (match events_6[0] {
2877                         Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
2878                                 channel_id = msg.channel_id.clone();
2879                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
2880                                 (msg.clone(), announcement_sigs.clone().unwrap())
2881                         },
2882                         _ => panic!("Unexpected event"),
2883                 }, channel_id)
2884         }
2885
2886         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) {
2887                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
2888                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
2889                 (msgs, chan_id, tx)
2890         }
2891
2892         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) {
2893                 let bs_announcement_sigs = {
2894                         let bs_announcement_sigs = node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap().unwrap();
2895                         node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
2896                         bs_announcement_sigs
2897                 };
2898
2899                 let events_7 = node_b.node.get_and_clear_pending_events();
2900                 assert_eq!(events_7.len(), 1);
2901                 let (announcement, bs_update) = match events_7[0] {
2902                         Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
2903                                 (msg, update_msg)
2904                         },
2905                         _ => panic!("Unexpected event"),
2906                 };
2907
2908                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
2909                 let events_8 = node_a.node.get_and_clear_pending_events();
2910                 assert_eq!(events_8.len(), 1);
2911                 let as_update = match events_8[0] {
2912                         Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
2913                                 assert!(*announcement == *msg);
2914                                 update_msg
2915                         },
2916                         _ => panic!("Unexpected event"),
2917                 };
2918
2919                 *node_a.network_chan_count.borrow_mut() += 1;
2920
2921                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
2922         }
2923
2924         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2925                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
2926         }
2927
2928         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) {
2929                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
2930                 for node in nodes {
2931                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
2932                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
2933                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
2934                 }
2935                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
2936         }
2937
2938         macro_rules! check_spends {
2939                 ($tx: expr, $spends_tx: expr) => {
2940                         {
2941                                 let mut funding_tx_map = HashMap::new();
2942                                 let spends_tx = $spends_tx;
2943                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
2944                                 $tx.verify(&funding_tx_map).unwrap();
2945                         }
2946                 }
2947         }
2948
2949         fn close_channel(outbound_node: &Node, inbound_node: &Node, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate) {
2950                 let (node_a, broadcaster_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster) } else { (&outbound_node.node, &outbound_node.tx_broadcaster) };
2951                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
2952                 let (tx_a, tx_b);
2953
2954                 node_a.close_channel(channel_id).unwrap();
2955                 let events_1 = node_a.get_and_clear_pending_events();
2956                 assert_eq!(events_1.len(), 1);
2957                 let shutdown_a = match events_1[0] {
2958                         Event::SendShutdown { ref node_id, ref msg } => {
2959                                 assert_eq!(node_id, &node_b.get_our_node_id());
2960                                 msg.clone()
2961                         },
2962                         _ => panic!("Unexpected event"),
2963                 };
2964
2965                 let (shutdown_b, mut closing_signed_b) = node_b.handle_shutdown(&node_a.get_our_node_id(), &shutdown_a).unwrap();
2966                 if !close_inbound_first {
2967                         assert!(closing_signed_b.is_none());
2968                 }
2969                 let (empty_a, mut closing_signed_a) = node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b.unwrap()).unwrap();
2970                 assert!(empty_a.is_none());
2971                 if close_inbound_first {
2972                         assert!(closing_signed_a.is_none());
2973                         closing_signed_a = node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
2974                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
2975                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
2976
2977                         let empty_b = node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
2978                         assert!(empty_b.is_none());
2979                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
2980                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
2981                 } else {
2982                         closing_signed_b = node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
2983                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
2984                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
2985
2986                         let empty_a2 = node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
2987                         assert!(empty_a2.is_none());
2988                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
2989                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
2990                 }
2991                 assert_eq!(tx_a, tx_b);
2992                 check_spends!(tx_a, funding_tx);
2993
2994                 let events_2 = node_a.get_and_clear_pending_events();
2995                 assert_eq!(events_2.len(), 1);
2996                 let as_update = match events_2[0] {
2997                         Event::BroadcastChannelUpdate { ref msg } => {
2998                                 msg.clone()
2999                         },
3000                         _ => panic!("Unexpected event"),
3001                 };
3002
3003                 let events_3 = node_b.get_and_clear_pending_events();
3004                 assert_eq!(events_3.len(), 1);
3005                 let bs_update = match events_3[0] {
3006                         Event::BroadcastChannelUpdate { ref msg } => {
3007                                 msg.clone()
3008                         },
3009                         _ => panic!("Unexpected event"),
3010                 };
3011
3012                 (as_update, bs_update)
3013         }
3014
3015         struct SendEvent {
3016                 node_id: PublicKey,
3017                 msgs: Vec<msgs::UpdateAddHTLC>,
3018                 commitment_msg: msgs::CommitmentSigned,
3019         }
3020         impl SendEvent {
3021                 fn from_event(event: Event) -> SendEvent {
3022                         match event {
3023                                 Event::UpdateHTLCs { node_id, updates: msgs::CommitmentUpdate { update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs, update_fee, commitment_signed } } => {
3024                                         assert!(update_fulfill_htlcs.is_empty());
3025                                         assert!(update_fail_htlcs.is_empty());
3026                                         assert!(update_fail_malformed_htlcs.is_empty());
3027                                         assert!(update_fee.is_none());
3028                                         SendEvent { node_id: node_id, msgs: update_add_htlcs, commitment_msg: commitment_signed }
3029                                 },
3030                                 _ => panic!("Unexpected event type!"),
3031                         }
3032                 }
3033         }
3034
3035         macro_rules! check_added_monitors {
3036                 ($node: expr, $count: expr) => {
3037                         {
3038                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3039                                 assert_eq!(added_monitors.len(), $count);
3040                                 added_monitors.clear();
3041                         }
3042                 }
3043         }
3044
3045         macro_rules! commitment_signed_dance {
3046                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
3047                         {
3048                                 check_added_monitors!($node_a, 0);
3049                                 let (as_revoke_and_ack, as_commitment_signed) = $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3050                                 check_added_monitors!($node_a, 1);
3051                                 check_added_monitors!($node_b, 0);
3052                                 assert!($node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
3053                                 check_added_monitors!($node_b, 1);
3054                                 let (bs_revoke_and_ack, bs_none) = $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed.unwrap()).unwrap();
3055                                 assert!(bs_none.is_none());
3056                                 check_added_monitors!($node_b, 1);
3057                                 if $fail_backwards {
3058                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
3059                                 }
3060                                 assert!($node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
3061                                 {
3062                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
3063                                         if $fail_backwards {
3064                                                 assert_eq!(added_monitors.len(), 2);
3065                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
3066                                         } else {
3067                                                 assert_eq!(added_monitors.len(), 1);
3068                                         }
3069                                         added_monitors.clear();
3070                                 }
3071                         }
3072                 }
3073         }
3074
3075         macro_rules! get_payment_preimage_hash {
3076                 ($node: expr) => {
3077                         {
3078                                 let payment_preimage = [*$node.network_payment_count.borrow(); 32];
3079                                 *$node.network_payment_count.borrow_mut() += 1;
3080                                 let mut payment_hash = [0; 32];
3081                                 let mut sha = Sha256::new();
3082                                 sha.input(&payment_preimage[..]);
3083                                 sha.result(&mut payment_hash);
3084                                 (payment_preimage, payment_hash)
3085                         }
3086                 }
3087         }
3088
3089         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
3090                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
3091
3092                 let mut payment_event = {
3093                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
3094                         check_added_monitors!(origin_node, 1);
3095
3096                         let mut events = origin_node.node.get_and_clear_pending_events();
3097                         assert_eq!(events.len(), 1);
3098                         SendEvent::from_event(events.remove(0))
3099                 };
3100                 let mut prev_node = origin_node;
3101
3102                 for (idx, &node) in expected_route.iter().enumerate() {
3103                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
3104
3105                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3106                         check_added_monitors!(node, 0);
3107                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
3108
3109                         let events_1 = node.node.get_and_clear_pending_events();
3110                         assert_eq!(events_1.len(), 1);
3111                         match events_1[0] {
3112                                 Event::PendingHTLCsForwardable { .. } => { },
3113                                 _ => panic!("Unexpected event"),
3114                         };
3115
3116                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
3117                         node.node.process_pending_htlc_forwards();
3118
3119                         let mut events_2 = node.node.get_and_clear_pending_events();
3120                         assert_eq!(events_2.len(), 1);
3121                         if idx == expected_route.len() - 1 {
3122                                 match events_2[0] {
3123                                         Event::PaymentReceived { ref payment_hash, amt } => {
3124                                                 assert_eq!(our_payment_hash, *payment_hash);
3125                                                 assert_eq!(amt, recv_value);
3126                                         },
3127                                         _ => panic!("Unexpected event"),
3128                                 }
3129                         } else {
3130                                 check_added_monitors!(node, 1);
3131                                 payment_event = SendEvent::from_event(events_2.remove(0));
3132                                 assert_eq!(payment_event.msgs.len(), 1);
3133                         }
3134
3135                         prev_node = node;
3136                 }
3137
3138                 (our_payment_preimage, our_payment_hash)
3139         }
3140
3141         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: [u8; 32]) {
3142                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
3143                 check_added_monitors!(expected_route.last().unwrap(), 1);
3144
3145                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
3146                 macro_rules! update_fulfill_dance {
3147                         ($node: expr, $prev_node: expr, $last_node: expr) => {
3148                                 {
3149                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
3150                                         if $last_node {
3151                                                 check_added_monitors!($node, 0);
3152                                         } else {
3153                                                 check_added_monitors!($node, 1);
3154                                         }
3155                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
3156                                 }
3157                         }
3158                 }
3159
3160                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
3161                 let mut prev_node = expected_route.last().unwrap();
3162                 for (idx, node) in expected_route.iter().rev().enumerate() {
3163                         assert_eq!(expected_next_node, node.node.get_our_node_id());
3164                         if next_msgs.is_some() {
3165                                 update_fulfill_dance!(node, prev_node, false);
3166                         }
3167
3168                         let events = node.node.get_and_clear_pending_events();
3169                         if !skip_last || idx != expected_route.len() - 1 {
3170                                 assert_eq!(events.len(), 1);
3171                                 match events[0] {
3172                                         Event::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 } } => {
3173                                                 assert!(update_add_htlcs.is_empty());
3174                                                 assert_eq!(update_fulfill_htlcs.len(), 1);
3175                                                 assert!(update_fail_htlcs.is_empty());
3176                                                 assert!(update_fail_malformed_htlcs.is_empty());
3177                                                 assert!(update_fee.is_none());
3178                                                 expected_next_node = node_id.clone();
3179                                                 next_msgs = Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()));
3180                                         },
3181                                         _ => panic!("Unexpected event"),
3182                                 }
3183                         } else {
3184                                 assert!(events.is_empty());
3185                         }
3186                         if !skip_last && idx == expected_route.len() - 1 {
3187                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
3188                         }
3189
3190                         prev_node = node;
3191                 }
3192
3193                 if !skip_last {
3194                         update_fulfill_dance!(origin_node, expected_route.first().unwrap(), true);
3195                         let events = origin_node.node.get_and_clear_pending_events();
3196                         assert_eq!(events.len(), 1);
3197                         match events[0] {
3198                                 Event::PaymentSent { payment_preimage } => {
3199                                         assert_eq!(payment_preimage, our_payment_preimage);
3200                                 },
3201                                 _ => panic!("Unexpected event"),
3202                         }
3203                 }
3204         }
3205
3206         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: [u8; 32]) {
3207                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
3208         }
3209
3210         const TEST_FINAL_CLTV: u32 = 32;
3211
3212         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
3213                 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();
3214                 assert_eq!(route.hops.len(), expected_route.len());
3215                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
3216                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
3217                 }
3218
3219                 send_along_route(origin_node, route, expected_route, recv_value)
3220         }
3221
3222         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
3223                 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();
3224                 assert_eq!(route.hops.len(), expected_route.len());
3225                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
3226                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
3227                 }
3228
3229                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
3230
3231                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
3232                 match err {
3233                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
3234                         _ => panic!("Unknown error variants"),
3235                 };
3236         }
3237
3238         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
3239                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
3240                 claim_payment(&origin, expected_route, our_payment_preimage);
3241         }
3242
3243         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: [u8; 32]) {
3244                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
3245                 check_added_monitors!(expected_route.last().unwrap(), 1);
3246
3247                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
3248                 macro_rules! update_fail_dance {
3249                         ($node: expr, $prev_node: expr, $last_node: expr) => {
3250                                 {
3251                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
3252                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
3253                                 }
3254                         }
3255                 }
3256
3257                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
3258                 let mut prev_node = expected_route.last().unwrap();
3259                 for (idx, node) in expected_route.iter().rev().enumerate() {
3260                         assert_eq!(expected_next_node, node.node.get_our_node_id());
3261                         if next_msgs.is_some() {
3262                                 // We may be the "last node" for the purpose of the commitment dance if we're
3263                                 // skipping the last node (implying it is disconnected) and we're the
3264                                 // second-to-last node!
3265                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
3266                         }
3267
3268                         let events = node.node.get_and_clear_pending_events();
3269                         if !skip_last || idx != expected_route.len() - 1 {
3270                                 assert_eq!(events.len(), 1);
3271                                 match events[0] {
3272                                         Event::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 } } => {
3273                                                 assert!(update_add_htlcs.is_empty());
3274                                                 assert!(update_fulfill_htlcs.is_empty());
3275                                                 assert_eq!(update_fail_htlcs.len(), 1);
3276                                                 assert!(update_fail_malformed_htlcs.is_empty());
3277                                                 assert!(update_fee.is_none());
3278                                                 expected_next_node = node_id.clone();
3279                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
3280                                         },
3281                                         _ => panic!("Unexpected event"),
3282                                 }
3283                         } else {
3284                                 assert!(events.is_empty());
3285                         }
3286                         if !skip_last && idx == expected_route.len() - 1 {
3287                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
3288                         }
3289
3290                         prev_node = node;
3291                 }
3292
3293                 if !skip_last {
3294                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
3295
3296                         let events = origin_node.node.get_and_clear_pending_events();
3297                         assert_eq!(events.len(), 1);
3298                         match events[0] {
3299                                 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
3300                                         assert_eq!(payment_hash, our_payment_hash);
3301                                         assert!(rejected_by_dest);
3302                                 },
3303                                 _ => panic!("Unexpected event"),
3304                         }
3305                 }
3306         }
3307
3308         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: [u8; 32]) {
3309                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
3310         }
3311
3312         fn create_network(node_count: usize) -> Vec<Node> {
3313                 let mut nodes = Vec::new();
3314                 let mut rng = thread_rng();
3315                 let secp_ctx = Secp256k1::new();
3316                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
3317
3318                 let chan_count = Rc::new(RefCell::new(0));
3319                 let payment_count = Rc::new(RefCell::new(0));
3320
3321                 for _ in 0..node_count {
3322                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
3323                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
3324                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
3325                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone()));
3326                         let node_id = {
3327                                 let mut key_slice = [0; 32];
3328                                 rng.fill_bytes(&mut key_slice);
3329                                 SecretKey::from_slice(&secp_ctx, &key_slice).unwrap()
3330                         };
3331                         let node = ChannelManager::new(node_id.clone(), 0, true, Network::Testnet, feeest.clone(), chan_monitor.clone(), chain_monitor.clone(), tx_broadcaster.clone(), Arc::clone(&logger)).unwrap();
3332                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &node_id), chain_monitor.clone(), Arc::clone(&logger));
3333                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router,
3334                                 network_payment_count: payment_count.clone(),
3335                                 network_chan_count: chan_count.clone(),
3336                         });
3337                 }
3338
3339                 nodes
3340         }
3341
3342         #[test]
3343         fn test_async_inbound_update_fee() {
3344                 let mut nodes = create_network(2);
3345                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3346                 let channel_id = chan.2;
3347
3348                 macro_rules! get_feerate {
3349                         ($node: expr) => {{
3350                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3351                                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3352                                 chan.get_feerate()
3353                         }}
3354                 }
3355
3356                 // balancing
3357                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
3358
3359                 // A                                        B
3360                 // update_fee                            ->
3361                 // send (1) commitment_signed            -.
3362                 //                                       <- update_add_htlc/commitment_signed
3363                 // send (2) RAA (awaiting remote revoke) -.
3364                 // (1) commitment_signed is delivered    ->
3365                 //                                       .- send (3) RAA (awaiting remote revoke)
3366                 // (2) RAA is delivered                  ->
3367                 //                                       .- send (4) commitment_signed
3368                 //                                       <- (3) RAA is delivered
3369                 // send (5) commitment_signed            -.
3370                 //                                       <- (4) commitment_signed is delivered
3371                 // send (6) RAA                          -.
3372                 // (5) commitment_signed is delivered    ->
3373                 //                                       <- RAA
3374                 // (6) RAA is delivered                  ->
3375
3376                 // First nodes[0] generates an update_fee
3377                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0]) + 20).unwrap();
3378                 check_added_monitors!(nodes[0], 1);
3379
3380                 let events_0 = nodes[0].node.get_and_clear_pending_events();
3381                 assert_eq!(events_0.len(), 1);
3382                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
3383                         Event::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
3384                                 (update_fee.as_ref(), commitment_signed)
3385                         },
3386                         _ => panic!("Unexpected event"),
3387                 };
3388
3389                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3390
3391                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
3392                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3393                 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();
3394                 check_added_monitors!(nodes[1], 1);
3395
3396                 let payment_event = {
3397                         let mut events_1 = nodes[1].node.get_and_clear_pending_events();
3398                         assert_eq!(events_1.len(), 1);
3399                         SendEvent::from_event(events_1.remove(0))
3400                 };
3401                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
3402                 assert_eq!(payment_event.msgs.len(), 1);
3403
3404                 // ...now when the messages get delivered everyone should be happy
3405                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3406                 let (as_revoke_msg, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
3407                 assert!(as_commitment_signed.is_none()); // nodes[0] is awaiting nodes[1] revoke_and_ack
3408                 check_added_monitors!(nodes[0], 1);
3409
3410                 // deliver(1), generate (3):
3411                 let (bs_revoke_msg, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3412                 assert!(bs_commitment_signed.is_none()); // nodes[1] is awaiting nodes[0] revoke_and_ack
3413                 check_added_monitors!(nodes[1], 1);
3414
3415                 let bs_update = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
3416                 assert!(bs_update.as_ref().unwrap().update_add_htlcs.is_empty()); // (4)
3417                 assert!(bs_update.as_ref().unwrap().update_fulfill_htlcs.is_empty()); // (4)
3418                 assert!(bs_update.as_ref().unwrap().update_fail_htlcs.is_empty()); // (4)
3419                 assert!(bs_update.as_ref().unwrap().update_fail_malformed_htlcs.is_empty()); // (4)
3420                 assert!(bs_update.as_ref().unwrap().update_fee.is_none()); // (4)
3421                 check_added_monitors!(nodes[1], 1);
3422
3423                 let as_update = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap(); // deliver (3)
3424                 assert!(as_update.as_ref().unwrap().update_add_htlcs.is_empty()); // (5)
3425                 assert!(as_update.as_ref().unwrap().update_fulfill_htlcs.is_empty()); // (5)
3426                 assert!(as_update.as_ref().unwrap().update_fail_htlcs.is_empty()); // (5)
3427                 assert!(as_update.as_ref().unwrap().update_fail_malformed_htlcs.is_empty()); // (5)
3428                 assert!(as_update.as_ref().unwrap().update_fee.is_none()); // (5)
3429                 check_added_monitors!(nodes[0], 1);
3430
3431                 let (as_second_revoke, as_second_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.unwrap().commitment_signed).unwrap(); // deliver (4)
3432                 assert!(as_second_commitment_signed.is_none()); // only (6)
3433                 check_added_monitors!(nodes[0], 1);
3434
3435                 let (bs_second_revoke, bs_second_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.unwrap().commitment_signed).unwrap(); // deliver (5)
3436                 assert!(bs_second_commitment_signed.is_none());
3437                 check_added_monitors!(nodes[1], 1);
3438
3439                 assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap().is_none());
3440                 check_added_monitors!(nodes[0], 1);
3441
3442                 let events_2 = nodes[0].node.get_and_clear_pending_events();
3443                 assert_eq!(events_2.len(), 1);
3444                 match events_2[0] {
3445                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
3446                         _ => panic!("Unexpected event"),
3447                 }
3448
3449                 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap().is_none()); // deliver (6)
3450                 check_added_monitors!(nodes[1], 1);
3451         }
3452
3453         #[test]
3454         fn test_update_fee_unordered_raa() {
3455                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
3456                 // crash in an earlier version of the update_fee patch)
3457                 let mut nodes = create_network(2);
3458                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3459                 let channel_id = chan.2;
3460
3461                 macro_rules! get_feerate {
3462                         ($node: expr) => {{
3463                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3464                                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3465                                 chan.get_feerate()
3466                         }}
3467                 }
3468
3469                 // balancing
3470                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
3471
3472                 // First nodes[0] generates an update_fee
3473                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0]) + 20).unwrap();
3474                 check_added_monitors!(nodes[0], 1);
3475
3476                 let events_0 = nodes[0].node.get_and_clear_pending_events();
3477                 assert_eq!(events_0.len(), 1);
3478                 let update_msg = match events_0[0] { // (1)
3479                         Event::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
3480                                 update_fee.as_ref()
3481                         },
3482                         _ => panic!("Unexpected event"),
3483                 };
3484
3485                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3486
3487                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
3488                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3489                 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();
3490                 check_added_monitors!(nodes[1], 1);
3491
3492                 let payment_event = {
3493                         let mut events_1 = nodes[1].node.get_and_clear_pending_events();
3494                         assert_eq!(events_1.len(), 1);
3495                         SendEvent::from_event(events_1.remove(0))
3496                 };
3497                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
3498                 assert_eq!(payment_event.msgs.len(), 1);
3499
3500                 // ...now when the messages get delivered everyone should be happy
3501                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3502                 let (as_revoke_msg, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
3503                 assert!(as_commitment_signed.is_none()); // nodes[0] is awaiting nodes[1] revoke_and_ack
3504                 check_added_monitors!(nodes[0], 1);
3505
3506                 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap().is_none()); // deliver (2)
3507                 check_added_monitors!(nodes[1], 1);
3508
3509                 // We can't continue, sadly, because our (1) now has a bogus signature
3510         }
3511
3512         #[test]
3513         fn test_multi_flight_update_fee() {
3514                 let nodes = create_network(2);
3515                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3516                 let channel_id = chan.2;
3517
3518                 macro_rules! get_feerate {
3519                         ($node: expr) => {{
3520                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3521                                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3522                                 chan.get_feerate()
3523                         }}
3524                 }
3525
3526                 // A                                        B
3527                 // update_fee/commitment_signed          ->
3528                 //                                       .- send (1) RAA and (2) commitment_signed
3529                 // update_fee (never committed)          ->
3530                 // (3) update_fee                        ->
3531                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
3532                 // don't track which updates correspond to which revoke_and_ack responses so we're in
3533                 // AwaitingRAA mode and will not generate the update_fee yet.
3534                 //                                       <- (1) RAA delivered
3535                 // (3) is generated and send (4) CS      -.
3536                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
3537                 // know the per_commitment_point to use for it.
3538                 //                                       <- (2) commitment_signed delivered
3539                 // revoke_and_ack                        ->
3540                 //                                          B should send no response here
3541                 // (4) commitment_signed delivered       ->
3542                 //                                       <- RAA/commitment_signed delivered
3543                 // revoke_and_ack                        ->
3544
3545                 // First nodes[0] generates an update_fee
3546                 let initial_feerate = get_feerate!(nodes[0]);
3547                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
3548                 check_added_monitors!(nodes[0], 1);
3549
3550                 let events_0 = nodes[0].node.get_and_clear_pending_events();
3551                 assert_eq!(events_0.len(), 1);
3552                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
3553                         Event::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
3554                                 (update_fee.as_ref().unwrap(), commitment_signed)
3555                         },
3556                         _ => panic!("Unexpected event"),
3557                 };
3558
3559                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
3560                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
3561                 let (bs_revoke_msg, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
3562                 check_added_monitors!(nodes[1], 1);
3563
3564                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
3565                 // transaction:
3566                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
3567                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3568
3569                 // Create the (3) update_fee message that nodes[0] will generate before it does...
3570                 let mut update_msg_2 = msgs::UpdateFee {
3571                         channel_id: update_msg_1.channel_id.clone(),
3572                         feerate_per_kw: (initial_feerate + 30) as u32,
3573                 };
3574
3575                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
3576
3577                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
3578                 // Deliver (3)
3579                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
3580
3581                 // Deliver (1), generating (3) and (4)
3582                 let as_second_update = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
3583                 check_added_monitors!(nodes[0], 1);
3584                 assert!(as_second_update.as_ref().unwrap().update_add_htlcs.is_empty());
3585                 assert!(as_second_update.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3586                 assert!(as_second_update.as_ref().unwrap().update_fail_htlcs.is_empty());
3587                 assert!(as_second_update.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3588                 // Check that the update_fee newly generated matches what we delivered:
3589                 assert_eq!(as_second_update.as_ref().unwrap().update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
3590                 assert_eq!(as_second_update.as_ref().unwrap().update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
3591
3592                 // Deliver (2) commitment_signed
3593                 let (as_revoke_msg, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), bs_commitment_signed.as_ref().unwrap()).unwrap();
3594                 check_added_monitors!(nodes[0], 1);
3595                 assert!(as_commitment_signed.is_none());
3596
3597                 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap().is_none());
3598                 check_added_monitors!(nodes[1], 1);
3599
3600                 // Delever (4)
3601                 let (bs_second_revoke, bs_second_commitment) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.unwrap().commitment_signed).unwrap();
3602                 check_added_monitors!(nodes[1], 1);
3603
3604                 assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap().is_none());
3605                 check_added_monitors!(nodes[0], 1);
3606
3607                 let (as_second_revoke, as_second_commitment) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment.unwrap()).unwrap();
3608                 assert!(as_second_commitment.is_none());
3609                 check_added_monitors!(nodes[0], 1);
3610
3611                 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap().is_none());
3612                 check_added_monitors!(nodes[1], 1);
3613         }
3614
3615         #[test]
3616         fn test_update_fee_vanilla() {
3617                 let nodes = create_network(2);
3618                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3619                 let channel_id = chan.2;
3620
3621                 macro_rules! get_feerate {
3622                         ($node: expr) => {{
3623                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3624                                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3625                                 chan.get_feerate()
3626                         }}
3627                 }
3628
3629                 let feerate = get_feerate!(nodes[0]);
3630                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
3631
3632                 let events_0 = nodes[0].node.get_and_clear_pending_events();
3633                 assert_eq!(events_0.len(), 1);
3634                 let (update_msg, commitment_signed) = match events_0[0] {
3635                                 Event::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 } } => {
3636                                 (update_fee.as_ref(), commitment_signed)
3637                         },
3638                         _ => panic!("Unexpected event"),
3639                 };
3640                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3641
3642                 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3643                 let commitment_signed = commitment_signed.unwrap();
3644                 check_added_monitors!(nodes[0], 1);
3645                 check_added_monitors!(nodes[1], 1);
3646
3647                 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3648                 assert!(resp_option.is_none());
3649                 check_added_monitors!(nodes[0], 1);
3650
3651                 let (revoke_msg, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3652                 assert!(commitment_signed.is_none());
3653                 check_added_monitors!(nodes[0], 1);
3654
3655                 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
3656                 assert!(resp_option.is_none());
3657                 check_added_monitors!(nodes[1], 1);
3658         }
3659
3660         #[test]
3661         fn test_update_fee_with_fundee_update_add_htlc() {
3662                 let mut nodes = create_network(2);
3663                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3664                 let channel_id = chan.2;
3665
3666                 macro_rules! get_feerate {
3667                         ($node: expr) => {{
3668                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3669                                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3670                                 chan.get_feerate()
3671                         }}
3672                 }
3673
3674                 // balancing
3675                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
3676
3677                 let feerate = get_feerate!(nodes[0]);
3678                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
3679
3680                 let events_0 = nodes[0].node.get_and_clear_pending_events();
3681                 assert_eq!(events_0.len(), 1);
3682                 let (update_msg, commitment_signed) = match events_0[0] {
3683                                 Event::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 } } => {
3684                                 (update_fee.as_ref(), commitment_signed)
3685                         },
3686                         _ => panic!("Unexpected event"),
3687                 };
3688                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3689                 check_added_monitors!(nodes[0], 1);
3690                 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3691                 let commitment_signed = commitment_signed.unwrap();
3692                 check_added_monitors!(nodes[1], 1);
3693
3694                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
3695
3696                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
3697
3698                 // nothing happens since node[1] is in AwaitingRemoteRevoke
3699                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
3700                 {
3701                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
3702                         assert_eq!(added_monitors.len(), 0);
3703                         added_monitors.clear();
3704                 }
3705                 let events = nodes[0].node.get_and_clear_pending_events();
3706                 assert_eq!(events.len(), 0);
3707                 // node[1] has nothing to do
3708
3709                 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3710                 assert!(resp_option.is_none());
3711                 check_added_monitors!(nodes[0], 1);
3712
3713                 let (revoke_msg, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3714                 assert!(commitment_signed.is_none());
3715                 check_added_monitors!(nodes[0], 1);
3716                 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
3717                 // AwaitingRemoteRevoke ends here
3718
3719                 let commitment_update = resp_option.unwrap();
3720                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
3721                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
3722                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
3723                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
3724                 assert_eq!(commitment_update.update_fee.is_none(), true);
3725
3726                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
3727                 let (revoke, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
3728                 check_added_monitors!(nodes[0], 1);
3729                 check_added_monitors!(nodes[1], 1);
3730                 let commitment_signed = commitment_signed.unwrap();
3731                 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
3732                 check_added_monitors!(nodes[1], 1);
3733                 assert!(resp_option.is_none());
3734
3735                 let (revoke, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
3736                 check_added_monitors!(nodes[1], 1);
3737                 assert!(commitment_signed.is_none());
3738                 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
3739                 check_added_monitors!(nodes[0], 1);
3740                 assert!(resp_option.is_none());
3741
3742                 let events = nodes[0].node.get_and_clear_pending_events();
3743                 assert_eq!(events.len(), 1);
3744                 match events[0] {
3745                         Event::PendingHTLCsForwardable { .. } => { },
3746                         _ => panic!("Unexpected event"),
3747                 };
3748                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
3749                 nodes[0].node.process_pending_htlc_forwards();
3750
3751                 let events = nodes[0].node.get_and_clear_pending_events();
3752                 assert_eq!(events.len(), 1);
3753                 match events[0] {
3754                         Event::PaymentReceived { .. } => { },
3755                         _ => panic!("Unexpected event"),
3756                 };
3757
3758                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
3759
3760                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
3761                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
3762                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
3763         }
3764
3765         #[test]
3766         fn test_update_fee() {
3767                 let nodes = create_network(2);
3768                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3769                 let channel_id = chan.2;
3770
3771                 macro_rules! get_feerate {
3772                         ($node: expr) => {{
3773                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3774                                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3775                                 chan.get_feerate()
3776                         }}
3777                 }
3778
3779                 // A                                        B
3780                 // (1) update_fee/commitment_signed      ->
3781                 //                                       <- (2) revoke_and_ack
3782                 //                                       .- send (3) commitment_signed
3783                 // (4) update_fee/commitment_signed      ->
3784                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
3785                 //                                       <- (3) commitment_signed delivered
3786                 // send (6) revoke_and_ack               -.
3787                 //                                       <- (5) deliver revoke_and_ack
3788                 // (6) deliver revoke_and_ack            ->
3789                 //                                       .- send (7) commitment_signed in response to (4)
3790                 //                                       <- (7) deliver commitment_signed
3791                 // revoke_and_ack                        ->
3792
3793                 // Create and deliver (1)...
3794                 let feerate = get_feerate!(nodes[0]);
3795                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
3796
3797                 let events_0 = nodes[0].node.get_and_clear_pending_events();
3798                 assert_eq!(events_0.len(), 1);
3799                 let (update_msg, commitment_signed) = match events_0[0] {
3800                                 Event::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 } } => {
3801                                 (update_fee.as_ref(), commitment_signed)
3802                         },
3803                         _ => panic!("Unexpected event"),
3804                 };
3805                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3806
3807                 // Generate (2) and (3):
3808                 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3809                 let commitment_signed_0 = commitment_signed.unwrap();
3810                 check_added_monitors!(nodes[0], 1);
3811                 check_added_monitors!(nodes[1], 1);
3812
3813                 // Deliver (2):
3814                 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3815                 assert!(resp_option.is_none());
3816                 check_added_monitors!(nodes[0], 1);
3817
3818                 // Create and deliver (4)...
3819                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
3820                 let events_0 = nodes[0].node.get_and_clear_pending_events();
3821                 assert_eq!(events_0.len(), 1);
3822                 let (update_msg, commitment_signed) = match events_0[0] {
3823                                 Event::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 } } => {
3824                                 (update_fee.as_ref(), commitment_signed)
3825                         },
3826                         _ => panic!("Unexpected event"),
3827                 };
3828                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3829
3830                 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3831                 // ... creating (5)
3832                 assert!(commitment_signed.is_none());
3833                 check_added_monitors!(nodes[0], 1);
3834                 check_added_monitors!(nodes[1], 1);
3835
3836                 // Handle (3), creating (6):
3837                 let (revoke_msg_0, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
3838                 assert!(commitment_signed.is_none());
3839                 check_added_monitors!(nodes[0], 1);
3840
3841                 // Deliver (5):
3842                 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3843                 assert!(resp_option.is_none());
3844                 check_added_monitors!(nodes[0], 1);
3845
3846                 // Deliver (6), creating (7):
3847                 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
3848                 let commitment_signed = resp_option.unwrap().commitment_signed;
3849                 check_added_monitors!(nodes[1], 1);
3850
3851                 // Deliver (7)
3852                 let (revoke_msg, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3853                 assert!(commitment_signed.is_none());
3854                 check_added_monitors!(nodes[0], 1);
3855                 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
3856                 assert!(resp_option.is_none());
3857                 check_added_monitors!(nodes[1], 1);
3858
3859                 assert_eq!(get_feerate!(nodes[0]), feerate + 30);
3860                 assert_eq!(get_feerate!(nodes[1]), feerate + 30);
3861                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
3862         }
3863
3864         #[test]
3865         fn fake_network_test() {
3866                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
3867                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
3868                 let nodes = create_network(4);
3869
3870                 // Create some initial channels
3871                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3872                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3873                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
3874
3875                 // Rebalance the network a bit by relaying one payment through all the channels...
3876                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
3877                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
3878                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
3879                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
3880
3881                 // Send some more payments
3882                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
3883                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
3884                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
3885
3886                 // Test failure packets
3887                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
3888                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
3889
3890                 // Add a new channel that skips 3
3891                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
3892
3893                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
3894                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
3895                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3896                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3897                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3898                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3899                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3900
3901                 // Do some rebalance loop payments, simultaneously
3902                 let mut hops = Vec::with_capacity(3);
3903                 hops.push(RouteHop {
3904                         pubkey: nodes[2].node.get_our_node_id(),
3905                         short_channel_id: chan_2.0.contents.short_channel_id,
3906                         fee_msat: 0,
3907                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
3908                 });
3909                 hops.push(RouteHop {
3910                         pubkey: nodes[3].node.get_our_node_id(),
3911                         short_channel_id: chan_3.0.contents.short_channel_id,
3912                         fee_msat: 0,
3913                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
3914                 });
3915                 hops.push(RouteHop {
3916                         pubkey: nodes[1].node.get_our_node_id(),
3917                         short_channel_id: chan_4.0.contents.short_channel_id,
3918                         fee_msat: 1000000,
3919                         cltv_expiry_delta: TEST_FINAL_CLTV,
3920                 });
3921                 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;
3922                 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;
3923                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
3924
3925                 let mut hops = Vec::with_capacity(3);
3926                 hops.push(RouteHop {
3927                         pubkey: nodes[3].node.get_our_node_id(),
3928                         short_channel_id: chan_4.0.contents.short_channel_id,
3929                         fee_msat: 0,
3930                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
3931                 });
3932                 hops.push(RouteHop {
3933                         pubkey: nodes[2].node.get_our_node_id(),
3934                         short_channel_id: chan_3.0.contents.short_channel_id,
3935                         fee_msat: 0,
3936                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
3937                 });
3938                 hops.push(RouteHop {
3939                         pubkey: nodes[1].node.get_our_node_id(),
3940                         short_channel_id: chan_2.0.contents.short_channel_id,
3941                         fee_msat: 1000000,
3942                         cltv_expiry_delta: TEST_FINAL_CLTV,
3943                 });
3944                 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;
3945                 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;
3946                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
3947
3948                 // Claim the rebalances...
3949                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
3950                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
3951
3952                 // Add a duplicate new channel from 2 to 4
3953                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
3954
3955                 // Send some payments across both channels
3956                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3957                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3958                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3959
3960                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
3961
3962                 //TODO: Test that routes work again here as we've been notified that the channel is full
3963
3964                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
3965                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
3966                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
3967
3968                 // Close down the channels...
3969                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
3970                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
3971                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
3972                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
3973                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
3974         }
3975
3976         #[test]
3977         fn duplicate_htlc_test() {
3978                 // Test that we accept duplicate payment_hash HTLCs across the network and that
3979                 // claiming/failing them are all separate and don't effect each other
3980                 let mut nodes = create_network(6);
3981
3982                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
3983                 create_announced_chan_between_nodes(&nodes, 0, 3);
3984                 create_announced_chan_between_nodes(&nodes, 1, 3);
3985                 create_announced_chan_between_nodes(&nodes, 2, 3);
3986                 create_announced_chan_between_nodes(&nodes, 3, 4);
3987                 create_announced_chan_between_nodes(&nodes, 3, 5);
3988
3989                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
3990
3991                 *nodes[0].network_payment_count.borrow_mut() -= 1;
3992                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
3993
3994                 *nodes[0].network_payment_count.borrow_mut() -= 1;
3995                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
3996
3997                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
3998                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
3999                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
4000         }
4001
4002         #[derive(PartialEq)]
4003         enum HTLCType { NONE, TIMEOUT, SUCCESS }
4004         /// Tests that the given node has broadcast transactions for the given Channel
4005         ///
4006         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
4007         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
4008         /// broadcast and the revoked outputs were claimed.
4009         ///
4010         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
4011         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
4012         ///
4013         /// All broadcast transactions must be accounted for in one of the above three types of we'll
4014         /// also fail.
4015         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
4016                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
4017                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
4018
4019                 let mut res = Vec::with_capacity(2);
4020                 node_txn.retain(|tx| {
4021                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
4022                                 check_spends!(tx, chan.3.clone());
4023                                 if commitment_tx.is_none() {
4024                                         res.push(tx.clone());
4025                                 }
4026                                 false
4027                         } else { true }
4028                 });
4029                 if let Some(explicit_tx) = commitment_tx {
4030                         res.push(explicit_tx.clone());
4031                 }
4032
4033                 assert_eq!(res.len(), 1);
4034
4035                 if has_htlc_tx != HTLCType::NONE {
4036                         node_txn.retain(|tx| {
4037                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
4038                                         check_spends!(tx, res[0].clone());
4039                                         if has_htlc_tx == HTLCType::TIMEOUT {
4040                                                 assert!(tx.lock_time != 0);
4041                                         } else {
4042                                                 assert!(tx.lock_time == 0);
4043                                         }
4044                                         res.push(tx.clone());
4045                                         false
4046                                 } else { true }
4047                         });
4048                         assert_eq!(res.len(), 2);
4049                 }
4050
4051                 assert!(node_txn.is_empty());
4052                 res
4053         }
4054
4055         /// Tests that the given node has broadcast a claim transaction against the provided revoked
4056         /// HTLC transaction.
4057         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
4058                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
4059                 assert_eq!(node_txn.len(), 1);
4060                 node_txn.retain(|tx| {
4061                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
4062                                 check_spends!(tx, revoked_tx.clone());
4063                                 false
4064                         } else { true }
4065                 });
4066                 assert!(node_txn.is_empty());
4067         }
4068
4069         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
4070                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
4071
4072                 assert!(node_txn.len() >= 1);
4073                 assert_eq!(node_txn[0].input.len(), 1);
4074                 let mut found_prev = false;
4075
4076                 for tx in prev_txn {
4077                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
4078                                 check_spends!(node_txn[0], tx.clone());
4079                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
4080                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
4081
4082                                 found_prev = true;
4083                                 break;
4084                         }
4085                 }
4086                 assert!(found_prev);
4087
4088                 let mut res = Vec::new();
4089                 mem::swap(&mut *node_txn, &mut res);
4090                 res
4091         }
4092
4093         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
4094                 let events_1 = nodes[a].node.get_and_clear_pending_events();
4095                 assert_eq!(events_1.len(), 1);
4096                 let as_update = match events_1[0] {
4097                         Event::BroadcastChannelUpdate { ref msg } => {
4098                                 msg.clone()
4099                         },
4100                         _ => panic!("Unexpected event"),
4101                 };
4102
4103                 let events_2 = nodes[b].node.get_and_clear_pending_events();
4104                 assert_eq!(events_2.len(), 1);
4105                 let bs_update = match events_2[0] {
4106                         Event::BroadcastChannelUpdate { ref msg } => {
4107                                 msg.clone()
4108                         },
4109                         _ => panic!("Unexpected event"),
4110                 };
4111
4112                 for node in nodes {
4113                         node.router.handle_channel_update(&as_update).unwrap();
4114                         node.router.handle_channel_update(&bs_update).unwrap();
4115                 }
4116         }
4117
4118         #[test]
4119         fn channel_reserve_test() {
4120                 use util::rng;
4121                 use std::sync::atomic::Ordering;
4122                 use ln::msgs::HandleError;
4123
4124                 macro_rules! get_channel_value_stat {
4125                         ($node: expr, $channel_id: expr) => {{
4126                                 let chan_lock = $node.node.channel_state.lock().unwrap();
4127                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
4128                                 chan.get_value_stat()
4129                         }}
4130                 }
4131
4132                 let mut nodes = create_network(3);
4133                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
4134                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
4135
4136                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
4137                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
4138
4139                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
4140                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
4141
4142                 macro_rules! get_route_and_payment_hash {
4143                         ($recv_value: expr) => {{
4144                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
4145                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4146                                 (route, payment_hash, payment_preimage)
4147                         }}
4148                 };
4149
4150                 macro_rules! expect_pending_htlcs_forwardable {
4151                         ($node: expr) => {{
4152                                 let events = $node.node.get_and_clear_pending_events();
4153                                 assert_eq!(events.len(), 1);
4154                                 match events[0] {
4155                                         Event::PendingHTLCsForwardable { .. } => { },
4156                                         _ => panic!("Unexpected event"),
4157                                 };
4158                                 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4159                                 $node.node.process_pending_htlc_forwards();
4160                         }}
4161                 };
4162
4163                 macro_rules! expect_forward {
4164                         ($node: expr) => {{
4165                                 let mut events = $node.node.get_and_clear_pending_events();
4166                                 assert_eq!(events.len(), 1);
4167                                 check_added_monitors!($node, 1);
4168                                 let payment_event = SendEvent::from_event(events.remove(0));
4169                                 payment_event
4170                         }}
4171                 }
4172
4173                 macro_rules! expect_payment_received {
4174                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
4175                                 let events = $node.node.get_and_clear_pending_events();
4176                                 assert_eq!(events.len(), 1);
4177                                 match events[0] {
4178                                         Event::PaymentReceived { ref payment_hash, amt } => {
4179                                                 assert_eq!($expected_payment_hash, *payment_hash);
4180                                                 assert_eq!($expected_recv_value, amt);
4181                                         },
4182                                         _ => panic!("Unexpected event"),
4183                                 }
4184                         }
4185                 };
4186
4187                 let feemsat = 239; // somehow we know?
4188                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
4189
4190                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
4191
4192                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
4193                 {
4194                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
4195                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
4196                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
4197                         match err {
4198                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4199                                 _ => panic!("Unknown error variants"),
4200                         }
4201                 }
4202
4203                 let mut htlc_id = 0;
4204                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
4205                 // nodes[0]'s wealth
4206                 loop {
4207                         let amt_msat = recv_value_0 + total_fee_msat;
4208                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
4209                                 break;
4210                         }
4211                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
4212                         htlc_id += 1;
4213
4214                         let (stat01_, stat11_, stat12_, stat22_) = (
4215                                 get_channel_value_stat!(nodes[0], chan_1.2),
4216                                 get_channel_value_stat!(nodes[1], chan_1.2),
4217                                 get_channel_value_stat!(nodes[1], chan_2.2),
4218                                 get_channel_value_stat!(nodes[2], chan_2.2),
4219                         );
4220
4221                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
4222                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
4223                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
4224                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
4225                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
4226                 }
4227
4228                 {
4229                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
4230                         // attempt to get channel_reserve violation
4231                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
4232                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
4233                         match err {
4234                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
4235                                 _ => panic!("Unknown error variants"),
4236                         }
4237                 }
4238
4239                 // adding pending output
4240                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
4241                 let amt_msat_1 = recv_value_1 + total_fee_msat;
4242
4243                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
4244                 let payment_event_1 = {
4245                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
4246                         check_added_monitors!(nodes[0], 1);
4247
4248                         let mut events = nodes[0].node.get_and_clear_pending_events();
4249                         assert_eq!(events.len(), 1);
4250                         SendEvent::from_event(events.remove(0))
4251                 };
4252                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
4253
4254                 // channel reserve test with htlc pending output > 0
4255                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
4256                 {
4257                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
4258                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
4259                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
4260                                 _ => panic!("Unknown error variants"),
4261                         }
4262                 }
4263
4264                 {
4265                         // test channel_reserve test on nodes[1] side
4266                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
4267
4268                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
4269                         let secp_ctx = Secp256k1::new();
4270                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
4271                                 let mut session_key = [0; 32];
4272                                 rng::fill_bytes(&mut session_key);
4273                                 session_key
4274                         }).expect("RNG is bad!");
4275
4276                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4277                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
4278                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
4279                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
4280                         let msg = msgs::UpdateAddHTLC {
4281                                 channel_id: chan_1.2,
4282                                 htlc_id,
4283                                 amount_msat: htlc_msat,
4284                                 payment_hash: our_payment_hash,
4285                                 cltv_expiry: htlc_cltv,
4286                                 onion_routing_packet: onion_packet,
4287                         };
4288
4289                         let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
4290                         match err {
4291                                 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
4292                         }
4293                 }
4294
4295                 // split the rest to test holding cell
4296                 let recv_value_21 = recv_value_2/2;
4297                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
4298                 {
4299                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
4300                         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);
4301                 }
4302
4303                 // now see if they go through on both sides
4304                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
4305                 // but this will stuck in the holding cell
4306                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
4307                 check_added_monitors!(nodes[0], 0);
4308                 let events = nodes[0].node.get_and_clear_pending_events();
4309                 assert_eq!(events.len(), 0);
4310
4311                 // test with outbound holding cell amount > 0
4312                 {
4313                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
4314                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
4315                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
4316                                 _ => panic!("Unknown error variants"),
4317                         }
4318                 }
4319
4320                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
4321                 // this will also stuck in the holding cell
4322                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
4323                 check_added_monitors!(nodes[0], 0);
4324                 let events = nodes[0].node.get_and_clear_pending_events();
4325                 assert_eq!(events.len(), 0);
4326
4327                 // flush the pending htlc
4328                 let (as_revoke_and_ack, as_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
4329                 check_added_monitors!(nodes[1], 1);
4330
4331                 let commitment_update_2 = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap().unwrap();
4332                 check_added_monitors!(nodes[0], 1);
4333                 let (bs_revoke_and_ack, bs_none) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed.unwrap()).unwrap();
4334                 assert!(bs_none.is_none());
4335                 check_added_monitors!(nodes[0], 1);
4336                 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
4337                 check_added_monitors!(nodes[1], 1);
4338
4339                 expect_pending_htlcs_forwardable!(nodes[1]);
4340
4341                 let ref payment_event_11 = expect_forward!(nodes[1]);
4342                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
4343                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
4344
4345                 expect_pending_htlcs_forwardable!(nodes[2]);
4346                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
4347
4348                 // flush the htlcs in the holding cell
4349                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
4350                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
4351                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
4352                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
4353                 expect_pending_htlcs_forwardable!(nodes[1]);
4354
4355                 let ref payment_event_3 = expect_forward!(nodes[1]);
4356                 assert_eq!(payment_event_3.msgs.len(), 2);
4357                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
4358                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
4359
4360                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
4361                 expect_pending_htlcs_forwardable!(nodes[2]);
4362
4363                 let events = nodes[2].node.get_and_clear_pending_events();
4364                 assert_eq!(events.len(), 2);
4365                 match events[0] {
4366                         Event::PaymentReceived { ref payment_hash, amt } => {
4367                                 assert_eq!(our_payment_hash_21, *payment_hash);
4368                                 assert_eq!(recv_value_21, amt);
4369                         },
4370                         _ => panic!("Unexpected event"),
4371                 }
4372                 match events[1] {
4373                         Event::PaymentReceived { ref payment_hash, amt } => {
4374                                 assert_eq!(our_payment_hash_22, *payment_hash);
4375                                 assert_eq!(recv_value_22, amt);
4376                         },
4377                         _ => panic!("Unexpected event"),
4378                 }
4379
4380                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
4381                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
4382                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
4383
4384                 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);
4385                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
4386                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
4387                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
4388
4389                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
4390                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
4391         }
4392
4393         #[test]
4394         fn channel_monitor_network_test() {
4395                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
4396                 // tests that ChannelMonitor is able to recover from various states.
4397                 let nodes = create_network(5);
4398
4399                 // Create some initial channels
4400                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4401                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4402                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4403                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4404
4405                 // Rebalance the network a bit by relaying one payment through all the channels...
4406                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
4407                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
4408                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
4409                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
4410
4411                 // Simple case with no pending HTLCs:
4412                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
4413                 {
4414                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
4415                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4416                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
4417                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
4418                 }
4419                 get_announce_close_broadcast_events(&nodes, 0, 1);
4420                 assert_eq!(nodes[0].node.list_channels().len(), 0);
4421                 assert_eq!(nodes[1].node.list_channels().len(), 1);
4422
4423                 // One pending HTLC is discarded by the force-close:
4424                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
4425
4426                 // Simple case of one pending HTLC to HTLC-Timeout
4427                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
4428                 {
4429                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
4430                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4431                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
4432                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
4433                 }
4434                 get_announce_close_broadcast_events(&nodes, 1, 2);
4435                 assert_eq!(nodes[1].node.list_channels().len(), 0);
4436                 assert_eq!(nodes[2].node.list_channels().len(), 1);
4437
4438                 macro_rules! claim_funds {
4439                         ($node: expr, $prev_node: expr, $preimage: expr) => {
4440                                 {
4441                                         assert!($node.node.claim_funds($preimage));
4442                                         check_added_monitors!($node, 1);
4443
4444                                         let events = $node.node.get_and_clear_pending_events();
4445                                         assert_eq!(events.len(), 1);
4446                                         match events[0] {
4447                                                 Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
4448                                                         assert!(update_add_htlcs.is_empty());
4449                                                         assert!(update_fail_htlcs.is_empty());
4450                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
4451                                                 },
4452                                                 _ => panic!("Unexpected event"),
4453                                         };
4454                                 }
4455                         }
4456                 }
4457
4458                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
4459                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
4460                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
4461                 {
4462                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
4463
4464                         // Claim the payment on nodes[3], giving it knowledge of the preimage
4465                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
4466
4467                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4468                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
4469
4470                         check_preimage_claim(&nodes[3], &node_txn);
4471                 }
4472                 get_announce_close_broadcast_events(&nodes, 2, 3);
4473                 assert_eq!(nodes[2].node.list_channels().len(), 0);
4474                 assert_eq!(nodes[3].node.list_channels().len(), 1);
4475
4476                 { // Cheat and reset nodes[4]'s height to 1
4477                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4478                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
4479                 }
4480
4481                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
4482                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
4483                 // One pending HTLC to time out:
4484                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
4485                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
4486                 // buffer space).
4487
4488                 {
4489                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4490                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
4491                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
4492                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4493                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
4494                         }
4495
4496                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
4497
4498                         // Claim the payment on nodes[4], giving it knowledge of the preimage
4499                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
4500
4501                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4502                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
4503                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
4504                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4505                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
4506                         }
4507
4508                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
4509
4510                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4511                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
4512
4513                         check_preimage_claim(&nodes[4], &node_txn);
4514                 }
4515                 get_announce_close_broadcast_events(&nodes, 3, 4);
4516                 assert_eq!(nodes[3].node.list_channels().len(), 0);
4517                 assert_eq!(nodes[4].node.list_channels().len(), 0);
4518
4519                 // Create some new channels:
4520                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
4521
4522                 // A pending HTLC which will be revoked:
4523                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4524                 // Get the will-be-revoked local txn from nodes[0]
4525                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
4526                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
4527                 assert_eq!(revoked_local_txn[0].input.len(), 1);
4528                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
4529                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
4530                 assert_eq!(revoked_local_txn[1].input.len(), 1);
4531                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
4532                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), 133); // HTLC-Timeout
4533                 // Revoke the old state
4534                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
4535
4536                 {
4537                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4538                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4539                         {
4540                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4541                                 assert_eq!(node_txn.len(), 3);
4542                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
4543                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
4544
4545                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
4546                                 node_txn.swap_remove(0);
4547                         }
4548                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
4549
4550                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4551                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
4552                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4553                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
4554                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
4555                 }
4556                 get_announce_close_broadcast_events(&nodes, 0, 1);
4557                 assert_eq!(nodes[0].node.list_channels().len(), 0);
4558                 assert_eq!(nodes[1].node.list_channels().len(), 0);
4559         }
4560
4561         #[test]
4562         fn revoked_output_claim() {
4563                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
4564                 // transaction is broadcast by its counterparty
4565                 let nodes = create_network(2);
4566                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4567                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
4568                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4569                 assert_eq!(revoked_local_txn.len(), 1);
4570                 // Only output is the full channel value back to nodes[0]:
4571                 assert_eq!(revoked_local_txn[0].output.len(), 1);
4572                 // Send a payment through, updating everyone's latest commitment txn
4573                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
4574
4575                 // Inform nodes[1] that nodes[0] broadcast a stale tx
4576                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4577                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4578                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4579                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
4580
4581                 assert_eq!(node_txn[0], node_txn[2]);
4582
4583                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
4584                 check_spends!(node_txn[1], chan_1.3.clone());
4585
4586                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
4587                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4588                 get_announce_close_broadcast_events(&nodes, 0, 1);
4589         }
4590
4591         #[test]
4592         fn claim_htlc_outputs_shared_tx() {
4593                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
4594                 let nodes = create_network(2);
4595
4596                 // Create some new channel:
4597                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4598
4599                 // Rebalance the network to generate htlc in the two directions
4600                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4601                 // 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
4602                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4603                 let _payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
4604
4605                 // Get the will-be-revoked local txn from node[0]
4606                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4607                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
4608                 assert_eq!(revoked_local_txn[0].input.len(), 1);
4609                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4610                 assert_eq!(revoked_local_txn[1].input.len(), 1);
4611                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
4612                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), 133); // HTLC-Timeout
4613                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
4614
4615                 //Revoke the old state
4616                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
4617
4618                 {
4619                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4620
4621                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4622
4623                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4624                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4625                         assert_eq!(node_txn.len(), 4);
4626
4627                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
4628                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
4629
4630                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
4631
4632                         let mut witness_lens = BTreeSet::new();
4633                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
4634                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
4635                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
4636                         assert_eq!(witness_lens.len(), 3);
4637                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
4638                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), 133); // revoked offered HTLC
4639                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), 138); // revoked received HTLC
4640
4641                         // Next nodes[1] broadcasts its current local tx state:
4642                         assert_eq!(node_txn[1].input.len(), 1);
4643                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
4644
4645                         assert_eq!(node_txn[2].input.len(), 1);
4646                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
4647                         assert_eq!(witness_script.len(), 133); //Spending an offered htlc output
4648                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
4649                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
4650                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
4651                 }
4652                 get_announce_close_broadcast_events(&nodes, 0, 1);
4653                 assert_eq!(nodes[0].node.list_channels().len(), 0);
4654                 assert_eq!(nodes[1].node.list_channels().len(), 0);
4655         }
4656
4657         #[test]
4658         fn claim_htlc_outputs_single_tx() {
4659                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
4660                 let nodes = create_network(2);
4661
4662                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4663
4664                 // Rebalance the network to generate htlc in the two directions
4665                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4666                 // 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
4667                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
4668                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4669                 let _payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
4670
4671                 // Get the will-be-revoked local txn from node[0]
4672                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4673
4674                 //Revoke the old state
4675                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
4676
4677                 {
4678                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4679
4680                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
4681
4682                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
4683                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4684                         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)
4685
4686                         assert_eq!(node_txn[0], node_txn[7]);
4687                         assert_eq!(node_txn[1], node_txn[8]);
4688                         assert_eq!(node_txn[2], node_txn[9]);
4689                         assert_eq!(node_txn[3], node_txn[10]);
4690                         assert_eq!(node_txn[4], node_txn[11]);
4691                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
4692                         assert_eq!(node_txn[4], node_txn[6]);
4693
4694                         assert_eq!(node_txn[0].input.len(), 1);
4695                         assert_eq!(node_txn[1].input.len(), 1);
4696                         assert_eq!(node_txn[2].input.len(), 1);
4697
4698                         let mut revoked_tx_map = HashMap::new();
4699                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
4700                         node_txn[0].verify(&revoked_tx_map).unwrap();
4701                         node_txn[1].verify(&revoked_tx_map).unwrap();
4702                         node_txn[2].verify(&revoked_tx_map).unwrap();
4703
4704                         let mut witness_lens = BTreeSet::new();
4705                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
4706                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
4707                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
4708                         assert_eq!(witness_lens.len(), 3);
4709                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
4710                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), 133); // revoked offered HTLC
4711                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), 138); // revoked received HTLC
4712
4713                         assert_eq!(node_txn[3].input.len(), 1);
4714                         check_spends!(node_txn[3], chan_1.3.clone());
4715
4716                         assert_eq!(node_txn[4].input.len(), 1);
4717                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
4718                         assert_eq!(witness_script.len(), 133); //Spending an offered htlc output
4719                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
4720                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
4721                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
4722                 }
4723                 get_announce_close_broadcast_events(&nodes, 0, 1);
4724                 assert_eq!(nodes[0].node.list_channels().len(), 0);
4725                 assert_eq!(nodes[1].node.list_channels().len(), 0);
4726         }
4727
4728         #[test]
4729         fn test_htlc_ignore_latest_remote_commitment() {
4730                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
4731                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
4732                 let nodes = create_network(2);
4733                 create_announced_chan_between_nodes(&nodes, 0, 1);
4734
4735                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
4736                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
4737                 {
4738                         let events = nodes[0].node.get_and_clear_pending_events();
4739                         assert_eq!(events.len(), 1);
4740                         match events[0] {
4741                                 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4742                                         assert_eq!(flags & 0b10, 0b10);
4743                                 },
4744                                 _ => panic!("Unexpected event"),
4745                         }
4746                 }
4747
4748                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4749                 assert_eq!(node_txn.len(), 2);
4750
4751                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4752                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
4753
4754                 {
4755                         let events = nodes[1].node.get_and_clear_pending_events();
4756                         assert_eq!(events.len(), 1);
4757                         match events[0] {
4758                                 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4759                                         assert_eq!(flags & 0b10, 0b10);
4760                                 },
4761                                 _ => panic!("Unexpected event"),
4762                         }
4763                 }
4764
4765                 // Duplicate the block_connected call since this may happen due to other listeners
4766                 // registering new transactions
4767                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
4768         }
4769
4770         #[test]
4771         fn test_force_close_fail_back() {
4772                 // Check which HTLCs are failed-backwards on channel force-closure
4773                 let mut nodes = create_network(3);
4774                 create_announced_chan_between_nodes(&nodes, 0, 1);
4775                 create_announced_chan_between_nodes(&nodes, 1, 2);
4776
4777                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
4778
4779                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4780
4781                 let mut payment_event = {
4782                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4783                         check_added_monitors!(nodes[0], 1);
4784
4785                         let mut events = nodes[0].node.get_and_clear_pending_events();
4786                         assert_eq!(events.len(), 1);
4787                         SendEvent::from_event(events.remove(0))
4788                 };
4789
4790                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4791                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4792
4793                 let events_1 = nodes[1].node.get_and_clear_pending_events();
4794                 assert_eq!(events_1.len(), 1);
4795                 match events_1[0] {
4796                         Event::PendingHTLCsForwardable { .. } => { },
4797                         _ => panic!("Unexpected event"),
4798                 };
4799
4800                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
4801                 nodes[1].node.process_pending_htlc_forwards();
4802
4803                 let mut events_2 = nodes[1].node.get_and_clear_pending_events();
4804                 assert_eq!(events_2.len(), 1);
4805                 payment_event = SendEvent::from_event(events_2.remove(0));
4806                 assert_eq!(payment_event.msgs.len(), 1);
4807
4808                 check_added_monitors!(nodes[1], 1);
4809                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4810                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
4811                 check_added_monitors!(nodes[2], 1);
4812
4813                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
4814                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
4815                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
4816
4817                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
4818                 let events_3 = nodes[2].node.get_and_clear_pending_events();
4819                 assert_eq!(events_3.len(), 1);
4820                 match events_3[0] {
4821                         Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4822                                 assert_eq!(flags & 0b10, 0b10);
4823                         },
4824                         _ => panic!("Unexpected event"),
4825                 }
4826
4827                 let tx = {
4828                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
4829                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
4830                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
4831                         // back to nodes[1] upon timeout otherwise.
4832                         assert_eq!(node_txn.len(), 1);
4833                         node_txn.remove(0)
4834                 };
4835
4836                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4837                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
4838
4839                 let events_4 = nodes[1].node.get_and_clear_pending_events();
4840                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
4841                 assert_eq!(events_4.len(), 1);
4842                 match events_4[0] {
4843                         Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4844                                 assert_eq!(flags & 0b10, 0b10);
4845                         },
4846                         _ => panic!("Unexpected event"),
4847                 }
4848
4849                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
4850                 {
4851                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
4852                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
4853                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
4854                 }
4855                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
4856                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
4857                 assert_eq!(node_txn.len(), 1);
4858                 assert_eq!(node_txn[0].input.len(), 1);
4859                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
4860                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
4861                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
4862
4863                 check_spends!(node_txn[0], tx);
4864         }
4865
4866         #[test]
4867         fn test_unconf_chan() {
4868                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
4869                 let nodes = create_network(2);
4870                 create_announced_chan_between_nodes(&nodes, 0, 1);
4871
4872                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
4873                 assert_eq!(channel_state.by_id.len(), 1);
4874                 assert_eq!(channel_state.short_to_id.len(), 1);
4875                 mem::drop(channel_state);
4876
4877                 let mut headers = Vec::new();
4878                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4879                 headers.push(header.clone());
4880                 for _i in 2..100 {
4881                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4882                         headers.push(header.clone());
4883                 }
4884                 while !headers.is_empty() {
4885                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
4886                 }
4887                 {
4888                         let events = nodes[0].node.get_and_clear_pending_events();
4889                         assert_eq!(events.len(), 1);
4890                         match events[0] {
4891                                 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4892                                         assert_eq!(flags & 0b10, 0b10);
4893                                 },
4894                                 _ => panic!("Unexpected event"),
4895                         }
4896                 }
4897                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
4898                 assert_eq!(channel_state.by_id.len(), 0);
4899                 assert_eq!(channel_state.short_to_id.len(), 0);
4900         }
4901
4902         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
4903         /// for claims/fails they are separated out.
4904         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)) {
4905                 let reestablish_1 = node_a.node.peer_connected(&node_b.node.get_our_node_id());
4906                 let reestablish_2 = node_b.node.peer_connected(&node_a.node.get_our_node_id());
4907
4908                 let mut resp_1 = Vec::new();
4909                 for msg in reestablish_1 {
4910                         resp_1.push(node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap());
4911                 }
4912                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
4913                         check_added_monitors!(node_b, 1);
4914                 } else {
4915                         check_added_monitors!(node_b, 0);
4916                 }
4917
4918                 let mut resp_2 = Vec::new();
4919                 for msg in reestablish_2 {
4920                         resp_2.push(node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap());
4921                 }
4922                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
4923                         check_added_monitors!(node_a, 1);
4924                 } else {
4925                         check_added_monitors!(node_a, 0);
4926                 }
4927
4928                 // We dont yet support both needing updates, as that would require a different commitment dance:
4929                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
4930                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
4931
4932                 for chan_msgs in resp_1.drain(..) {
4933                         if pre_all_htlcs {
4934                                 let a = node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
4935                                 let _announcement_sigs_opt = a.unwrap();
4936                                 //TODO: Test announcement_sigs re-sending when we've implemented it
4937                         } else {
4938                                 assert!(chan_msgs.0.is_none());
4939                         }
4940                         if pending_raa.0 {
4941                                 assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
4942                                 check_added_monitors!(node_a, 1);
4943                         } else {
4944                                 assert!(chan_msgs.1.is_none());
4945                         }
4946                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
4947                                 let commitment_update = chan_msgs.2.unwrap();
4948                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
4949                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
4950                                 } else {
4951                                         assert!(commitment_update.update_add_htlcs.is_empty());
4952                                 }
4953                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
4954                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
4955                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4956                                 for update_add in commitment_update.update_add_htlcs {
4957                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
4958                                 }
4959                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
4960                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
4961                                 }
4962                                 for update_fail in commitment_update.update_fail_htlcs {
4963                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
4964                                 }
4965
4966                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
4967                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
4968                                 } else {
4969                                         let (as_revoke_and_ack, as_commitment_signed) = node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4970                                         check_added_monitors!(node_a, 1);
4971                                         assert!(as_commitment_signed.is_none());
4972                                         assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
4973                                         check_added_monitors!(node_b, 1);
4974                                 }
4975                         } else {
4976                                 assert!(chan_msgs.2.is_none());
4977                         }
4978                 }
4979
4980                 for chan_msgs in resp_2.drain(..) {
4981                         if pre_all_htlcs {
4982                                 let _announcement_sigs_opt = node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
4983                                 //TODO: Test announcement_sigs re-sending when we've implemented it
4984                         } else {
4985                                 assert!(chan_msgs.0.is_none());
4986                         }
4987                         if pending_raa.1 {
4988                                 assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
4989                                 check_added_monitors!(node_b, 1);
4990                         } else {
4991                                 assert!(chan_msgs.1.is_none());
4992                         }
4993                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
4994                                 let commitment_update = chan_msgs.2.unwrap();
4995                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
4996                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
4997                                 }
4998                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
4999                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
5000                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
5001                                 for update_add in commitment_update.update_add_htlcs {
5002                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
5003                                 }
5004                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
5005                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
5006                                 }
5007                                 for update_fail in commitment_update.update_fail_htlcs {
5008                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
5009                                 }
5010
5011                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
5012                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
5013                                 } else {
5014                                         let (bs_revoke_and_ack, bs_commitment_signed) = node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
5015                                         check_added_monitors!(node_b, 1);
5016                                         assert!(bs_commitment_signed.is_none());
5017                                         assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
5018                                         check_added_monitors!(node_a, 1);
5019                                 }
5020                         } else {
5021                                 assert!(chan_msgs.2.is_none());
5022                         }
5023                 }
5024         }
5025
5026         #[test]
5027         fn test_simple_peer_disconnect() {
5028                 // Test that we can reconnect when there are no lost messages
5029                 let nodes = create_network(3);
5030                 create_announced_chan_between_nodes(&nodes, 0, 1);
5031                 create_announced_chan_between_nodes(&nodes, 1, 2);
5032
5033                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5034                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5035                 reconnect_nodes(&nodes[0], &nodes[1], true, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5036
5037                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
5038                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
5039                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
5040                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
5041
5042                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5043                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5044                 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5045
5046                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
5047                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
5048                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
5049                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
5050
5051                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5052                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5053
5054                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
5055                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
5056
5057                 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
5058                 {
5059                         let events = nodes[0].node.get_and_clear_pending_events();
5060                         assert_eq!(events.len(), 2);
5061                         match events[0] {
5062                                 Event::PaymentSent { payment_preimage } => {
5063                                         assert_eq!(payment_preimage, payment_preimage_3);
5064                                 },
5065                                 _ => panic!("Unexpected event"),
5066                         }
5067                         match events[1] {
5068                                 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
5069                                         assert_eq!(payment_hash, payment_hash_5);
5070                                         assert!(rejected_by_dest);
5071                                 },
5072                                 _ => panic!("Unexpected event"),
5073                         }
5074                 }
5075
5076                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
5077                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
5078         }
5079
5080         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
5081                 // Test that we can reconnect when in-flight HTLC updates get dropped
5082                 let mut nodes = create_network(2);
5083                 if messages_delivered == 0 {
5084                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
5085                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
5086                 } else {
5087                         create_announced_chan_between_nodes(&nodes, 0, 1);
5088                 }
5089
5090                 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();
5091                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
5092
5093                 let payment_event = {
5094                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
5095                         check_added_monitors!(nodes[0], 1);
5096
5097                         let mut events = nodes[0].node.get_and_clear_pending_events();
5098                         assert_eq!(events.len(), 1);
5099                         SendEvent::from_event(events.remove(0))
5100                 };
5101                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
5102
5103                 if messages_delivered < 2 {
5104                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
5105                 } else {
5106                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5107                         let (bs_revoke_and_ack, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
5108                         check_added_monitors!(nodes[1], 1);
5109
5110                         if messages_delivered >= 3 {
5111                                 assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
5112                                 check_added_monitors!(nodes[0], 1);
5113
5114                                 if messages_delivered >= 4 {
5115                                         let (as_revoke_and_ack, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed.unwrap()).unwrap();
5116                                         assert!(as_commitment_signed.is_none());
5117                                         check_added_monitors!(nodes[0], 1);
5118
5119                                         if messages_delivered >= 5 {
5120                                                 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
5121                                                 check_added_monitors!(nodes[1], 1);
5122                                         }
5123                                 }
5124                         }
5125                 }
5126
5127                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5128                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5129                 if messages_delivered < 2 {
5130                         // Even if the funding_locked messages get exchanged, as long as nothing further was
5131                         // received on either side, both sides will need to resend them.
5132                         reconnect_nodes(&nodes[0], &nodes[1], true, (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
5133                 } else if messages_delivered == 2 {
5134                         // nodes[0] still wants its RAA + commitment_signed
5135                         reconnect_nodes(&nodes[0], &nodes[1], false, (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
5136                 } else if messages_delivered == 3 {
5137                         // nodes[0] still wants its commitment_signed
5138                         reconnect_nodes(&nodes[0], &nodes[1], false, (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
5139                 } else if messages_delivered == 4 {
5140                         // nodes[1] still wants its final RAA
5141                         reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
5142                 } else if messages_delivered == 5 {
5143                         // Everything was delivered...
5144                         reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5145                 }
5146
5147                 let events_1 = nodes[1].node.get_and_clear_pending_events();
5148                 assert_eq!(events_1.len(), 1);
5149                 match events_1[0] {
5150                         Event::PendingHTLCsForwardable { .. } => { },
5151                         _ => panic!("Unexpected event"),
5152                 };
5153
5154                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5155                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5156                 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5157
5158                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
5159                 nodes[1].node.process_pending_htlc_forwards();
5160
5161                 let events_2 = nodes[1].node.get_and_clear_pending_events();
5162                 assert_eq!(events_2.len(), 1);
5163                 match events_2[0] {
5164                         Event::PaymentReceived { ref payment_hash, amt } => {
5165                                 assert_eq!(payment_hash_1, *payment_hash);
5166                                 assert_eq!(amt, 1000000);
5167                         },
5168                         _ => panic!("Unexpected event"),
5169                 }
5170
5171                 nodes[1].node.claim_funds(payment_preimage_1);
5172                 check_added_monitors!(nodes[1], 1);
5173
5174                 let events_3 = nodes[1].node.get_and_clear_pending_events();
5175                 assert_eq!(events_3.len(), 1);
5176                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
5177                         Event::UpdateHTLCs { ref node_id, ref updates } => {
5178                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
5179                                 assert!(updates.update_add_htlcs.is_empty());
5180                                 assert!(updates.update_fail_htlcs.is_empty());
5181                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5182                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5183                                 assert!(updates.update_fee.is_none());
5184                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
5185                         },
5186                         _ => panic!("Unexpected event"),
5187                 };
5188
5189                 if messages_delivered >= 1 {
5190                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
5191
5192                         let events_4 = nodes[0].node.get_and_clear_pending_events();
5193                         assert_eq!(events_4.len(), 1);
5194                         match events_4[0] {
5195                                 Event::PaymentSent { ref payment_preimage } => {
5196                                         assert_eq!(payment_preimage_1, *payment_preimage);
5197                                 },
5198                                 _ => panic!("Unexpected event"),
5199                         }
5200
5201                         if messages_delivered >= 2 {
5202                                 let (as_revoke_and_ack, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
5203                                 check_added_monitors!(nodes[0], 1);
5204
5205                                 if messages_delivered >= 3 {
5206                                         assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
5207                                         check_added_monitors!(nodes[1], 1);
5208
5209                                         if messages_delivered >= 4 {
5210                                                 let (bs_revoke_and_ack, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.unwrap()).unwrap();
5211                                                 assert!(bs_commitment_signed.is_none());
5212                                                 check_added_monitors!(nodes[1], 1);
5213
5214                                                 if messages_delivered >= 5 {
5215                                                         assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
5216                                                         check_added_monitors!(nodes[0], 1);
5217                                                 }
5218                                         }
5219                                 }
5220                         }
5221                 }
5222
5223                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5224                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5225                 if messages_delivered < 2 {
5226                         reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
5227                         //TODO: Deduplicate PaymentSent events, then enable this if:
5228                         //if messages_delivered < 1 {
5229                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
5230                                 assert_eq!(events_4.len(), 1);
5231                                 match events_4[0] {
5232                                         Event::PaymentSent { ref payment_preimage } => {
5233                                                 assert_eq!(payment_preimage_1, *payment_preimage);
5234                                         },
5235                                         _ => panic!("Unexpected event"),
5236                                 }
5237                         //}
5238                 } else if messages_delivered == 2 {
5239                         // nodes[0] still wants its RAA + commitment_signed
5240                         reconnect_nodes(&nodes[0], &nodes[1], false, (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
5241                 } else if messages_delivered == 3 {
5242                         // nodes[0] still wants its commitment_signed
5243                         reconnect_nodes(&nodes[0], &nodes[1], false, (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
5244                 } else if messages_delivered == 4 {
5245                         // nodes[1] still wants its final RAA
5246                         reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
5247                 } else if messages_delivered == 5 {
5248                         // Everything was delivered...
5249                         reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5250                 }
5251
5252                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5253                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5254                 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5255
5256                 // Channel should still work fine...
5257                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
5258                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
5259         }
5260
5261         #[test]
5262         fn test_drop_messages_peer_disconnect_a() {
5263                 do_test_drop_messages_peer_disconnect(0);
5264                 do_test_drop_messages_peer_disconnect(1);
5265                 do_test_drop_messages_peer_disconnect(2);
5266         }
5267
5268         #[test]
5269         fn test_drop_messages_peer_disconnect_b() {
5270                 do_test_drop_messages_peer_disconnect(3);
5271                 do_test_drop_messages_peer_disconnect(4);
5272                 do_test_drop_messages_peer_disconnect(5);
5273         }
5274
5275         #[test]
5276         fn test_funding_peer_disconnect() {
5277                 // Test that we can lock in our funding tx while disconnected
5278                 let nodes = create_network(2);
5279                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
5280
5281                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5282                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5283
5284                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
5285                 let events_1 = nodes[0].node.get_and_clear_pending_events();
5286                 assert_eq!(events_1.len(), 1);
5287                 match events_1[0] {
5288                         Event::SendFundingLocked { ref node_id, msg: _, ref announcement_sigs } => {
5289                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5290                                 assert!(announcement_sigs.is_none());
5291                         },
5292                         _ => panic!("Unexpected event"),
5293                 }
5294
5295                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
5296                 let events_2 = nodes[1].node.get_and_clear_pending_events();
5297                 assert_eq!(events_2.len(), 1);
5298                 match events_2[0] {
5299                         Event::SendFundingLocked { ref node_id, msg: _, ref announcement_sigs } => {
5300                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
5301                                 assert!(announcement_sigs.is_none());
5302                         },
5303                         _ => panic!("Unexpected event"),
5304                 }
5305
5306                 reconnect_nodes(&nodes[0], &nodes[1], true, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5307                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5308                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5309                 reconnect_nodes(&nodes[0], &nodes[1], true, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5310
5311                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
5312                 // rebroadcasting announcement_signatures upon reconnect.
5313
5314                 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();
5315                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
5316                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
5317         }
5318
5319         #[test]
5320         fn test_invalid_channel_announcement() {
5321                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
5322                 let secp_ctx = Secp256k1::new();
5323                 let nodes = create_network(2);
5324
5325                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
5326
5327                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
5328                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
5329                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
5330                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
5331
5332                 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 } );
5333
5334                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
5335                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
5336
5337                 let as_network_key = nodes[0].node.get_our_node_id();
5338                 let bs_network_key = nodes[1].node.get_our_node_id();
5339
5340                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
5341
5342                 let mut chan_announcement;
5343
5344                 macro_rules! dummy_unsigned_msg {
5345                         () => {
5346                                 msgs::UnsignedChannelAnnouncement {
5347                                         features: msgs::GlobalFeatures::new(),
5348                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
5349                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
5350                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
5351                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
5352                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
5353                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
5354                                         excess_data: Vec::new(),
5355                                 };
5356                         }
5357                 }
5358
5359                 macro_rules! sign_msg {
5360                         ($unsigned_msg: expr) => {
5361                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
5362                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
5363                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
5364                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
5365                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
5366                                 chan_announcement = msgs::ChannelAnnouncement {
5367                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
5368                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
5369                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
5370                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
5371                                         contents: $unsigned_msg
5372                                 }
5373                         }
5374                 }
5375
5376                 let unsigned_msg = dummy_unsigned_msg!();
5377                 sign_msg!(unsigned_msg);
5378                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
5379                 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 } );
5380
5381                 // Configured with Network::Testnet
5382                 let mut unsigned_msg = dummy_unsigned_msg!();
5383                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
5384                 sign_msg!(unsigned_msg);
5385                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
5386
5387                 let mut unsigned_msg = dummy_unsigned_msg!();
5388                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
5389                 sign_msg!(unsigned_msg);
5390                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
5391         }
5392 }