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