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