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