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