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