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