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