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