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