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