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