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