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