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