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