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