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