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