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