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