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