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