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