Merge pull request #393 from ariard/2019-11-send-cmt-error-handling
[rust-lightning] / src / ln / channelmanager.rs
1 //! The top-level channel management and payment tracking stuff lives here.
2 //!
3 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
4 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
5 //! upon reconnect to the relevant peer(s).
6 //!
7 //! It does not manage routing logic (see ln::router for that) nor does it manage constructing
8 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
9 //! imply it needs to fail HTLCs/payments/channels it manages).
10
11 use bitcoin::blockdata::block::BlockHeader;
12 use bitcoin::blockdata::transaction::Transaction;
13 use bitcoin::blockdata::constants::genesis_block;
14 use bitcoin::network::constants::Network;
15 use bitcoin::util::hash::BitcoinHash;
16
17 use bitcoin_hashes::{Hash, HashEngine};
18 use bitcoin_hashes::hmac::{Hmac, HmacEngine};
19 use bitcoin_hashes::sha256::Hash as Sha256;
20 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
21 use bitcoin_hashes::cmp::fixed_time_eq;
22
23 use secp256k1::key::{SecretKey,PublicKey};
24 use secp256k1::Secp256k1;
25 use secp256k1::ecdh::SharedSecret;
26 use secp256k1;
27
28 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
29 use chain::transaction::OutPoint;
30 use ln::channel::{Channel, ChannelError};
31 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
32 use ln::router::Route;
33 use ln::msgs;
34 use ln::msgs::LocalFeatures;
35 use ln::onion_utils;
36 use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
37 use chain::keysinterface::KeysInterface;
38 use util::config::UserConfig;
39 use util::{byte_utils, events};
40 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
41 use util::chacha20::ChaCha20;
42 use util::logger::Logger;
43 use util::errors::APIError;
44
45 use std::{cmp, mem};
46 use std::collections::{HashMap, hash_map, HashSet};
47 use std::io::Cursor;
48 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
49 use std::sync::atomic::{AtomicUsize, Ordering};
50 use std::time::Duration;
51
52 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
53 //
54 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
55 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
56 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
57 //
58 // When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
59 // which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
60 // filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
61 // the HTLC backwards along the relevant path).
62 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
63 // our payment, which we can use to decode errors or inform the user that the payment was sent.
64 /// Stores the info we will need to send when we want to forward an HTLC onwards
65 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
66 pub(super) struct PendingForwardHTLCInfo {
67         onion_packet: Option<msgs::OnionPacket>,
68         incoming_shared_secret: [u8; 32],
69         payment_hash: PaymentHash,
70         short_channel_id: u64,
71         pub(super) amt_to_forward: u64,
72         pub(super) outgoing_cltv_value: u32,
73 }
74
75 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
76 pub(super) enum HTLCFailureMsg {
77         Relay(msgs::UpdateFailHTLC),
78         Malformed(msgs::UpdateFailMalformedHTLC),
79 }
80
81 /// Stores whether we can't forward an HTLC or relevant forwarding info
82 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
83 pub(super) enum PendingHTLCStatus {
84         Forward(PendingForwardHTLCInfo),
85         Fail(HTLCFailureMsg),
86 }
87
88 /// Tracks the inbound corresponding to an outbound HTLC
89 #[derive(Clone, PartialEq)]
90 pub(super) struct HTLCPreviousHopData {
91         short_channel_id: u64,
92         htlc_id: u64,
93         incoming_packet_shared_secret: [u8; 32],
94 }
95
96 /// Tracks the inbound corresponding to an outbound HTLC
97 #[derive(Clone, PartialEq)]
98 pub(super) enum HTLCSource {
99         PreviousHopData(HTLCPreviousHopData),
100         OutboundRoute {
101                 route: Route,
102                 session_priv: SecretKey,
103                 /// Technically we can recalculate this from the route, but we cache it here to avoid
104                 /// doing a double-pass on route when we get a failure back
105                 first_hop_htlc_msat: u64,
106         },
107 }
108 #[cfg(test)]
109 impl HTLCSource {
110         pub fn dummy() -> Self {
111                 HTLCSource::OutboundRoute {
112                         route: Route { hops: Vec::new() },
113                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
114                         first_hop_htlc_msat: 0,
115                 }
116         }
117 }
118
119 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
120 pub(super) enum HTLCFailReason {
121         LightningError {
122                 err: msgs::OnionErrorPacket,
123         },
124         Reason {
125                 failure_code: u16,
126                 data: Vec<u8>,
127         }
128 }
129
130 /// payment_hash type, use to cross-lock hop
131 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
132 pub struct PaymentHash(pub [u8;32]);
133 /// payment_preimage type, use to route payment between hop
134 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
135 pub struct PaymentPreimage(pub [u8;32]);
136
137 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
138
139 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
140 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
141 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
142 /// channel_state lock. We then return the set of things that need to be done outside the lock in
143 /// this struct and call handle_error!() on it.
144
145 struct MsgHandleErrInternal {
146         err: msgs::LightningError,
147         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
148 }
149 impl MsgHandleErrInternal {
150         #[inline]
151         fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
152                 Self {
153                         err: LightningError {
154                                 err,
155                                 action: msgs::ErrorAction::SendErrorMessage {
156                                         msg: msgs::ErrorMessage {
157                                                 channel_id,
158                                                 data: err.to_string()
159                                         },
160                                 },
161                         },
162                         shutdown_finish: None,
163                 }
164         }
165         #[inline]
166         fn ignore_no_close(err: &'static str) -> Self {
167                 Self {
168                         err: LightningError {
169                                 err,
170                                 action: msgs::ErrorAction::IgnoreError,
171                         },
172                         shutdown_finish: None,
173                 }
174         }
175         #[inline]
176         fn from_no_close(err: msgs::LightningError) -> Self {
177                 Self { err, shutdown_finish: None }
178         }
179         #[inline]
180         fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
181                 Self {
182                         err: LightningError {
183                                 err,
184                                 action: msgs::ErrorAction::SendErrorMessage {
185                                         msg: msgs::ErrorMessage {
186                                                 channel_id,
187                                                 data: err.to_string()
188                                         },
189                                 },
190                         },
191                         shutdown_finish: Some((shutdown_res, channel_update)),
192                 }
193         }
194         #[inline]
195         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
196                 Self {
197                         err: match err {
198                                 ChannelError::Ignore(msg) => LightningError {
199                                         err: msg,
200                                         action: msgs::ErrorAction::IgnoreError,
201                                 },
202                                 ChannelError::Close(msg) => LightningError {
203                                         err: msg,
204                                         action: msgs::ErrorAction::SendErrorMessage {
205                                                 msg: msgs::ErrorMessage {
206                                                         channel_id,
207                                                         data: msg.to_string()
208                                                 },
209                                         },
210                                 },
211                                 ChannelError::CloseDelayBroadcast { msg, .. } => LightningError {
212                                         err: msg,
213                                         action: msgs::ErrorAction::SendErrorMessage {
214                                                 msg: msgs::ErrorMessage {
215                                                         channel_id,
216                                                         data: msg.to_string()
217                                                 },
218                                         },
219                                 },
220                         },
221                         shutdown_finish: None,
222                 }
223         }
224 }
225
226 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
227 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
228 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
229 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
230 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
231
232 pub(super) enum HTLCForwardInfo {
233         AddHTLC {
234                 prev_short_channel_id: u64,
235                 prev_htlc_id: u64,
236                 forward_info: PendingForwardHTLCInfo,
237         },
238         FailHTLC {
239                 htlc_id: u64,
240                 err_packet: msgs::OnionErrorPacket,
241         },
242 }
243
244 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
245 /// be sent in the order they appear in the return value, however sometimes the order needs to be
246 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
247 /// they were originally sent). In those cases, this enum is also returned.
248 #[derive(Clone, PartialEq)]
249 pub(super) enum RAACommitmentOrder {
250         /// Send the CommitmentUpdate messages first
251         CommitmentFirst,
252         /// Send the RevokeAndACK message first
253         RevokeAndACKFirst,
254 }
255
256 // Note this is only exposed in cfg(test):
257 pub(super) struct ChannelHolder {
258         pub(super) by_id: HashMap<[u8; 32], Channel>,
259         pub(super) short_to_id: HashMap<u64, [u8; 32]>,
260         /// short channel id -> forward infos. Key of 0 means payments received
261         /// Note that while this is held in the same mutex as the channels themselves, no consistency
262         /// guarantees are made about the existence of a channel with the short id here, nor the short
263         /// ids in the PendingForwardHTLCInfo!
264         pub(super) forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
265         /// payment_hash -> Vec<(amount_received, htlc_source)> for tracking things that were to us and
266         /// can be failed/claimed by the user
267         /// Note that while this is held in the same mutex as the channels themselves, no consistency
268         /// guarantees are made about the channels given here actually existing anymore by the time you
269         /// go to read them!
270         pub(super) claimable_htlcs: HashMap<PaymentHash, Vec<(u64, HTLCPreviousHopData)>>,
271         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
272         /// for broadcast messages, where ordering isn't as strict).
273         pub(super) pending_msg_events: Vec<events::MessageSendEvent>,
274 }
275 pub(super) struct MutChannelHolder<'a> {
276         pub(super) by_id: &'a mut HashMap<[u8; 32], Channel>,
277         pub(super) short_to_id: &'a mut HashMap<u64, [u8; 32]>,
278         pub(super) forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
279         pub(super) claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<(u64, HTLCPreviousHopData)>>,
280         pub(super) pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
281 }
282 impl ChannelHolder {
283         pub(super) fn borrow_parts(&mut self) -> MutChannelHolder {
284                 MutChannelHolder {
285                         by_id: &mut self.by_id,
286                         short_to_id: &mut self.short_to_id,
287                         forward_htlcs: &mut self.forward_htlcs,
288                         claimable_htlcs: &mut self.claimable_htlcs,
289                         pending_msg_events: &mut self.pending_msg_events,
290                 }
291         }
292 }
293
294 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
295 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
296
297 /// Manager which keeps track of a number of channels and sends messages to the appropriate
298 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
299 ///
300 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
301 /// to individual Channels.
302 ///
303 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
304 /// all peers during write/read (though does not modify this instance, only the instance being
305 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
306 /// called funding_transaction_generated for outbound channels).
307 ///
308 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
309 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
310 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
311 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
312 /// the serialization process). If the deserialized version is out-of-date compared to the
313 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
314 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
315 ///
316 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
317 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
318 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
319 /// block_connected() to step towards your best block) upon deserialization before using the
320 /// object!
321 pub struct ChannelManager {
322         default_configuration: UserConfig,
323         genesis_hash: Sha256dHash,
324         fee_estimator: Arc<FeeEstimator>,
325         monitor: Arc<ManyChannelMonitor>,
326         chain_monitor: Arc<ChainWatchInterface>,
327         tx_broadcaster: Arc<BroadcasterInterface>,
328
329         #[cfg(test)]
330         pub(super) latest_block_height: AtomicUsize,
331         #[cfg(not(test))]
332         latest_block_height: AtomicUsize,
333         last_block_hash: Mutex<Sha256dHash>,
334         secp_ctx: Secp256k1<secp256k1::All>,
335
336         #[cfg(test)]
337         pub(super) channel_state: Mutex<ChannelHolder>,
338         #[cfg(not(test))]
339         channel_state: Mutex<ChannelHolder>,
340         our_network_key: SecretKey,
341
342         pending_events: Mutex<Vec<events::Event>>,
343         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
344         /// Essentially just when we're serializing ourselves out.
345         /// Taken first everywhere where we are making changes before any other locks.
346         total_consistency_lock: RwLock<()>,
347
348         keys_manager: Arc<KeysInterface>,
349
350         logger: Arc<Logger>,
351 }
352
353 /// The amount of time we require our counterparty wait to claim their money (ie time between when
354 /// we, or our watchtower, must check for them having broadcast a theft transaction).
355 pub(crate) const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
356 /// The amount of time we're willing to wait to claim money back to us
357 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 6 * 24 * 7;
358
359 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
360 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
361 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
362 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
363 /// CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
364 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
365 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
366
367 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
368 // ie that if the next-hop peer fails the HTLC within
369 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
370 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
371 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
372 // LATENCY_GRACE_PERIOD_BLOCKS.
373 #[deny(const_err)]
374 #[allow(dead_code)]
375 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - CLTV_CLAIM_BUFFER - ANTI_REORG_DELAY - LATENCY_GRACE_PERIOD_BLOCKS;
376
377 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
378 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
379 #[deny(const_err)]
380 #[allow(dead_code)]
381 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
382
383 macro_rules! secp_call {
384         ( $res: expr, $err: expr ) => {
385                 match $res {
386                         Ok(key) => key,
387                         Err(_) => return Err($err),
388                 }
389         };
390 }
391
392 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
393 pub struct ChannelDetails {
394         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
395         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
396         /// Note that this means this value is *not* persistent - it can change once during the
397         /// lifetime of the channel.
398         pub channel_id: [u8; 32],
399         /// The position of the funding transaction in the chain. None if the funding transaction has
400         /// not yet been confirmed and the channel fully opened.
401         pub short_channel_id: Option<u64>,
402         /// The node_id of our counterparty
403         pub remote_network_id: PublicKey,
404         /// The value, in satoshis, of this channel as appears in the funding output
405         pub channel_value_satoshis: u64,
406         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
407         pub user_id: u64,
408         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
409         /// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
410         /// available for inclusion in new outbound HTLCs). This further does not include any pending
411         /// outgoing HTLCs which are awaiting some other resolution to be sent.
412         pub outbound_capacity_msat: u64,
413         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
414         /// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
415         /// available for inclusion in new inbound HTLCs).
416         /// Note that there are some corner cases not fully handled here, so the actual available
417         /// inbound capacity may be slightly higher than this.
418         pub inbound_capacity_msat: u64,
419         /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
420         /// the peer is connected, and (c) no monitor update failure is pending resolution.
421         pub is_live: bool,
422 }
423
424 macro_rules! handle_error {
425         ($self: ident, $internal: expr) => {
426                 match $internal {
427                         Ok(msg) => Ok(msg),
428                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
429                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
430                                         $self.finish_force_close_channel(shutdown_res);
431                                         if let Some(update) = update_option {
432                                                 let mut channel_state = $self.channel_state.lock().unwrap();
433                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
434                                                         msg: update
435                                                 });
436                                         }
437                                 }
438                                 Err(err)
439                         },
440                 }
441         }
442 }
443
444 macro_rules! break_chan_entry {
445         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
446                 match $res {
447                         Ok(res) => res,
448                         Err(ChannelError::Ignore(msg)) => {
449                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
450                         },
451                         Err(ChannelError::Close(msg)) => {
452                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
453                                 let (channel_id, mut chan) = $entry.remove_entry();
454                                 if let Some(short_id) = chan.get_short_channel_id() {
455                                         $channel_state.short_to_id.remove(&short_id);
456                                 }
457                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
458                         },
459                         Err(ChannelError::CloseDelayBroadcast { .. }) => { panic!("Wait is only generated on receipt of channel_reestablish, which is handled by try_chan_entry, we don't bother to support it here"); }
460                 }
461         }
462 }
463
464 macro_rules! try_chan_entry {
465         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
466                 match $res {
467                         Ok(res) => res,
468                         Err(ChannelError::Ignore(msg)) => {
469                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
470                         },
471                         Err(ChannelError::Close(msg)) => {
472                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
473                                 let (channel_id, mut chan) = $entry.remove_entry();
474                                 if let Some(short_id) = chan.get_short_channel_id() {
475                                         $channel_state.short_to_id.remove(&short_id);
476                                 }
477                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
478                         },
479                         Err(ChannelError::CloseDelayBroadcast { msg, update }) => {
480                                 log_error!($self, "Channel {} need to be shutdown but closing transactions not broadcast due to {}", log_bytes!($entry.key()[..]), msg);
481                                 let (channel_id, mut chan) = $entry.remove_entry();
482                                 if let Some(short_id) = chan.get_short_channel_id() {
483                                         $channel_state.short_to_id.remove(&short_id);
484                                 }
485                                 if let Some(update) = update {
486                                         if let Err(e) = $self.monitor.add_update_monitor(update.get_funding_txo().unwrap(), update) {
487                                                 match e {
488                                                         // Upstream channel is dead, but we want at least to fail backward HTLCs to save
489                                                         // downstream channels. In case of PermanentFailure, we are not going to be able
490                                                         // to claim back to_remote output on remote commitment transaction. Doesn't
491                                                         // make a difference here, we are concern about HTLCs circuit, not onchain funds.
492                                                         ChannelMonitorUpdateErr::PermanentFailure => {},
493                                                         ChannelMonitorUpdateErr::TemporaryFailure => {},
494                                                 }
495                                         }
496                                 }
497                                 let mut shutdown_res = chan.force_shutdown();
498                                 if shutdown_res.0.len() >= 1 {
499                                         log_error!($self, "You have a toxic local commitment transaction {} avaible in channel monitor, read comment in ChannelMonitor::get_latest_local_commitment_txn to be informed of manual action to take", shutdown_res.0[0].txid());
500                                 }
501                                 shutdown_res.0.clear();
502                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, shutdown_res, $self.get_channel_update(&chan).ok()))
503                         }
504                 }
505         }
506 }
507
508 macro_rules! handle_monitor_err {
509         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
510                 handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, Vec::new(), Vec::new())
511         };
512         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
513                 match $err {
514                         ChannelMonitorUpdateErr::PermanentFailure => {
515                                 log_error!($self, "Closing channel {} due to monitor update PermanentFailure", log_bytes!($entry.key()[..]));
516                                 let (channel_id, mut chan) = $entry.remove_entry();
517                                 if let Some(short_id) = chan.get_short_channel_id() {
518                                         $channel_state.short_to_id.remove(&short_id);
519                                 }
520                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
521                                 // chain in a confused state! We need to move them into the ChannelMonitor which
522                                 // will be responsible for failing backwards once things confirm on-chain.
523                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
524                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
525                                 // us bother trying to claim it just to forward on to another peer. If we're
526                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
527                                 // given up the preimage yet, so might as well just wait until the payment is
528                                 // retried, avoiding the on-chain fees.
529                                 let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()));
530                                 res
531                         },
532                         ChannelMonitorUpdateErr::TemporaryFailure => {
533                                 log_info!($self, "Disabling channel {} due to monitor update TemporaryFailure. On restore will send {} and process {} forwards and {} fails",
534                                                 log_bytes!($entry.key()[..]),
535                                                 if $resend_commitment && $resend_raa {
536                                                                 match $action_type {
537                                                                         RAACommitmentOrder::CommitmentFirst => { "commitment then RAA" },
538                                                                         RAACommitmentOrder::RevokeAndACKFirst => { "RAA then commitment" },
539                                                                 }
540                                                         } else if $resend_commitment { "commitment" }
541                                                         else if $resend_raa { "RAA" }
542                                                         else { "nothing" },
543                                                 (&$failed_forwards as &Vec<(PendingForwardHTLCInfo, u64)>).len(),
544                                                 (&$failed_fails as &Vec<(HTLCSource, PaymentHash, HTLCFailReason)>).len());
545                                 if !$resend_commitment {
546                                         debug_assert!($action_type == RAACommitmentOrder::RevokeAndACKFirst || !$resend_raa);
547                                 }
548                                 if !$resend_raa {
549                                         debug_assert!($action_type == RAACommitmentOrder::CommitmentFirst || !$resend_commitment);
550                                 }
551                                 $entry.get_mut().monitor_update_failed($resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
552                                 Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()))
553                         },
554                 }
555         }
556 }
557
558 macro_rules! return_monitor_err {
559         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
560                 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment);
561         };
562         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
563                 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
564         }
565 }
566
567 // Does not break in case of TemporaryFailure!
568 macro_rules! maybe_break_monitor_err {
569         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
570                 match (handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment), $err) {
571                         (e, ChannelMonitorUpdateErr::PermanentFailure) => {
572                                 break e;
573                         },
574                         (_, ChannelMonitorUpdateErr::TemporaryFailure) => { },
575                 }
576         }
577 }
578
579 impl ChannelManager {
580         /// Constructs a new ChannelManager to hold several channels and route between them.
581         ///
582         /// This is the main "logic hub" for all channel-related actions, and implements
583         /// ChannelMessageHandler.
584         ///
585         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
586         ///
587         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
588         ///
589         /// User must provide the current blockchain height from which to track onchain channel
590         /// funding outpoints and send payments with reliable timelocks.
591         pub fn new(network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>,keys_manager: Arc<KeysInterface>, config: UserConfig, current_blockchain_height: usize) -> Result<Arc<ChannelManager>, secp256k1::Error> {
592                 let secp_ctx = Secp256k1::new();
593
594                 let res = Arc::new(ChannelManager {
595                         default_configuration: config.clone(),
596                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
597                         fee_estimator: feeest.clone(),
598                         monitor: monitor.clone(),
599                         chain_monitor,
600                         tx_broadcaster,
601
602                         latest_block_height: AtomicUsize::new(current_blockchain_height),
603                         last_block_hash: Mutex::new(Default::default()),
604                         secp_ctx,
605
606                         channel_state: Mutex::new(ChannelHolder{
607                                 by_id: HashMap::new(),
608                                 short_to_id: HashMap::new(),
609                                 forward_htlcs: HashMap::new(),
610                                 claimable_htlcs: HashMap::new(),
611                                 pending_msg_events: Vec::new(),
612                         }),
613                         our_network_key: keys_manager.get_node_secret(),
614
615                         pending_events: Mutex::new(Vec::new()),
616                         total_consistency_lock: RwLock::new(()),
617
618                         keys_manager,
619
620                         logger,
621                 });
622                 let weak_res = Arc::downgrade(&res);
623                 res.chain_monitor.register_listener(weak_res);
624                 Ok(res)
625         }
626
627         /// Creates a new outbound channel to the given remote node and with the given value.
628         ///
629         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
630         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
631         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
632         /// may wish to avoid using 0 for user_id here.
633         ///
634         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
635         /// PeerManager::process_events afterwards.
636         ///
637         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
638         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
639         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
640                 if channel_value_satoshis < 1000 {
641                         return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
642                 }
643
644                 let channel = Channel::new_outbound(&*self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, Arc::clone(&self.logger), &self.default_configuration)?;
645                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
646
647                 let _ = self.total_consistency_lock.read().unwrap();
648                 let mut channel_state = self.channel_state.lock().unwrap();
649                 match channel_state.by_id.entry(channel.channel_id()) {
650                         hash_map::Entry::Occupied(_) => {
651                                 if cfg!(feature = "fuzztarget") {
652                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
653                                 } else {
654                                         panic!("RNG is bad???");
655                                 }
656                         },
657                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
658                 }
659                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
660                         node_id: their_network_key,
661                         msg: res,
662                 });
663                 Ok(())
664         }
665
666         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
667         /// more information.
668         pub fn list_channels(&self) -> Vec<ChannelDetails> {
669                 let channel_state = self.channel_state.lock().unwrap();
670                 let mut res = Vec::with_capacity(channel_state.by_id.len());
671                 for (channel_id, channel) in channel_state.by_id.iter() {
672                         let (inbound_capacity_msat, outbound_capacity_msat) = channel.get_inbound_outbound_available_balance_msat();
673                         res.push(ChannelDetails {
674                                 channel_id: (*channel_id).clone(),
675                                 short_channel_id: channel.get_short_channel_id(),
676                                 remote_network_id: channel.get_their_node_id(),
677                                 channel_value_satoshis: channel.get_value_satoshis(),
678                                 inbound_capacity_msat,
679                                 outbound_capacity_msat,
680                                 user_id: channel.get_user_id(),
681                                 is_live: channel.is_live(),
682                         });
683                 }
684                 res
685         }
686
687         /// Gets the list of usable channels, in random order. Useful as an argument to
688         /// Router::get_route to ensure non-announced channels are used.
689         ///
690         /// These are guaranteed to have their is_live value set to true, see the documentation for
691         /// ChannelDetails::is_live for more info on exactly what the criteria are.
692         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
693                 let channel_state = self.channel_state.lock().unwrap();
694                 let mut res = Vec::with_capacity(channel_state.by_id.len());
695                 for (channel_id, channel) in channel_state.by_id.iter() {
696                         // Note we use is_live here instead of usable which leads to somewhat confused
697                         // internal/external nomenclature, but that's ok cause that's probably what the user
698                         // really wanted anyway.
699                         if channel.is_live() {
700                                 let (inbound_capacity_msat, outbound_capacity_msat) = channel.get_inbound_outbound_available_balance_msat();
701                                 res.push(ChannelDetails {
702                                         channel_id: (*channel_id).clone(),
703                                         short_channel_id: channel.get_short_channel_id(),
704                                         remote_network_id: channel.get_their_node_id(),
705                                         channel_value_satoshis: channel.get_value_satoshis(),
706                                         inbound_capacity_msat,
707                                         outbound_capacity_msat,
708                                         user_id: channel.get_user_id(),
709                                         is_live: true,
710                                 });
711                         }
712                 }
713                 res
714         }
715
716         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
717         /// will be accepted on the given channel, and after additional timeout/the closing of all
718         /// pending HTLCs, the channel will be closed on chain.
719         ///
720         /// May generate a SendShutdown message event on success, which should be relayed.
721         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
722                 let _ = self.total_consistency_lock.read().unwrap();
723
724                 let (mut failed_htlcs, chan_option) = {
725                         let mut channel_state_lock = self.channel_state.lock().unwrap();
726                         let channel_state = channel_state_lock.borrow_parts();
727                         match channel_state.by_id.entry(channel_id.clone()) {
728                                 hash_map::Entry::Occupied(mut chan_entry) => {
729                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
730                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
731                                                 node_id: chan_entry.get().get_their_node_id(),
732                                                 msg: shutdown_msg
733                                         });
734                                         if chan_entry.get().is_shutdown() {
735                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
736                                                         channel_state.short_to_id.remove(&short_id);
737                                                 }
738                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
739                                         } else { (failed_htlcs, None) }
740                                 },
741                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
742                         }
743                 };
744                 for htlc_source in failed_htlcs.drain(..) {
745                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
746                 }
747                 let chan_update = if let Some(chan) = chan_option {
748                         if let Ok(update) = self.get_channel_update(&chan) {
749                                 Some(update)
750                         } else { None }
751                 } else { None };
752
753                 if let Some(update) = chan_update {
754                         let mut channel_state = self.channel_state.lock().unwrap();
755                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
756                                 msg: update
757                         });
758                 }
759
760                 Ok(())
761         }
762
763         #[inline]
764         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
765                 let (local_txn, mut failed_htlcs) = shutdown_res;
766                 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
767                 for htlc_source in failed_htlcs.drain(..) {
768                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
769                 }
770                 for tx in local_txn {
771                         self.tx_broadcaster.broadcast_transaction(&tx);
772                 }
773         }
774
775         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
776         /// the chain and rejecting new HTLCs on the given channel.
777         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
778                 let _ = self.total_consistency_lock.read().unwrap();
779
780                 let mut chan = {
781                         let mut channel_state_lock = self.channel_state.lock().unwrap();
782                         let channel_state = channel_state_lock.borrow_parts();
783                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
784                                 if let Some(short_id) = chan.get_short_channel_id() {
785                                         channel_state.short_to_id.remove(&short_id);
786                                 }
787                                 chan
788                         } else {
789                                 return;
790                         }
791                 };
792                 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
793                 self.finish_force_close_channel(chan.force_shutdown());
794                 if let Ok(update) = self.get_channel_update(&chan) {
795                         let mut channel_state = self.channel_state.lock().unwrap();
796                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
797                                 msg: update
798                         });
799                 }
800         }
801
802         /// Force close all channels, immediately broadcasting the latest local commitment transaction
803         /// for each to the chain and rejecting new HTLCs on each.
804         pub fn force_close_all_channels(&self) {
805                 for chan in self.list_channels() {
806                         self.force_close_channel(&chan.channel_id);
807                 }
808         }
809
810         const ZERO:[u8; 65] = [0; 65];
811         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
812                 macro_rules! return_malformed_err {
813                         ($msg: expr, $err_code: expr) => {
814                                 {
815                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
816                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
817                                                 channel_id: msg.channel_id,
818                                                 htlc_id: msg.htlc_id,
819                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
820                                                 failure_code: $err_code,
821                                         })), self.channel_state.lock().unwrap());
822                                 }
823                         }
824                 }
825
826                 if let Err(_) = msg.onion_routing_packet.public_key {
827                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
828                 }
829
830                 let shared_secret = {
831                         let mut arr = [0; 32];
832                         arr.copy_from_slice(&SharedSecret::new(&msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
833                         arr
834                 };
835                 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(&shared_secret);
836
837                 if msg.onion_routing_packet.version != 0 {
838                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
839                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
840                         //the hash doesn't really serve any purpose - in the case of hashing all data, the
841                         //receiving node would have to brute force to figure out which version was put in the
842                         //packet by the node that send us the message, in the case of hashing the hop_data, the
843                         //node knows the HMAC matched, so they already know what is there...
844                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
845                 }
846
847                 let mut hmac = HmacEngine::<Sha256>::new(&mu);
848                 hmac.input(&msg.onion_routing_packet.hop_data);
849                 hmac.input(&msg.payment_hash.0[..]);
850                 if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
851                         return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
852                 }
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: onion_utils::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
866                                         })), channel_state.unwrap());
867                                 }
868                         }
869                 }
870
871                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
872                 let next_hop_data = {
873                         let mut decoded = [0; 65];
874                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
875                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
876                                 Err(err) => {
877                                         let error_code = match err {
878                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
879                                                 _ => 0x2000 | 2, // Should never happen
880                                         };
881                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
882                                 },
883                                 Ok(msg) => msg
884                         }
885                 };
886
887                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
888                                 // OUR PAYMENT!
889                                 // final_expiry_too_soon
890                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
891                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
892                                 }
893                                 // final_incorrect_htlc_amount
894                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
895                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
896                                 }
897                                 // final_incorrect_cltv_expiry
898                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
899                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
900                                 }
901
902                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
903                                 // message, however that would leak that we are the recipient of this payment, so
904                                 // instead we stay symmetric with the forwarding case, only responding (after a
905                                 // delay) once they've send us a commitment_signed!
906
907                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
908                                         onion_packet: None,
909                                         payment_hash: msg.payment_hash.clone(),
910                                         short_channel_id: 0,
911                                         incoming_shared_secret: shared_secret,
912                                         amt_to_forward: next_hop_data.data.amt_to_forward,
913                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
914                                 })
915                         } else {
916                                 let mut new_packet_data = [0; 20*65];
917                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
918                                 chacha.process(&ChannelManager::ZERO[..], &mut new_packet_data[19*65..]);
919
920                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
921
922                                 let blinding_factor = {
923                                         let mut sha = Sha256::engine();
924                                         sha.input(&new_pubkey.serialize()[..]);
925                                         sha.input(&shared_secret);
926                                         Sha256::from_engine(sha).into_inner()
927                                 };
928
929                                 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor[..]) {
930                                         Err(e)
931                                 } else { Ok(new_pubkey) };
932
933                                 let outgoing_packet = msgs::OnionPacket {
934                                         version: 0,
935                                         public_key,
936                                         hop_data: new_packet_data,
937                                         hmac: next_hop_data.hmac.clone(),
938                                 };
939
940                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
941                                         onion_packet: Some(outgoing_packet),
942                                         payment_hash: msg.payment_hash.clone(),
943                                         short_channel_id: next_hop_data.data.short_channel_id,
944                                         incoming_shared_secret: shared_secret,
945                                         amt_to_forward: next_hop_data.data.amt_to_forward,
946                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
947                                 })
948                         };
949
950                 channel_state = Some(self.channel_state.lock().unwrap());
951                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
952                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
953                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
954                                 let forwarding_id = match id_option {
955                                         None => { // unknown_next_peer
956                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
957                                         },
958                                         Some(id) => id.clone(),
959                                 };
960                                 if let Some((err, code, chan_update)) = loop {
961                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
962
963                                         // Note that we could technically not return an error yet here and just hope
964                                         // that the connection is reestablished or monitor updated by the time we get
965                                         // around to doing the actual forward, but better to fail early if we can and
966                                         // hopefully an attacker trying to path-trace payments cannot make this occur
967                                         // on a small/per-node/per-channel scale.
968                                         if !chan.is_live() { // channel_disabled
969                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
970                                         }
971                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
972                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
973                                         }
974                                         let fee = amt_to_forward.checked_mul(chan.get_fee_proportional_millionths() as u64).and_then(|prop_fee| { (prop_fee / 1000000).checked_add(chan.get_our_fee_base_msat(&*self.fee_estimator) as u64) });
975                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
976                                                 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())));
977                                         }
978                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
979                                                 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())));
980                                         }
981                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
982                                         // We want to have at least LATENCY_GRACE_PERIOD_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
983                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS as u32 { // expiry_too_soon
984                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
985                                         }
986                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
987                                                 break Some(("CLTV expiry is too far in the future", 21, None));
988                                         }
989                                         break None;
990                                 }
991                                 {
992                                         let mut res = Vec::with_capacity(8 + 128);
993                                         if let Some(chan_update) = chan_update {
994                                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
995                                                         res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
996                                                 }
997                                                 else if code == 0x1000 | 13 {
998                                                         res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
999                                                 }
1000                                                 else if code == 0x1000 | 20 {
1001                                                         res.extend_from_slice(&byte_utils::be16_to_array(chan_update.contents.flags));
1002                                                 }
1003                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1004                                         }
1005                                         return_err!(err, code, &res[..]);
1006                                 }
1007                         }
1008                 }
1009
1010                 (pending_forward_info, channel_state.unwrap())
1011         }
1012
1013         /// only fails if the channel does not yet have an assigned short_id
1014         /// May be called with channel_state already locked!
1015         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, LightningError> {
1016                 let short_channel_id = match chan.get_short_channel_id() {
1017                         None => return Err(LightningError{err: "Channel not yet established", action: msgs::ErrorAction::IgnoreError}),
1018                         Some(id) => id,
1019                 };
1020
1021                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1022
1023                 let unsigned = msgs::UnsignedChannelUpdate {
1024                         chain_hash: self.genesis_hash,
1025                         short_channel_id: short_channel_id,
1026                         timestamp: chan.get_channel_update_count(),
1027                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1028                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1029                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1030                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1031                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1032                         excess_data: Vec::new(),
1033                 };
1034
1035                 let msg_hash = Sha256dHash::hash(&unsigned.encode()[..]);
1036                 let sig = self.secp_ctx.sign(&hash_to_message!(&msg_hash[..]), &self.our_network_key);
1037
1038                 Ok(msgs::ChannelUpdate {
1039                         signature: sig,
1040                         contents: unsigned
1041                 })
1042         }
1043
1044         /// Sends a payment along a given route.
1045         ///
1046         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1047         /// fields for more info.
1048         ///
1049         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1050         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1051         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1052         /// specified in the last hop in the route! Thus, you should probably do your own
1053         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1054         /// payment") and prevent double-sends yourself.
1055         ///
1056         /// May generate a SendHTLCs message event on success, which should be relayed.
1057         ///
1058         /// Raises APIError::RoutError when invalid route or forward parameter
1059         /// (cltv_delta, fee, node public key) is specified.
1060         /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1061         /// (including due to previous monitor update failure or new permanent monitor update failure).
1062         /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1063         /// relevant updates.
1064         ///
1065         /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1066         /// and you may wish to retry via a different route immediately.
1067         /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1068         /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1069         /// the payment via a different route unless you intend to pay twice!
1070         pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1071                 if route.hops.len() < 1 || route.hops.len() > 20 {
1072                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1073                 }
1074                 let our_node_id = self.get_our_node_id();
1075                 for (idx, hop) in route.hops.iter().enumerate() {
1076                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1077                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1078                         }
1079                 }
1080
1081                 let session_priv = self.keys_manager.get_session_key();
1082
1083                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1084
1085                 let onion_keys = secp_call!(onion_utils::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1086                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1087                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height)?;
1088                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1089
1090                 let _ = self.total_consistency_lock.read().unwrap();
1091
1092                 let err: Result<(), _> = loop {
1093                         let mut channel_lock = self.channel_state.lock().unwrap();
1094
1095                         let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1096                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1097                                 Some(id) => id.clone(),
1098                         };
1099
1100                         let channel_state = channel_lock.borrow_parts();
1101                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1102                                 match {
1103                                         if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1104                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1105                                         }
1106                                         if !chan.get().is_live() {
1107                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1108                                         }
1109                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1110                                                 route: route.clone(),
1111                                                 session_priv: session_priv.clone(),
1112                                                 first_hop_htlc_msat: htlc_msat,
1113                                         }, onion_packet), channel_state, chan)
1114                                 } {
1115                                         Some((update_add, commitment_signed, chan_monitor)) => {
1116                                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1117                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true);
1118                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1119                                                         // that we will resent the commitment update once we unfree monitor
1120                                                         // updating, so we have to take special care that we don't return
1121                                                         // something else in case we will resend later!
1122                                                         return Err(APIError::MonitorUpdateFailed);
1123                                                 }
1124
1125                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1126                                                         node_id: route.hops.first().unwrap().pubkey,
1127                                                         updates: msgs::CommitmentUpdate {
1128                                                                 update_add_htlcs: vec![update_add],
1129                                                                 update_fulfill_htlcs: Vec::new(),
1130                                                                 update_fail_htlcs: Vec::new(),
1131                                                                 update_fail_malformed_htlcs: Vec::new(),
1132                                                                 update_fee: None,
1133                                                                 commitment_signed,
1134                                                         },
1135                                                 });
1136                                         },
1137                                         None => {},
1138                                 }
1139                         } else { unreachable!(); }
1140                         return Ok(());
1141                 };
1142
1143                 match handle_error!(self, err) {
1144                         Ok(_) => unreachable!(),
1145                         Err(e) => {
1146                                 if let msgs::ErrorAction::IgnoreError = e.action {
1147                                 } else {
1148                                         log_error!(self, "Got bad keys: {}!", e.err);
1149                                         let mut channel_state = self.channel_state.lock().unwrap();
1150                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1151                                                 node_id: route.hops.first().unwrap().pubkey,
1152                                                 action: e.action,
1153                                         });
1154                                 }
1155                                 Err(APIError::ChannelUnavailable { err: e.err })
1156                         },
1157                 }
1158         }
1159
1160         /// Call this upon creation of a funding transaction for the given channel.
1161         ///
1162         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1163         /// or your counterparty can steal your funds!
1164         ///
1165         /// Panics if a funding transaction has already been provided for this channel.
1166         ///
1167         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1168         /// be trivially prevented by using unique funding transaction keys per-channel).
1169         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1170                 let _ = self.total_consistency_lock.read().unwrap();
1171
1172                 let (mut chan, msg, chan_monitor) = {
1173                         let (res, chan) = {
1174                                 let mut channel_state = self.channel_state.lock().unwrap();
1175                                 match channel_state.by_id.remove(temporary_channel_id) {
1176                                         Some(mut chan) => {
1177                                                 (chan.get_outbound_funding_created(funding_txo)
1178                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
1179                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1180                                                         } else { unreachable!(); })
1181                                                 , chan)
1182                                         },
1183                                         None => return
1184                                 }
1185                         };
1186                         match handle_error!(self, res) {
1187                                 Ok(funding_msg) => {
1188                                         (chan, funding_msg.0, funding_msg.1)
1189                                 },
1190                                 Err(e) => {
1191                                         log_error!(self, "Got bad signatures: {}!", e.err);
1192                                         let mut channel_state = self.channel_state.lock().unwrap();
1193                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1194                                                 node_id: chan.get_their_node_id(),
1195                                                 action: e.action,
1196                                         });
1197                                         return;
1198                                 },
1199                         }
1200                 };
1201                 // Because we have exclusive ownership of the channel here we can release the channel_state
1202                 // lock before add_update_monitor
1203                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1204                         match e {
1205                                 ChannelMonitorUpdateErr::PermanentFailure => {
1206                                         match handle_error!(self, Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", *temporary_channel_id, chan.force_shutdown(), None))) {
1207                                                 Err(e) => {
1208                                                         log_error!(self, "Failed to store ChannelMonitor update for funding tx generation");
1209                                                         let mut channel_state = self.channel_state.lock().unwrap();
1210                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1211                                                                 node_id: chan.get_their_node_id(),
1212                                                                 action: e.action,
1213                                                         });
1214                                                         return;
1215                                                 },
1216                                                 Ok(()) => unreachable!(),
1217                                         }
1218                                 },
1219                                 ChannelMonitorUpdateErr::TemporaryFailure => {
1220                                         // Its completely fine to continue with a FundingCreated until the monitor
1221                                         // update is persisted, as long as we don't generate the FundingBroadcastSafe
1222                                         // until the monitor has been safely persisted (as funding broadcast is not,
1223                                         // in fact, safe).
1224                                         chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
1225                                 },
1226                         }
1227                 }
1228
1229                 let mut channel_state = self.channel_state.lock().unwrap();
1230                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1231                         node_id: chan.get_their_node_id(),
1232                         msg: msg,
1233                 });
1234                 match channel_state.by_id.entry(chan.channel_id()) {
1235                         hash_map::Entry::Occupied(_) => {
1236                                 panic!("Generated duplicate funding txid?");
1237                         },
1238                         hash_map::Entry::Vacant(e) => {
1239                                 e.insert(chan);
1240                         }
1241                 }
1242         }
1243
1244         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1245                 if !chan.should_announce() { return None }
1246
1247                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1248                         Ok(res) => res,
1249                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1250                 };
1251                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1252                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1253
1254                 Some(msgs::AnnouncementSignatures {
1255                         channel_id: chan.channel_id(),
1256                         short_channel_id: chan.get_short_channel_id().unwrap(),
1257                         node_signature: our_node_sig,
1258                         bitcoin_signature: our_bitcoin_sig,
1259                 })
1260         }
1261
1262         /// Processes HTLCs which are pending waiting on random forward delay.
1263         ///
1264         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
1265         /// Will likely generate further events.
1266         pub fn process_pending_htlc_forwards(&self) {
1267                 let _ = self.total_consistency_lock.read().unwrap();
1268
1269                 let mut new_events = Vec::new();
1270                 let mut failed_forwards = Vec::new();
1271                 let mut handle_errors = Vec::new();
1272                 {
1273                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1274                         let channel_state = channel_state_lock.borrow_parts();
1275
1276                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1277                                 if short_chan_id != 0 {
1278                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1279                                                 Some(chan_id) => chan_id.clone(),
1280                                                 None => {
1281                                                         failed_forwards.reserve(pending_forwards.len());
1282                                                         for forward_info in pending_forwards.drain(..) {
1283                                                                 match forward_info {
1284                                                                         HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info } => {
1285                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1286                                                                                         short_channel_id: prev_short_channel_id,
1287                                                                                         htlc_id: prev_htlc_id,
1288                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1289                                                                                 });
1290                                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1291                                                                         },
1292                                                                         HTLCForwardInfo::FailHTLC { .. } => {
1293                                                                                 // Channel went away before we could fail it. This implies
1294                                                                                 // the channel is now on chain and our counterparty is
1295                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
1296                                                                                 // problem, not ours.
1297                                                                         }
1298                                                                 }
1299                                                         }
1300                                                         continue;
1301                                                 }
1302                                         };
1303                                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(forward_chan_id) {
1304                                                 let mut add_htlc_msgs = Vec::new();
1305                                                 let mut fail_htlc_msgs = Vec::new();
1306                                                 for forward_info in pending_forwards.drain(..) {
1307                                                         match forward_info {
1308                                                                 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info } => {
1309                                                                         log_trace!(self, "Adding HTLC from short id {} with payment_hash {} to channel with short id {} after delay", log_bytes!(forward_info.payment_hash.0), prev_short_channel_id, short_chan_id);
1310                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1311                                                                                 short_channel_id: prev_short_channel_id,
1312                                                                                 htlc_id: prev_htlc_id,
1313                                                                                 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1314                                                                         });
1315                                                                         match chan.get_mut().send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, htlc_source.clone(), forward_info.onion_packet.unwrap()) {
1316                                                                                 Err(e) => {
1317                                                                                         if let ChannelError::Ignore(msg) = e {
1318                                                                                                 log_trace!(self, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(forward_info.payment_hash.0), msg);
1319                                                                                         } else {
1320                                                                                                 panic!("Stated return value requirements in send_htlc() were not met");
1321                                                                                         }
1322                                                                                         let chan_update = self.get_channel_update(chan.get()).unwrap();
1323                                                                                         failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1324                                                                                         continue;
1325                                                                                 },
1326                                                                                 Ok(update_add) => {
1327                                                                                         match update_add {
1328                                                                                                 Some(msg) => { add_htlc_msgs.push(msg); },
1329                                                                                                 None => {
1330                                                                                                         // Nothing to do here...we're waiting on a remote
1331                                                                                                         // revoke_and_ack before we can add anymore HTLCs. The Channel
1332                                                                                                         // will automatically handle building the update_add_htlc and
1333                                                                                                         // commitment_signed messages when we can.
1334                                                                                                         // TODO: Do some kind of timer to set the channel as !is_live()
1335                                                                                                         // as we don't really want others relying on us relaying through
1336                                                                                                         // this channel currently :/.
1337                                                                                                 }
1338                                                                                         }
1339                                                                                 }
1340                                                                         }
1341                                                                 },
1342                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
1343                                                                         log_trace!(self, "Failing HTLC back to channel with short id {} after delay", short_chan_id);
1344                                                                         match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet) {
1345                                                                                 Err(e) => {
1346                                                                                         if let ChannelError::Ignore(msg) = e {
1347                                                                                                 log_trace!(self, "Failed to fail backwards to short_id {}: {}", short_chan_id, msg);
1348                                                                                         } else {
1349                                                                                                 panic!("Stated return value requirements in get_update_fail_htlc() were not met");
1350                                                                                         }
1351                                                                                         // fail-backs are best-effort, we probably already have one
1352                                                                                         // pending, and if not that's OK, if not, the channel is on
1353                                                                                         // the chain and sending the HTLC-Timeout is their problem.
1354                                                                                         continue;
1355                                                                                 },
1356                                                                                 Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
1357                                                                                 Ok(None) => {
1358                                                                                         // Nothing to do here...we're waiting on a remote
1359                                                                                         // revoke_and_ack before we can update the commitment
1360                                                                                         // transaction. The Channel will automatically handle
1361                                                                                         // building the update_fail_htlc and commitment_signed
1362                                                                                         // messages when we can.
1363                                                                                         // We don't need any kind of timer here as they should fail
1364                                                                                         // the channel onto the chain if they can't get our
1365                                                                                         // update_fail_htlc in time, it's not our problem.
1366                                                                                 }
1367                                                                         }
1368                                                                 },
1369                                                         }
1370                                                 }
1371
1372                                                 if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
1373                                                         let (commitment_msg, monitor) = match chan.get_mut().send_commitment() {
1374                                                                 Ok(res) => res,
1375                                                                 Err(e) => {
1376                                                                         // We surely failed send_commitment due to bad keys, in that case
1377                                                                         // close channel and then send error message to peer.
1378                                                                         let their_node_id = chan.get().get_their_node_id();
1379                                                                         let err: Result<(), _>  = match e {
1380                                                                                 ChannelError::Ignore(_) => {
1381                                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1382                                                                                 },
1383                                                                                 ChannelError::Close(msg) => {
1384                                                                                         log_trace!(self, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
1385                                                                                         let (channel_id, mut channel) = chan.remove_entry();
1386                                                                                         if let Some(short_id) = channel.get_short_channel_id() {
1387                                                                                                 channel_state.short_to_id.remove(&short_id);
1388                                                                                         }
1389                                                                                         Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, channel.force_shutdown(), self.get_channel_update(&channel).ok()))
1390                                                                                 },
1391                                                                                 ChannelError::CloseDelayBroadcast { .. } => { panic!("Wait is only generated on receipt of channel_reestablish, which is handled by try_chan_entry, we don't bother to support it here"); }
1392                                                                         };
1393                                                                         match handle_error!(self, err) {
1394                                                                                 Ok(_) => unreachable!(),
1395                                                                                 Err(e) => {
1396                                                                                         if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1397                                                                                         } else {
1398                                                                                                 log_error!(self, "Got bad keys: {}!", e.err);
1399                                                                                                 let mut channel_state = self.channel_state.lock().unwrap();
1400                                                                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1401                                                                                                         node_id: their_node_id,
1402                                                                                                         action: e.action,
1403                                                                                                 });
1404                                                                                         }
1405                                                                                         continue;
1406                                                                                 },
1407                                                                         }
1408                                                                 }
1409                                                         };
1410                                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1411                                                                 handle_errors.push((chan.get().get_their_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
1412                                                                 continue;
1413                                                         }
1414                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1415                                                                 node_id: chan.get().get_their_node_id(),
1416                                                                 updates: msgs::CommitmentUpdate {
1417                                                                         update_add_htlcs: add_htlc_msgs,
1418                                                                         update_fulfill_htlcs: Vec::new(),
1419                                                                         update_fail_htlcs: fail_htlc_msgs,
1420                                                                         update_fail_malformed_htlcs: Vec::new(),
1421                                                                         update_fee: None,
1422                                                                         commitment_signed: commitment_msg,
1423                                                                 },
1424                                                         });
1425                                                 }
1426                                         } else {
1427                                                 unreachable!();
1428                                         }
1429                                 } else {
1430                                         for forward_info in pending_forwards.drain(..) {
1431                                                 match forward_info {
1432                                                         HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info } => {
1433                                                                 let prev_hop_data = HTLCPreviousHopData {
1434                                                                         short_channel_id: prev_short_channel_id,
1435                                                                         htlc_id: prev_htlc_id,
1436                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1437                                                                 };
1438                                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1439                                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push((forward_info.amt_to_forward, prev_hop_data)),
1440                                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![(forward_info.amt_to_forward, prev_hop_data)]); },
1441                                                                 };
1442                                                                 new_events.push(events::Event::PaymentReceived {
1443                                                                         payment_hash: forward_info.payment_hash,
1444                                                                         amt: forward_info.amt_to_forward,
1445                                                                 });
1446                                                         },
1447                                                         HTLCForwardInfo::FailHTLC { .. } => {
1448                                                                 panic!("Got pending fail of our own HTLC");
1449                                                         }
1450                                                 }
1451                                         }
1452                                 }
1453                         }
1454                 }
1455
1456                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1457                         match update {
1458                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1459                                 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() }),
1460                         };
1461                 }
1462
1463                 for (their_node_id, err) in handle_errors.drain(..) {
1464                         match handle_error!(self, err) {
1465                                 Ok(_) => {},
1466                                 Err(e) => {
1467                                         if let msgs::ErrorAction::IgnoreError = e.action {
1468                                         } else {
1469                                                 let mut channel_state = self.channel_state.lock().unwrap();
1470                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1471                                                         node_id: their_node_id,
1472                                                         action: e.action,
1473                                                 });
1474                                         }
1475                                 },
1476                         }
1477                 }
1478
1479                 if new_events.is_empty() { return }
1480                 let mut events = self.pending_events.lock().unwrap();
1481                 events.append(&mut new_events);
1482         }
1483
1484         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1485         /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
1486         /// along the path (including in our own channel on which we received it).
1487         /// Returns false if no payment was found to fail backwards, true if the process of failing the
1488         /// HTLC backwards has been started.
1489         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) -> bool {
1490                 let _ = self.total_consistency_lock.read().unwrap();
1491
1492                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1493                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1494                 if let Some(mut sources) = removed_source {
1495                         for (recvd_value, htlc_with_hash) in sources.drain(..) {
1496                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1497                                 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1498                                                 HTLCSource::PreviousHopData(htlc_with_hash), payment_hash,
1499                                                 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(recvd_value).to_vec() });
1500                         }
1501                         true
1502                 } else { false }
1503         }
1504
1505         /// Fails an HTLC backwards to the sender of it to us.
1506         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1507         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1508         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1509         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1510         /// still-available channels.
1511         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1512                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
1513                 //identify whether we sent it or not based on the (I presume) very different runtime
1514                 //between the branches here. We should make this async and move it into the forward HTLCs
1515                 //timer handling.
1516                 match source {
1517                         HTLCSource::OutboundRoute { ref route, .. } => {
1518                                 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1519                                 mem::drop(channel_state_lock);
1520                                 match &onion_error {
1521                                         &HTLCFailReason::LightningError { ref err } => {
1522 #[cfg(test)]
1523                                                 let (channel_update, payment_retryable, onion_error_code) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
1524 #[cfg(not(test))]
1525                                                 let (channel_update, payment_retryable, _) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
1526                                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1527                                                 // process_onion_failure we should close that channel as it implies our
1528                                                 // next-hop is needlessly blaming us!
1529                                                 if let Some(update) = channel_update {
1530                                                         self.channel_state.lock().unwrap().pending_msg_events.push(
1531                                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1532                                                                         update,
1533                                                                 }
1534                                                         );
1535                                                 }
1536                                                 self.pending_events.lock().unwrap().push(
1537                                                         events::Event::PaymentFailed {
1538                                                                 payment_hash: payment_hash.clone(),
1539                                                                 rejected_by_dest: !payment_retryable,
1540 #[cfg(test)]
1541                                                                 error_code: onion_error_code
1542                                                         }
1543                                                 );
1544                                         },
1545                                         &HTLCFailReason::Reason {
1546 #[cfg(test)]
1547                                                         ref failure_code,
1548                                                         .. } => {
1549                                                 // we get a fail_malformed_htlc from the first hop
1550                                                 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1551                                                 // failures here, but that would be insufficient as Router::get_route
1552                                                 // generally ignores its view of our own channels as we provide them via
1553                                                 // ChannelDetails.
1554                                                 // TODO: For non-temporary failures, we really should be closing the
1555                                                 // channel here as we apparently can't relay through them anyway.
1556                                                 self.pending_events.lock().unwrap().push(
1557                                                         events::Event::PaymentFailed {
1558                                                                 payment_hash: payment_hash.clone(),
1559                                                                 rejected_by_dest: route.hops.len() == 1,
1560 #[cfg(test)]
1561                                                                 error_code: Some(*failure_code),
1562                                                         }
1563                                                 );
1564                                         }
1565                                 }
1566                         },
1567                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1568                                 let err_packet = match onion_error {
1569                                         HTLCFailReason::Reason { failure_code, data } => {
1570                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1571                                                 let packet = onion_utils::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1572                                                 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1573                                         },
1574                                         HTLCFailReason::LightningError { err } => {
1575                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built LightningError", log_bytes!(payment_hash.0));
1576                                                 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1577                                         }
1578                                 };
1579
1580                                 let mut forward_event = None;
1581                                 if channel_state_lock.forward_htlcs.is_empty() {
1582                                         forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
1583                                 }
1584                                 match channel_state_lock.forward_htlcs.entry(short_channel_id) {
1585                                         hash_map::Entry::Occupied(mut entry) => {
1586                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id, err_packet });
1587                                         },
1588                                         hash_map::Entry::Vacant(entry) => {
1589                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id, err_packet }));
1590                                         }
1591                                 }
1592                                 mem::drop(channel_state_lock);
1593                                 if let Some(time) = forward_event {
1594                                         let mut pending_events = self.pending_events.lock().unwrap();
1595                                         pending_events.push(events::Event::PendingHTLCsForwardable {
1596                                                 time_forwardable: time
1597                                         });
1598                                 }
1599                         },
1600                 }
1601         }
1602
1603         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1604         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1605         /// should probably kick the net layer to go send messages if this returns true!
1606         ///
1607         /// May panic if called except in response to a PaymentReceived event.
1608         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1609                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1610
1611                 let _ = self.total_consistency_lock.read().unwrap();
1612
1613                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1614                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1615                 if let Some(mut sources) = removed_source {
1616                         // TODO: We should require the user specify the expected amount so that we can claim
1617                         // only payments for the correct amount, and reject payments for incorrect amounts
1618                         // (which are probably middle nodes probing to break our privacy).
1619                         for (_, htlc_with_hash) in sources.drain(..) {
1620                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1621                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1622                         }
1623                         true
1624                 } else { false }
1625         }
1626         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1627                 let (their_node_id, err) = loop {
1628                         match source {
1629                                 HTLCSource::OutboundRoute { .. } => {
1630                                         mem::drop(channel_state_lock);
1631                                         let mut pending_events = self.pending_events.lock().unwrap();
1632                                         pending_events.push(events::Event::PaymentSent {
1633                                                 payment_preimage
1634                                         });
1635                                 },
1636                                 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1637                                         //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1638                                         let channel_state = channel_state_lock.borrow_parts();
1639
1640                                         let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1641                                                 Some(chan_id) => chan_id.clone(),
1642                                                 None => {
1643                                                         // TODO: There is probably a channel manager somewhere that needs to
1644                                                         // learn the preimage as the channel already hit the chain and that's
1645                                                         // why it's missing.
1646                                                         return
1647                                                 }
1648                                         };
1649
1650                                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(chan_id) {
1651                                                 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
1652                                                 match chan.get_mut().get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1653                                                         Ok((msgs, monitor_option)) => {
1654                                                                 if let Some(chan_monitor) = monitor_option {
1655                                                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1656                                                                                 if was_frozen_for_monitor {
1657                                                                                         assert!(msgs.is_none());
1658                                                                                 } else {
1659                                                                                         break (chan.get().get_their_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, msgs.is_some()));
1660                                                                                 }
1661                                                                         }
1662                                                                 }
1663                                                                 if let Some((msg, commitment_signed)) = msgs {
1664                                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1665                                                                                 node_id: chan.get().get_their_node_id(),
1666                                                                                 updates: msgs::CommitmentUpdate {
1667                                                                                         update_add_htlcs: Vec::new(),
1668                                                                                         update_fulfill_htlcs: vec![msg],
1669                                                                                         update_fail_htlcs: Vec::new(),
1670                                                                                         update_fail_malformed_htlcs: Vec::new(),
1671                                                                                         update_fee: None,
1672                                                                                         commitment_signed,
1673                                                                                 }
1674                                                                         });
1675                                                                 }
1676                                                         },
1677                                                         Err(_e) => {
1678                                                                 // TODO: There is probably a channel manager somewhere that needs to
1679                                                                 // learn the preimage as the channel may be about to hit the chain.
1680                                                                 //TODO: Do something with e?
1681                                                                 return
1682                                                         },
1683                                                 }
1684                                         } else { unreachable!(); }
1685                                 },
1686                         }
1687                         return;
1688                 };
1689
1690                 match handle_error!(self, err) {
1691                         Ok(_) => {},
1692                         Err(e) => {
1693                                 if let msgs::ErrorAction::IgnoreError = e.action {
1694                                 } else {
1695                                         let mut channel_state = self.channel_state.lock().unwrap();
1696                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1697                                                 node_id: their_node_id,
1698                                                 action: e.action,
1699                                         });
1700                                 }
1701                         },
1702                 }
1703         }
1704
1705         /// Gets the node_id held by this ChannelManager
1706         pub fn get_our_node_id(&self) -> PublicKey {
1707                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1708         }
1709
1710         /// Used to restore channels to normal operation after a
1711         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1712         /// operation.
1713         pub fn test_restore_channel_monitor(&self) {
1714                 let mut close_results = Vec::new();
1715                 let mut htlc_forwards = Vec::new();
1716                 let mut htlc_failures = Vec::new();
1717                 let mut pending_events = Vec::new();
1718                 let _ = self.total_consistency_lock.read().unwrap();
1719
1720                 {
1721                         let mut channel_lock = self.channel_state.lock().unwrap();
1722                         let channel_state = channel_lock.borrow_parts();
1723                         let short_to_id = channel_state.short_to_id;
1724                         let pending_msg_events = channel_state.pending_msg_events;
1725                         channel_state.by_id.retain(|_, channel| {
1726                                 if channel.is_awaiting_monitor_update() {
1727                                         let chan_monitor = channel.channel_monitor();
1728                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1729                                                 match e {
1730                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1731                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1732                                                                 // backwards when a monitor update failed. We should make sure
1733                                                                 // knowledge of those gets moved into the appropriate in-memory
1734                                                                 // ChannelMonitor and they get failed backwards once we get
1735                                                                 // on-chain confirmations.
1736                                                                 // Note I think #198 addresses this, so once it's merged a test
1737                                                                 // should be written.
1738                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1739                                                                         short_to_id.remove(&short_id);
1740                                                                 }
1741                                                                 close_results.push(channel.force_shutdown());
1742                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1743                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1744                                                                                 msg: update
1745                                                                         });
1746                                                                 }
1747                                                                 false
1748                                                         },
1749                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1750                                                 }
1751                                         } else {
1752                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures, needs_broadcast_safe, funding_locked) = channel.monitor_updating_restored();
1753                                                 if !pending_forwards.is_empty() {
1754                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1755                                                 }
1756                                                 htlc_failures.append(&mut pending_failures);
1757
1758                                                 macro_rules! handle_cs { () => {
1759                                                         if let Some(update) = commitment_update {
1760                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1761                                                                         node_id: channel.get_their_node_id(),
1762                                                                         updates: update,
1763                                                                 });
1764                                                         }
1765                                                 } }
1766                                                 macro_rules! handle_raa { () => {
1767                                                         if let Some(revoke_and_ack) = raa {
1768                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1769                                                                         node_id: channel.get_their_node_id(),
1770                                                                         msg: revoke_and_ack,
1771                                                                 });
1772                                                         }
1773                                                 } }
1774                                                 match order {
1775                                                         RAACommitmentOrder::CommitmentFirst => {
1776                                                                 handle_cs!();
1777                                                                 handle_raa!();
1778                                                         },
1779                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1780                                                                 handle_raa!();
1781                                                                 handle_cs!();
1782                                                         },
1783                                                 }
1784                                                 if needs_broadcast_safe {
1785                                                         pending_events.push(events::Event::FundingBroadcastSafe {
1786                                                                 funding_txo: channel.get_funding_txo().unwrap(),
1787                                                                 user_channel_id: channel.get_user_id(),
1788                                                         });
1789                                                 }
1790                                                 if let Some(msg) = funding_locked {
1791                                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
1792                                                                 node_id: channel.get_their_node_id(),
1793                                                                 msg,
1794                                                         });
1795                                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
1796                                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1797                                                                         node_id: channel.get_their_node_id(),
1798                                                                         msg: announcement_sigs,
1799                                                                 });
1800                                                         }
1801                                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
1802                                                 }
1803                                                 true
1804                                         }
1805                                 } else { true }
1806                         });
1807                 }
1808
1809                 self.pending_events.lock().unwrap().append(&mut pending_events);
1810
1811                 for failure in htlc_failures.drain(..) {
1812                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1813                 }
1814                 self.forward_htlcs(&mut htlc_forwards[..]);
1815
1816                 for res in close_results.drain(..) {
1817                         self.finish_force_close_channel(res);
1818                 }
1819         }
1820
1821         fn internal_open_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1822                 if msg.chain_hash != self.genesis_hash {
1823                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1824                 }
1825
1826                 let channel = Channel::new_from_req(&*self.fee_estimator, &self.keys_manager, their_node_id.clone(), their_local_features, msg, 0, Arc::clone(&self.logger), &self.default_configuration)
1827                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1828                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1829                 let channel_state = channel_state_lock.borrow_parts();
1830                 match channel_state.by_id.entry(channel.channel_id()) {
1831                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1832                         hash_map::Entry::Vacant(entry) => {
1833                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1834                                         node_id: their_node_id.clone(),
1835                                         msg: channel.get_accept_channel(),
1836                                 });
1837                                 entry.insert(channel);
1838                         }
1839                 }
1840                 Ok(())
1841         }
1842
1843         fn internal_accept_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1844                 let (value, output_script, user_id) = {
1845                         let mut channel_lock = self.channel_state.lock().unwrap();
1846                         let channel_state = channel_lock.borrow_parts();
1847                         match channel_state.by_id.entry(msg.temporary_channel_id) {
1848                                 hash_map::Entry::Occupied(mut chan) => {
1849                                         if chan.get().get_their_node_id() != *their_node_id {
1850                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1851                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1852                                         }
1853                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration, their_local_features), channel_state, chan);
1854                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1855                                 },
1856                                 //TODO: same as above
1857                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1858                         }
1859                 };
1860                 let mut pending_events = self.pending_events.lock().unwrap();
1861                 pending_events.push(events::Event::FundingGenerationReady {
1862                         temporary_channel_id: msg.temporary_channel_id,
1863                         channel_value_satoshis: value,
1864                         output_script: output_script,
1865                         user_channel_id: user_id,
1866                 });
1867                 Ok(())
1868         }
1869
1870         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1871                 let ((funding_msg, monitor_update), mut chan) = {
1872                         let mut channel_lock = self.channel_state.lock().unwrap();
1873                         let channel_state = channel_lock.borrow_parts();
1874                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1875                                 hash_map::Entry::Occupied(mut chan) => {
1876                                         if chan.get().get_their_node_id() != *their_node_id {
1877                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1878                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1879                                         }
1880                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1881                                 },
1882                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1883                         }
1884                 };
1885                 // Because we have exclusive ownership of the channel here we can release the channel_state
1886                 // lock before add_update_monitor
1887                 if let Err(e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1888                         match e {
1889                                 ChannelMonitorUpdateErr::PermanentFailure => {
1890                                         // Note that we reply with the new channel_id in error messages if we gave up on the
1891                                         // channel, not the temporary_channel_id. This is compatible with ourselves, but the
1892                                         // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
1893                                         // any messages referencing a previously-closed channel anyway.
1894                                         return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", funding_msg.channel_id, chan.force_shutdown(), None));
1895                                 },
1896                                 ChannelMonitorUpdateErr::TemporaryFailure => {
1897                                         // There's no problem signing a counterparty's funding transaction if our monitor
1898                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
1899                                         // accepted payment from yet. We do, however, need to wait to send our funding_locked
1900                                         // until we have persisted our monitor.
1901                                         chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
1902                                 },
1903                         }
1904                 }
1905                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1906                 let channel_state = channel_state_lock.borrow_parts();
1907                 match channel_state.by_id.entry(funding_msg.channel_id) {
1908                         hash_map::Entry::Occupied(_) => {
1909                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1910                         },
1911                         hash_map::Entry::Vacant(e) => {
1912                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1913                                         node_id: their_node_id.clone(),
1914                                         msg: funding_msg,
1915                                 });
1916                                 e.insert(chan);
1917                         }
1918                 }
1919                 Ok(())
1920         }
1921
1922         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1923                 let (funding_txo, user_id) = {
1924                         let mut channel_lock = self.channel_state.lock().unwrap();
1925                         let channel_state = channel_lock.borrow_parts();
1926                         match channel_state.by_id.entry(msg.channel_id) {
1927                                 hash_map::Entry::Occupied(mut chan) => {
1928                                         if chan.get().get_their_node_id() != *their_node_id {
1929                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1930                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1931                                         }
1932                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1933                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1934                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
1935                                         }
1936                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1937                                 },
1938                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1939                         }
1940                 };
1941                 let mut pending_events = self.pending_events.lock().unwrap();
1942                 pending_events.push(events::Event::FundingBroadcastSafe {
1943                         funding_txo: funding_txo,
1944                         user_channel_id: user_id,
1945                 });
1946                 Ok(())
1947         }
1948
1949         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1950                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1951                 let channel_state = channel_state_lock.borrow_parts();
1952                 match channel_state.by_id.entry(msg.channel_id) {
1953                         hash_map::Entry::Occupied(mut chan) => {
1954                                 if chan.get().get_their_node_id() != *their_node_id {
1955                                         //TODO: here and below MsgHandleErrInternal, #153 case
1956                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1957                                 }
1958                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1959                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1960                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1961                                                 node_id: their_node_id.clone(),
1962                                                 msg: announcement_sigs,
1963                                         });
1964                                 }
1965                                 Ok(())
1966                         },
1967                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1968                 }
1969         }
1970
1971         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1972                 let (mut dropped_htlcs, chan_option) = {
1973                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1974                         let channel_state = channel_state_lock.borrow_parts();
1975
1976                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1977                                 hash_map::Entry::Occupied(mut chan_entry) => {
1978                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1979                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1980                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1981                                         }
1982                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1983                                         if let Some(msg) = shutdown {
1984                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1985                                                         node_id: their_node_id.clone(),
1986                                                         msg,
1987                                                 });
1988                                         }
1989                                         if let Some(msg) = closing_signed {
1990                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1991                                                         node_id: their_node_id.clone(),
1992                                                         msg,
1993                                                 });
1994                                         }
1995                                         if chan_entry.get().is_shutdown() {
1996                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1997                                                         channel_state.short_to_id.remove(&short_id);
1998                                                 }
1999                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
2000                                         } else { (dropped_htlcs, None) }
2001                                 },
2002                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2003                         }
2004                 };
2005                 for htlc_source in dropped_htlcs.drain(..) {
2006                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2007                 }
2008                 if let Some(chan) = chan_option {
2009                         if let Ok(update) = self.get_channel_update(&chan) {
2010                                 let mut channel_state = self.channel_state.lock().unwrap();
2011                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2012                                         msg: update
2013                                 });
2014                         }
2015                 }
2016                 Ok(())
2017         }
2018
2019         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
2020                 let (tx, chan_option) = {
2021                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2022                         let channel_state = channel_state_lock.borrow_parts();
2023                         match channel_state.by_id.entry(msg.channel_id.clone()) {
2024                                 hash_map::Entry::Occupied(mut chan_entry) => {
2025                                         if chan_entry.get().get_their_node_id() != *their_node_id {
2026                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2027                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2028                                         }
2029                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
2030                                         if let Some(msg) = closing_signed {
2031                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2032                                                         node_id: their_node_id.clone(),
2033                                                         msg,
2034                                                 });
2035                                         }
2036                                         if tx.is_some() {
2037                                                 // We're done with this channel, we've got a signed closing transaction and
2038                                                 // will send the closing_signed back to the remote peer upon return. This
2039                                                 // also implies there are no pending HTLCs left on the channel, so we can
2040                                                 // fully delete it from tracking (the channel monitor is still around to
2041                                                 // watch for old state broadcasts)!
2042                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2043                                                         channel_state.short_to_id.remove(&short_id);
2044                                                 }
2045                                                 (tx, Some(chan_entry.remove_entry().1))
2046                                         } else { (tx, None) }
2047                                 },
2048                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2049                         }
2050                 };
2051                 if let Some(broadcast_tx) = tx {
2052                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2053                 }
2054                 if let Some(chan) = chan_option {
2055                         if let Ok(update) = self.get_channel_update(&chan) {
2056                                 let mut channel_state = self.channel_state.lock().unwrap();
2057                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2058                                         msg: update
2059                                 });
2060                         }
2061                 }
2062                 Ok(())
2063         }
2064
2065         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2066                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2067                 //determine the state of the payment based on our response/if we forward anything/the time
2068                 //we take to respond. We should take care to avoid allowing such an attack.
2069                 //
2070                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2071                 //us repeatedly garbled in different ways, and compare our error messages, which are
2072                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
2073                 //but we should prevent it anyway.
2074
2075                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2076                 let channel_state = channel_state_lock.borrow_parts();
2077
2078                 match channel_state.by_id.entry(msg.channel_id) {
2079                         hash_map::Entry::Occupied(mut chan) => {
2080                                 if chan.get().get_their_node_id() != *their_node_id {
2081                                         //TODO: here MsgHandleErrInternal, #153 case
2082                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2083                                 }
2084                                 if !chan.get().is_usable() {
2085                                         // If the update_add is completely bogus, the call will Err and we will close,
2086                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2087                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2088                                         if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2089                                                 let chan_update = self.get_channel_update(chan.get());
2090                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2091                                                         channel_id: msg.channel_id,
2092                                                         htlc_id: msg.htlc_id,
2093                                                         reason: if let Ok(update) = chan_update {
2094                                                                 // TODO: Note that |20 is defined as "channel FROM the processing
2095                                                                 // node has been disabled" (emphasis mine), which seems to imply
2096                                                                 // that we can't return |20 for an inbound channel being disabled.
2097                                                                 // This probably needs a spec update but should definitely be
2098                                                                 // allowed.
2099                                                                 onion_utils::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &{
2100                                                                         let mut res = Vec::with_capacity(8 + 128);
2101                                                                         res.extend_from_slice(&byte_utils::be16_to_array(update.contents.flags));
2102                                                                         res.extend_from_slice(&update.encode_with_len()[..]);
2103                                                                         res
2104                                                                 }[..])
2105                                                         } else {
2106                                                                 // This can only happen if the channel isn't in the fully-funded
2107                                                                 // state yet, implying our counterparty is trying to route payments
2108                                                                 // over the channel back to themselves (cause no one else should
2109                                                                 // know the short_id is a lightning channel yet). We should have no
2110                                                                 // problem just calling this unknown_next_peer
2111                                                                 onion_utils::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2112                                                         },
2113                                                 }));
2114                                         }
2115                                 }
2116                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2117                         },
2118                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2119                 }
2120                 Ok(())
2121         }
2122
2123         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2124                 let mut channel_lock = self.channel_state.lock().unwrap();
2125                 let htlc_source = {
2126                         let channel_state = channel_lock.borrow_parts();
2127                         match channel_state.by_id.entry(msg.channel_id) {
2128                                 hash_map::Entry::Occupied(mut chan) => {
2129                                         if chan.get().get_their_node_id() != *their_node_id {
2130                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2131                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2132                                         }
2133                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2134                                 },
2135                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2136                         }
2137                 };
2138                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2139                 Ok(())
2140         }
2141
2142         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2143                 let mut channel_lock = self.channel_state.lock().unwrap();
2144                 let channel_state = channel_lock.borrow_parts();
2145                 match channel_state.by_id.entry(msg.channel_id) {
2146                         hash_map::Entry::Occupied(mut chan) => {
2147                                 if chan.get().get_their_node_id() != *their_node_id {
2148                                         //TODO: here and below MsgHandleErrInternal, #153 case
2149                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2150                                 }
2151                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::LightningError { err: msg.reason.clone() }), channel_state, chan);
2152                         },
2153                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2154                 }
2155                 Ok(())
2156         }
2157
2158         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2159                 let mut channel_lock = self.channel_state.lock().unwrap();
2160                 let channel_state = channel_lock.borrow_parts();
2161                 match channel_state.by_id.entry(msg.channel_id) {
2162                         hash_map::Entry::Occupied(mut chan) => {
2163                                 if chan.get().get_their_node_id() != *their_node_id {
2164                                         //TODO: here and below MsgHandleErrInternal, #153 case
2165                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2166                                 }
2167                                 if (msg.failure_code & 0x8000) == 0 {
2168                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2169                                 }
2170                                 try_chan_entry!(self, chan.get_mut().update_fail_malformed_htlc(&msg, HTLCFailReason::Reason { failure_code: msg.failure_code, data: Vec::new() }), channel_state, chan);
2171                                 Ok(())
2172                         },
2173                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2174                 }
2175         }
2176
2177         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2178                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2179                 let channel_state = channel_state_lock.borrow_parts();
2180                 match channel_state.by_id.entry(msg.channel_id) {
2181                         hash_map::Entry::Occupied(mut chan) => {
2182                                 if chan.get().get_their_node_id() != *their_node_id {
2183                                         //TODO: here and below MsgHandleErrInternal, #153 case
2184                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2185                                 }
2186                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2187                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2188                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2189                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some());
2190                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2191                                 }
2192                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2193                                         node_id: their_node_id.clone(),
2194                                         msg: revoke_and_ack,
2195                                 });
2196                                 if let Some(msg) = commitment_signed {
2197                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2198                                                 node_id: their_node_id.clone(),
2199                                                 updates: msgs::CommitmentUpdate {
2200                                                         update_add_htlcs: Vec::new(),
2201                                                         update_fulfill_htlcs: Vec::new(),
2202                                                         update_fail_htlcs: Vec::new(),
2203                                                         update_fail_malformed_htlcs: Vec::new(),
2204                                                         update_fee: None,
2205                                                         commitment_signed: msg,
2206                                                 },
2207                                         });
2208                                 }
2209                                 if let Some(msg) = closing_signed {
2210                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2211                                                 node_id: their_node_id.clone(),
2212                                                 msg,
2213                                         });
2214                                 }
2215                                 Ok(())
2216                         },
2217                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2218                 }
2219         }
2220
2221         #[inline]
2222         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2223                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2224                         let mut forward_event = None;
2225                         if !pending_forwards.is_empty() {
2226                                 let mut channel_state = self.channel_state.lock().unwrap();
2227                                 if channel_state.forward_htlcs.is_empty() {
2228                                         forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS))
2229                                 }
2230                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2231                                         match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2232                                                 hash_map::Entry::Occupied(mut entry) => {
2233                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info });
2234                                                 },
2235                                                 hash_map::Entry::Vacant(entry) => {
2236                                                         entry.insert(vec!(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info }));
2237                                                 }
2238                                         }
2239                                 }
2240                         }
2241                         match forward_event {
2242                                 Some(time) => {
2243                                         let mut pending_events = self.pending_events.lock().unwrap();
2244                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2245                                                 time_forwardable: time
2246                                         });
2247                                 }
2248                                 None => {},
2249                         }
2250                 }
2251         }
2252
2253         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2254                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2255                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2256                         let channel_state = channel_state_lock.borrow_parts();
2257                         match channel_state.by_id.entry(msg.channel_id) {
2258                                 hash_map::Entry::Occupied(mut chan) => {
2259                                         if chan.get().get_their_node_id() != *their_node_id {
2260                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2261                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2262                                         }
2263                                         let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2264                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2265                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2266                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2267                                                 if was_frozen_for_monitor {
2268                                                         assert!(commitment_update.is_none() && closing_signed.is_none() && pending_forwards.is_empty() && pending_failures.is_empty());
2269                                                         return Err(MsgHandleErrInternal::ignore_no_close("Previous monitor update failure prevented responses to RAA"));
2270                                                 } else {
2271                                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, commitment_update.is_some(), pending_forwards, pending_failures);
2272                                                 }
2273                                         }
2274                                         if let Some(updates) = commitment_update {
2275                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2276                                                         node_id: their_node_id.clone(),
2277                                                         updates,
2278                                                 });
2279                                         }
2280                                         if let Some(msg) = closing_signed {
2281                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2282                                                         node_id: their_node_id.clone(),
2283                                                         msg,
2284                                                 });
2285                                         }
2286                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2287                                 },
2288                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2289                         }
2290                 };
2291                 for failure in pending_failures.drain(..) {
2292                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2293                 }
2294                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2295
2296                 Ok(())
2297         }
2298
2299         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2300                 let mut channel_lock = self.channel_state.lock().unwrap();
2301                 let channel_state = channel_lock.borrow_parts();
2302                 match channel_state.by_id.entry(msg.channel_id) {
2303                         hash_map::Entry::Occupied(mut chan) => {
2304                                 if chan.get().get_their_node_id() != *their_node_id {
2305                                         //TODO: here and below MsgHandleErrInternal, #153 case
2306                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2307                                 }
2308                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2309                         },
2310                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2311                 }
2312                 Ok(())
2313         }
2314
2315         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2316                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2317                 let channel_state = channel_state_lock.borrow_parts();
2318
2319                 match channel_state.by_id.entry(msg.channel_id) {
2320                         hash_map::Entry::Occupied(mut chan) => {
2321                                 if chan.get().get_their_node_id() != *their_node_id {
2322                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2323                                 }
2324                                 if !chan.get().is_usable() {
2325                                         return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it", action: msgs::ErrorAction::IgnoreError}));
2326                                 }
2327
2328                                 let our_node_id = self.get_our_node_id();
2329                                 let (announcement, our_bitcoin_sig) =
2330                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2331
2332                                 let were_node_one = announcement.node_id_1 == our_node_id;
2333                                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
2334                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2335                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2336                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2337                                 }
2338
2339                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2340
2341                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2342                                         msg: msgs::ChannelAnnouncement {
2343                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2344                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2345                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2346                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2347                                                 contents: announcement,
2348                                         },
2349                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2350                                 });
2351                         },
2352                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2353                 }
2354                 Ok(())
2355         }
2356
2357         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2358                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2359                 let channel_state = channel_state_lock.borrow_parts();
2360
2361                 match channel_state.by_id.entry(msg.channel_id) {
2362                         hash_map::Entry::Occupied(mut chan) => {
2363                                 if chan.get().get_their_node_id() != *their_node_id {
2364                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2365                                 }
2366                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2367                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2368                                 if let Some(monitor) = channel_monitor {
2369                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2370                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2371                                                 // for the messages it returns, but if we're setting what messages to
2372                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2373                                                 if revoke_and_ack.is_none() {
2374                                                         order = RAACommitmentOrder::CommitmentFirst;
2375                                                 }
2376                                                 if commitment_update.is_none() {
2377                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2378                                                 }
2379                                                 return_monitor_err!(self, e, channel_state, chan, order, revoke_and_ack.is_some(), commitment_update.is_some());
2380                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2381                                         }
2382                                 }
2383                                 if let Some(msg) = funding_locked {
2384                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2385                                                 node_id: their_node_id.clone(),
2386                                                 msg
2387                                         });
2388                                 }
2389                                 macro_rules! send_raa { () => {
2390                                         if let Some(msg) = revoke_and_ack {
2391                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2392                                                         node_id: their_node_id.clone(),
2393                                                         msg
2394                                                 });
2395                                         }
2396                                 } }
2397                                 macro_rules! send_cu { () => {
2398                                         if let Some(updates) = commitment_update {
2399                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2400                                                         node_id: their_node_id.clone(),
2401                                                         updates
2402                                                 });
2403                                         }
2404                                 } }
2405                                 match order {
2406                                         RAACommitmentOrder::RevokeAndACKFirst => {
2407                                                 send_raa!();
2408                                                 send_cu!();
2409                                         },
2410                                         RAACommitmentOrder::CommitmentFirst => {
2411                                                 send_cu!();
2412                                                 send_raa!();
2413                                         },
2414                                 }
2415                                 if let Some(msg) = shutdown {
2416                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2417                                                 node_id: their_node_id.clone(),
2418                                                 msg,
2419                                         });
2420                                 }
2421                                 Ok(())
2422                         },
2423                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2424                 }
2425         }
2426
2427         /// Begin Update fee process. Allowed only on an outbound channel.
2428         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2429         /// PeerManager::process_events afterwards.
2430         /// Note: This API is likely to change!
2431         #[doc(hidden)]
2432         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2433                 let _ = self.total_consistency_lock.read().unwrap();
2434                 let their_node_id;
2435                 let err: Result<(), _> = loop {
2436                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2437                         let channel_state = channel_state_lock.borrow_parts();
2438
2439                         match channel_state.by_id.entry(channel_id) {
2440                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2441                                 hash_map::Entry::Occupied(mut chan) => {
2442                                         if !chan.get().is_outbound() {
2443                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2444                                         }
2445                                         if chan.get().is_awaiting_monitor_update() {
2446                                                 return Err(APIError::MonitorUpdateFailed);
2447                                         }
2448                                         if !chan.get().is_live() {
2449                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2450                                         }
2451                                         their_node_id = chan.get().get_their_node_id();
2452                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2453                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2454                                         {
2455                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2456                                                         unimplemented!();
2457                                                 }
2458                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2459                                                         node_id: chan.get().get_their_node_id(),
2460                                                         updates: msgs::CommitmentUpdate {
2461                                                                 update_add_htlcs: Vec::new(),
2462                                                                 update_fulfill_htlcs: Vec::new(),
2463                                                                 update_fail_htlcs: Vec::new(),
2464                                                                 update_fail_malformed_htlcs: Vec::new(),
2465                                                                 update_fee: Some(update_fee),
2466                                                                 commitment_signed,
2467                                                         },
2468                                                 });
2469                                         }
2470                                 },
2471                         }
2472                         return Ok(())
2473                 };
2474
2475                 match handle_error!(self, err) {
2476                         Ok(_) => unreachable!(),
2477                         Err(e) => {
2478                                 if let msgs::ErrorAction::IgnoreError = e.action {
2479                                 } else {
2480                                         log_error!(self, "Got bad keys: {}!", e.err);
2481                                         let mut channel_state = self.channel_state.lock().unwrap();
2482                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2483                                                 node_id: their_node_id,
2484                                                 action: e.action,
2485                                         });
2486                                 }
2487                                 Err(APIError::APIMisuseError { err: e.err })
2488                         },
2489                 }
2490         }
2491 }
2492
2493 impl events::MessageSendEventsProvider for ChannelManager {
2494         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2495                 // TODO: Event release to users and serialization is currently race-y: it's very easy for a
2496                 // user to serialize a ChannelManager with pending events in it and lose those events on
2497                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2498                 {
2499                         //TODO: This behavior should be documented.
2500                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2501                                 if let Some(preimage) = htlc_update.payment_preimage {
2502                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2503                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2504                                 } else {
2505                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2506                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2507                                 }
2508                         }
2509                 }
2510
2511                 let mut ret = Vec::new();
2512                 let mut channel_state = self.channel_state.lock().unwrap();
2513                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2514                 ret
2515         }
2516 }
2517
2518 impl events::EventsProvider for ChannelManager {
2519         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2520                 // TODO: Event release to users and serialization is currently race-y: it's very easy for a
2521                 // user to serialize a ChannelManager with pending events in it and lose those events on
2522                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2523                 {
2524                         //TODO: This behavior should be documented.
2525                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2526                                 if let Some(preimage) = htlc_update.payment_preimage {
2527                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2528                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2529                                 } else {
2530                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2531                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2532                                 }
2533                         }
2534                 }
2535
2536                 let mut ret = Vec::new();
2537                 let mut pending_events = self.pending_events.lock().unwrap();
2538                 mem::swap(&mut ret, &mut *pending_events);
2539                 ret
2540         }
2541 }
2542
2543 impl ChainListener for ChannelManager {
2544         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2545                 let header_hash = header.bitcoin_hash();
2546                 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2547                 let _ = self.total_consistency_lock.read().unwrap();
2548                 let mut failed_channels = Vec::new();
2549                 {
2550                         let mut channel_lock = self.channel_state.lock().unwrap();
2551                         let channel_state = channel_lock.borrow_parts();
2552                         let short_to_id = channel_state.short_to_id;
2553                         let pending_msg_events = channel_state.pending_msg_events;
2554                         channel_state.by_id.retain(|_, channel| {
2555                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2556                                 if let Ok(Some(funding_locked)) = chan_res {
2557                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2558                                                 node_id: channel.get_their_node_id(),
2559                                                 msg: funding_locked,
2560                                         });
2561                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2562                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2563                                                         node_id: channel.get_their_node_id(),
2564                                                         msg: announcement_sigs,
2565                                                 });
2566                                         }
2567                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2568                                 } else if let Err(e) = chan_res {
2569                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
2570                                                 node_id: channel.get_their_node_id(),
2571                                                 action: msgs::ErrorAction::SendErrorMessage { msg: e },
2572                                         });
2573                                         return false;
2574                                 }
2575                                 if let Some(funding_txo) = channel.get_funding_txo() {
2576                                         for tx in txn_matched {
2577                                                 for inp in tx.input.iter() {
2578                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2579                                                                 log_trace!(self, "Detected channel-closing tx {} spending {}:{}, closing channel {}", tx.txid(), inp.previous_output.txid, inp.previous_output.vout, log_bytes!(channel.channel_id()));
2580                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2581                                                                         short_to_id.remove(&short_id);
2582                                                                 }
2583                                                                 // It looks like our counterparty went on-chain. We go ahead and
2584                                                                 // broadcast our latest local state as well here, just in case its
2585                                                                 // some kind of SPV attack, though we expect these to be dropped.
2586                                                                 failed_channels.push(channel.force_shutdown());
2587                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2588                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2589                                                                                 msg: update
2590                                                                         });
2591                                                                 }
2592                                                                 return false;
2593                                                         }
2594                                                 }
2595                                         }
2596                                 }
2597                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2598                                         if let Some(short_id) = channel.get_short_channel_id() {
2599                                                 short_to_id.remove(&short_id);
2600                                         }
2601                                         failed_channels.push(channel.force_shutdown());
2602                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2603                                         // the latest local tx for us, so we should skip that here (it doesn't really
2604                                         // hurt anything, but does make tests a bit simpler).
2605                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2606                                         if let Ok(update) = self.get_channel_update(&channel) {
2607                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2608                                                         msg: update
2609                                                 });
2610                                         }
2611                                         return false;
2612                                 }
2613                                 true
2614                         });
2615                 }
2616                 for failure in failed_channels.drain(..) {
2617                         self.finish_force_close_channel(failure);
2618                 }
2619                 self.latest_block_height.store(height as usize, Ordering::Release);
2620                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2621         }
2622
2623         /// We force-close the channel without letting our counterparty participate in the shutdown
2624         fn block_disconnected(&self, header: &BlockHeader, _: u32) {
2625                 let _ = self.total_consistency_lock.read().unwrap();
2626                 let mut failed_channels = Vec::new();
2627                 {
2628                         let mut channel_lock = self.channel_state.lock().unwrap();
2629                         let channel_state = channel_lock.borrow_parts();
2630                         let short_to_id = channel_state.short_to_id;
2631                         let pending_msg_events = channel_state.pending_msg_events;
2632                         channel_state.by_id.retain(|_,  v| {
2633                                 if v.block_disconnected(header) {
2634                                         if let Some(short_id) = v.get_short_channel_id() {
2635                                                 short_to_id.remove(&short_id);
2636                                         }
2637                                         failed_channels.push(v.force_shutdown());
2638                                         if let Ok(update) = self.get_channel_update(&v) {
2639                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2640                                                         msg: update
2641                                                 });
2642                                         }
2643                                         false
2644                                 } else {
2645                                         true
2646                                 }
2647                         });
2648                 }
2649                 for failure in failed_channels.drain(..) {
2650                         self.finish_force_close_channel(failure);
2651                 }
2652                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2653                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2654         }
2655 }
2656
2657 impl ChannelMessageHandler for ChannelManager {
2658         //TODO: Handle errors and close channel (or so)
2659         fn handle_open_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &msgs::OpenChannel) -> Result<(), LightningError> {
2660                 let _ = self.total_consistency_lock.read().unwrap();
2661                 handle_error!(self, self.internal_open_channel(their_node_id, their_local_features, msg))
2662         }
2663
2664         fn handle_accept_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &msgs::AcceptChannel) -> Result<(), LightningError> {
2665                 let _ = self.total_consistency_lock.read().unwrap();
2666                 handle_error!(self, self.internal_accept_channel(their_node_id, their_local_features, msg))
2667         }
2668
2669         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), LightningError> {
2670                 let _ = self.total_consistency_lock.read().unwrap();
2671                 handle_error!(self, self.internal_funding_created(their_node_id, msg))
2672         }
2673
2674         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), LightningError> {
2675                 let _ = self.total_consistency_lock.read().unwrap();
2676                 handle_error!(self, self.internal_funding_signed(their_node_id, msg))
2677         }
2678
2679         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), LightningError> {
2680                 let _ = self.total_consistency_lock.read().unwrap();
2681                 handle_error!(self, self.internal_funding_locked(their_node_id, msg))
2682         }
2683
2684         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), LightningError> {
2685                 let _ = self.total_consistency_lock.read().unwrap();
2686                 handle_error!(self, self.internal_shutdown(their_node_id, msg))
2687         }
2688
2689         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), LightningError> {
2690                 let _ = self.total_consistency_lock.read().unwrap();
2691                 handle_error!(self, self.internal_closing_signed(their_node_id, msg))
2692         }
2693
2694         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), LightningError> {
2695                 let _ = self.total_consistency_lock.read().unwrap();
2696                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg))
2697         }
2698
2699         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), LightningError> {
2700                 let _ = self.total_consistency_lock.read().unwrap();
2701                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg))
2702         }
2703
2704         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), LightningError> {
2705                 let _ = self.total_consistency_lock.read().unwrap();
2706                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg))
2707         }
2708
2709         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), LightningError> {
2710                 let _ = self.total_consistency_lock.read().unwrap();
2711                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg))
2712         }
2713
2714         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), LightningError> {
2715                 let _ = self.total_consistency_lock.read().unwrap();
2716                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg))
2717         }
2718
2719         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), LightningError> {
2720                 let _ = self.total_consistency_lock.read().unwrap();
2721                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg))
2722         }
2723
2724         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), LightningError> {
2725                 let _ = self.total_consistency_lock.read().unwrap();
2726                 handle_error!(self, self.internal_update_fee(their_node_id, msg))
2727         }
2728
2729         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), LightningError> {
2730                 let _ = self.total_consistency_lock.read().unwrap();
2731                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg))
2732         }
2733
2734         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), LightningError> {
2735                 let _ = self.total_consistency_lock.read().unwrap();
2736                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg))
2737         }
2738
2739         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2740                 let _ = self.total_consistency_lock.read().unwrap();
2741                 let mut failed_channels = Vec::new();
2742                 let mut failed_payments = Vec::new();
2743                 {
2744                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2745                         let channel_state = channel_state_lock.borrow_parts();
2746                         let short_to_id = channel_state.short_to_id;
2747                         let pending_msg_events = channel_state.pending_msg_events;
2748                         if no_connection_possible {
2749                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2750                                 channel_state.by_id.retain(|_, chan| {
2751                                         if chan.get_their_node_id() == *their_node_id {
2752                                                 if let Some(short_id) = chan.get_short_channel_id() {
2753                                                         short_to_id.remove(&short_id);
2754                                                 }
2755                                                 failed_channels.push(chan.force_shutdown());
2756                                                 if let Ok(update) = self.get_channel_update(&chan) {
2757                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2758                                                                 msg: update
2759                                                         });
2760                                                 }
2761                                                 false
2762                                         } else {
2763                                                 true
2764                                         }
2765                                 });
2766                         } else {
2767                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2768                                 channel_state.by_id.retain(|_, chan| {
2769                                         if chan.get_their_node_id() == *their_node_id {
2770                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2771                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2772                                                 if !failed_adds.is_empty() {
2773                                                         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
2774                                                         failed_payments.push((chan_update, failed_adds));
2775                                                 }
2776                                                 if chan.is_shutdown() {
2777                                                         if let Some(short_id) = chan.get_short_channel_id() {
2778                                                                 short_to_id.remove(&short_id);
2779                                                         }
2780                                                         return false;
2781                                                 }
2782                                         }
2783                                         true
2784                                 })
2785                         }
2786                         pending_msg_events.retain(|msg| {
2787                                 match msg {
2788                                         &events::MessageSendEvent::SendAcceptChannel { ref node_id, .. } => node_id != their_node_id,
2789                                         &events::MessageSendEvent::SendOpenChannel { ref node_id, .. } => node_id != their_node_id,
2790                                         &events::MessageSendEvent::SendFundingCreated { ref node_id, .. } => node_id != their_node_id,
2791                                         &events::MessageSendEvent::SendFundingSigned { ref node_id, .. } => node_id != their_node_id,
2792                                         &events::MessageSendEvent::SendFundingLocked { ref node_id, .. } => node_id != their_node_id,
2793                                         &events::MessageSendEvent::SendAnnouncementSignatures { ref node_id, .. } => node_id != their_node_id,
2794                                         &events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => node_id != their_node_id,
2795                                         &events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => node_id != their_node_id,
2796                                         &events::MessageSendEvent::SendClosingSigned { ref node_id, .. } => node_id != their_node_id,
2797                                         &events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != their_node_id,
2798                                         &events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != their_node_id,
2799                                         &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
2800                                         &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
2801                                         &events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != their_node_id,
2802                                         &events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
2803                                 }
2804                         });
2805                 }
2806                 for failure in failed_channels.drain(..) {
2807                         self.finish_force_close_channel(failure);
2808                 }
2809                 for (chan_update, mut htlc_sources) in failed_payments {
2810                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2811                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2812                         }
2813                 }
2814         }
2815
2816         fn peer_connected(&self, their_node_id: &PublicKey) {
2817                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2818
2819                 let _ = self.total_consistency_lock.read().unwrap();
2820                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2821                 let channel_state = channel_state_lock.borrow_parts();
2822                 let pending_msg_events = channel_state.pending_msg_events;
2823                 channel_state.by_id.retain(|_, chan| {
2824                         if chan.get_their_node_id() == *their_node_id {
2825                                 if !chan.have_received_message() {
2826                                         // If we created this (outbound) channel while we were disconnected from the
2827                                         // peer we probably failed to send the open_channel message, which is now
2828                                         // lost. We can't have had anything pending related to this channel, so we just
2829                                         // drop it.
2830                                         false
2831                                 } else {
2832                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2833                                                 node_id: chan.get_their_node_id(),
2834                                                 msg: chan.get_channel_reestablish(),
2835                                         });
2836                                         true
2837                                 }
2838                         } else { true }
2839                 });
2840                 //TODO: Also re-broadcast announcement_signatures
2841         }
2842
2843         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2844                 let _ = self.total_consistency_lock.read().unwrap();
2845
2846                 if msg.channel_id == [0; 32] {
2847                         for chan in self.list_channels() {
2848                                 if chan.remote_network_id == *their_node_id {
2849                                         self.force_close_channel(&chan.channel_id);
2850                                 }
2851                         }
2852                 } else {
2853                         self.force_close_channel(&msg.channel_id);
2854                 }
2855         }
2856 }
2857
2858 const SERIALIZATION_VERSION: u8 = 1;
2859 const MIN_SERIALIZATION_VERSION: u8 = 1;
2860
2861 impl Writeable for PendingForwardHTLCInfo {
2862         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2863                 self.onion_packet.write(writer)?;
2864                 self.incoming_shared_secret.write(writer)?;
2865                 self.payment_hash.write(writer)?;
2866                 self.short_channel_id.write(writer)?;
2867                 self.amt_to_forward.write(writer)?;
2868                 self.outgoing_cltv_value.write(writer)?;
2869                 Ok(())
2870         }
2871 }
2872
2873 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2874         fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2875                 Ok(PendingForwardHTLCInfo {
2876                         onion_packet: Readable::read(reader)?,
2877                         incoming_shared_secret: Readable::read(reader)?,
2878                         payment_hash: Readable::read(reader)?,
2879                         short_channel_id: Readable::read(reader)?,
2880                         amt_to_forward: Readable::read(reader)?,
2881                         outgoing_cltv_value: Readable::read(reader)?,
2882                 })
2883         }
2884 }
2885
2886 impl Writeable for HTLCFailureMsg {
2887         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2888                 match self {
2889                         &HTLCFailureMsg::Relay(ref fail_msg) => {
2890                                 0u8.write(writer)?;
2891                                 fail_msg.write(writer)?;
2892                         },
2893                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
2894                                 1u8.write(writer)?;
2895                                 fail_msg.write(writer)?;
2896                         }
2897                 }
2898                 Ok(())
2899         }
2900 }
2901
2902 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
2903         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
2904                 match <u8 as Readable<R>>::read(reader)? {
2905                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
2906                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
2907                         _ => Err(DecodeError::InvalidValue),
2908                 }
2909         }
2910 }
2911
2912 impl Writeable for PendingHTLCStatus {
2913         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2914                 match self {
2915                         &PendingHTLCStatus::Forward(ref forward_info) => {
2916                                 0u8.write(writer)?;
2917                                 forward_info.write(writer)?;
2918                         },
2919                         &PendingHTLCStatus::Fail(ref fail_msg) => {
2920                                 1u8.write(writer)?;
2921                                 fail_msg.write(writer)?;
2922                         }
2923                 }
2924                 Ok(())
2925         }
2926 }
2927
2928 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
2929         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
2930                 match <u8 as Readable<R>>::read(reader)? {
2931                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
2932                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
2933                         _ => Err(DecodeError::InvalidValue),
2934                 }
2935         }
2936 }
2937
2938 impl_writeable!(HTLCPreviousHopData, 0, {
2939         short_channel_id,
2940         htlc_id,
2941         incoming_packet_shared_secret
2942 });
2943
2944 impl Writeable for HTLCSource {
2945         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2946                 match self {
2947                         &HTLCSource::PreviousHopData(ref hop_data) => {
2948                                 0u8.write(writer)?;
2949                                 hop_data.write(writer)?;
2950                         },
2951                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
2952                                 1u8.write(writer)?;
2953                                 route.write(writer)?;
2954                                 session_priv.write(writer)?;
2955                                 first_hop_htlc_msat.write(writer)?;
2956                         }
2957                 }
2958                 Ok(())
2959         }
2960 }
2961
2962 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
2963         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
2964                 match <u8 as Readable<R>>::read(reader)? {
2965                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
2966                         1 => Ok(HTLCSource::OutboundRoute {
2967                                 route: Readable::read(reader)?,
2968                                 session_priv: Readable::read(reader)?,
2969                                 first_hop_htlc_msat: Readable::read(reader)?,
2970                         }),
2971                         _ => Err(DecodeError::InvalidValue),
2972                 }
2973         }
2974 }
2975
2976 impl Writeable for HTLCFailReason {
2977         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2978                 match self {
2979                         &HTLCFailReason::LightningError { ref err } => {
2980                                 0u8.write(writer)?;
2981                                 err.write(writer)?;
2982                         },
2983                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
2984                                 1u8.write(writer)?;
2985                                 failure_code.write(writer)?;
2986                                 data.write(writer)?;
2987                         }
2988                 }
2989                 Ok(())
2990         }
2991 }
2992
2993 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
2994         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
2995                 match <u8 as Readable<R>>::read(reader)? {
2996                         0 => Ok(HTLCFailReason::LightningError { err: Readable::read(reader)? }),
2997                         1 => Ok(HTLCFailReason::Reason {
2998                                 failure_code: Readable::read(reader)?,
2999                                 data: Readable::read(reader)?,
3000                         }),
3001                         _ => Err(DecodeError::InvalidValue),
3002                 }
3003         }
3004 }
3005
3006 impl Writeable for HTLCForwardInfo {
3007         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3008                 match self {
3009                         &HTLCForwardInfo::AddHTLC { ref prev_short_channel_id, ref prev_htlc_id, ref forward_info } => {
3010                                 0u8.write(writer)?;
3011                                 prev_short_channel_id.write(writer)?;
3012                                 prev_htlc_id.write(writer)?;
3013                                 forward_info.write(writer)?;
3014                         },
3015                         &HTLCForwardInfo::FailHTLC { ref htlc_id, ref err_packet } => {
3016                                 1u8.write(writer)?;
3017                                 htlc_id.write(writer)?;
3018                                 err_packet.write(writer)?;
3019                         },
3020                 }
3021                 Ok(())
3022         }
3023 }
3024
3025 impl<R: ::std::io::Read> Readable<R> for HTLCForwardInfo {
3026         fn read(reader: &mut R) -> Result<HTLCForwardInfo, DecodeError> {
3027                 match <u8 as Readable<R>>::read(reader)? {
3028                         0 => Ok(HTLCForwardInfo::AddHTLC {
3029                                 prev_short_channel_id: Readable::read(reader)?,
3030                                 prev_htlc_id: Readable::read(reader)?,
3031                                 forward_info: Readable::read(reader)?,
3032                         }),
3033                         1 => Ok(HTLCForwardInfo::FailHTLC {
3034                                 htlc_id: Readable::read(reader)?,
3035                                 err_packet: Readable::read(reader)?,
3036                         }),
3037                         _ => Err(DecodeError::InvalidValue),
3038                 }
3039         }
3040 }
3041
3042 impl Writeable for ChannelManager {
3043         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3044                 let _ = self.total_consistency_lock.write().unwrap();
3045
3046                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3047                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3048
3049                 self.genesis_hash.write(writer)?;
3050                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3051                 self.last_block_hash.lock().unwrap().write(writer)?;
3052
3053                 let channel_state = self.channel_state.lock().unwrap();
3054                 let mut unfunded_channels = 0;
3055                 for (_, channel) in channel_state.by_id.iter() {
3056                         if !channel.is_funding_initiated() {
3057                                 unfunded_channels += 1;
3058                         }
3059                 }
3060                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3061                 for (_, channel) in channel_state.by_id.iter() {
3062                         if channel.is_funding_initiated() {
3063                                 channel.write(writer)?;
3064                         }
3065                 }
3066
3067                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3068                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3069                         short_channel_id.write(writer)?;
3070                         (pending_forwards.len() as u64).write(writer)?;
3071                         for forward in pending_forwards {
3072                                 forward.write(writer)?;
3073                         }
3074                 }
3075
3076                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3077                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3078                         payment_hash.write(writer)?;
3079                         (previous_hops.len() as u64).write(writer)?;
3080                         for &(recvd_amt, ref previous_hop) in previous_hops.iter() {
3081                                 recvd_amt.write(writer)?;
3082                                 previous_hop.write(writer)?;
3083                         }
3084                 }
3085
3086                 Ok(())
3087         }
3088 }
3089
3090 /// Arguments for the creation of a ChannelManager that are not deserialized.
3091 ///
3092 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3093 /// is:
3094 /// 1) Deserialize all stored ChannelMonitors.
3095 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3096 ///    ChannelManager)>::read(reader, args).
3097 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3098 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3099 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3100 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3101 /// 4) Reconnect blocks on your ChannelMonitors.
3102 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3103 /// 6) Disconnect/connect blocks on the ChannelManager.
3104 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3105 ///    automatically as it does in ChannelManager::new()).
3106 pub struct ChannelManagerReadArgs<'a> {
3107         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3108         /// deserialization.
3109         pub keys_manager: Arc<KeysInterface>,
3110
3111         /// The fee_estimator for use in the ChannelManager in the future.
3112         ///
3113         /// No calls to the FeeEstimator will be made during deserialization.
3114         pub fee_estimator: Arc<FeeEstimator>,
3115         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3116         ///
3117         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3118         /// you have deserialized ChannelMonitors separately and will add them to your
3119         /// ManyChannelMonitor after deserializing this ChannelManager.
3120         pub monitor: Arc<ManyChannelMonitor>,
3121         /// The ChainWatchInterface for use in the ChannelManager in the future.
3122         ///
3123         /// No calls to the ChainWatchInterface will be made during deserialization.
3124         pub chain_monitor: Arc<ChainWatchInterface>,
3125         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3126         /// used to broadcast the latest local commitment transactions of channels which must be
3127         /// force-closed during deserialization.
3128         pub tx_broadcaster: Arc<BroadcasterInterface>,
3129         /// The Logger for use in the ChannelManager and which may be used to log information during
3130         /// deserialization.
3131         pub logger: Arc<Logger>,
3132         /// Default settings used for new channels. Any existing channels will continue to use the
3133         /// runtime settings which were stored when the ChannelManager was serialized.
3134         pub default_config: UserConfig,
3135
3136         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3137         /// value.get_funding_txo() should be the key).
3138         ///
3139         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3140         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
3141         /// is true for missing channels as well. If there is a monitor missing for which we find
3142         /// channel data Err(DecodeError::InvalidValue) will be returned.
3143         ///
3144         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3145         /// this struct.
3146         pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3147 }
3148
3149 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3150         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3151                 let _ver: u8 = Readable::read(reader)?;
3152                 let min_ver: u8 = Readable::read(reader)?;
3153                 if min_ver > SERIALIZATION_VERSION {
3154                         return Err(DecodeError::UnknownVersion);
3155                 }
3156
3157                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3158                 let latest_block_height: u32 = Readable::read(reader)?;
3159                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3160
3161                 let mut closed_channels = Vec::new();
3162
3163                 let channel_count: u64 = Readable::read(reader)?;
3164                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3165                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3166                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3167                 for _ in 0..channel_count {
3168                         let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3169                         if channel.last_block_connected != last_block_hash {
3170                                 return Err(DecodeError::InvalidValue);
3171                         }
3172
3173                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3174                         funding_txo_set.insert(funding_txo.clone());
3175                         if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3176                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3177                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3178                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3179                                         let mut force_close_res = channel.force_shutdown();
3180                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3181                                         closed_channels.push(force_close_res);
3182                                 } else {
3183                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3184                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3185                                         }
3186                                         by_id.insert(channel.channel_id(), channel);
3187                                 }
3188                         } else {
3189                                 return Err(DecodeError::InvalidValue);
3190                         }
3191                 }
3192
3193                 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3194                         if !funding_txo_set.contains(funding_txo) {
3195                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3196                         }
3197                 }
3198
3199                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3200                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3201                 for _ in 0..forward_htlcs_count {
3202                         let short_channel_id = Readable::read(reader)?;
3203                         let pending_forwards_count: u64 = Readable::read(reader)?;
3204                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3205                         for _ in 0..pending_forwards_count {
3206                                 pending_forwards.push(Readable::read(reader)?);
3207                         }
3208                         forward_htlcs.insert(short_channel_id, pending_forwards);
3209                 }
3210
3211                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3212                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3213                 for _ in 0..claimable_htlcs_count {
3214                         let payment_hash = Readable::read(reader)?;
3215                         let previous_hops_len: u64 = Readable::read(reader)?;
3216                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3217                         for _ in 0..previous_hops_len {
3218                                 previous_hops.push((Readable::read(reader)?, Readable::read(reader)?));
3219                         }
3220                         claimable_htlcs.insert(payment_hash, previous_hops);
3221                 }
3222
3223                 let channel_manager = ChannelManager {
3224                         genesis_hash,
3225                         fee_estimator: args.fee_estimator,
3226                         monitor: args.monitor,
3227                         chain_monitor: args.chain_monitor,
3228                         tx_broadcaster: args.tx_broadcaster,
3229
3230                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3231                         last_block_hash: Mutex::new(last_block_hash),
3232                         secp_ctx: Secp256k1::new(),
3233
3234                         channel_state: Mutex::new(ChannelHolder {
3235                                 by_id,
3236                                 short_to_id,
3237                                 forward_htlcs,
3238                                 claimable_htlcs,
3239                                 pending_msg_events: Vec::new(),
3240                         }),
3241                         our_network_key: args.keys_manager.get_node_secret(),
3242
3243                         pending_events: Mutex::new(Vec::new()),
3244                         total_consistency_lock: RwLock::new(()),
3245                         keys_manager: args.keys_manager,
3246                         logger: args.logger,
3247                         default_configuration: args.default_config,
3248                 };
3249
3250                 for close_res in closed_channels.drain(..) {
3251                         channel_manager.finish_force_close_channel(close_res);
3252                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3253                         //connection or two.
3254                 }
3255
3256                 Ok((last_block_hash.clone(), channel_manager))
3257         }
3258 }