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