50f8ccbb74f4833175b00060fcd7ee882873c71b
[rust-lightning] / lightning / src / ln / channelmanager.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! The top-level channel management and payment tracking stuff lives here.
11 //!
12 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
13 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
14 //! upon reconnect to the relevant peer(s).
15 //!
16 //! It does not manage routing logic (see routing::router::get_route for that) nor does it manage constructing
17 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
18 //! imply it needs to fail HTLCs/payments/channels it manages).
19 //!
20
21 use bitcoin::blockdata::block::{Block, BlockHeader};
22 use bitcoin::blockdata::constants::genesis_block;
23 use bitcoin::network::constants::Network;
24
25 use bitcoin::hashes::{Hash, HashEngine};
26 use bitcoin::hashes::hmac::{Hmac, HmacEngine};
27 use bitcoin::hashes::sha256::Hash as Sha256;
28 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
29 use bitcoin::hashes::cmp::fixed_time_eq;
30 use bitcoin::hash_types::BlockHash;
31
32 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
33 use bitcoin::secp256k1::Secp256k1;
34 use bitcoin::secp256k1::ecdh::SharedSecret;
35 use bitcoin::secp256k1;
36
37 use chain;
38 use chain::Watch;
39 use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
40 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, ChannelMonitorUpdateErr, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent, CLOSED_CHANNEL_UPDATE_ID};
41 use chain::transaction::{OutPoint, TransactionData};
42 // Since this struct is returned in `list_channels` methods, expose it here in case users want to
43 // construct one themselves.
44 pub use ln::channel::CounterpartyForwardingInfo;
45 use ln::channel::{Channel, ChannelError};
46 use ln::features::{InitFeatures, NodeFeatures};
47 use routing::router::{Route, RouteHop};
48 use ln::msgs;
49 use ln::msgs::NetAddress;
50 use ln::onion_utils;
51 use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, OptionalField};
52 use chain::keysinterface::{Sign, KeysInterface, KeysManager, InMemorySigner};
53 use util::config::UserConfig;
54 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
55 use util::{byte_utils, events};
56 use util::ser::{Readable, ReadableArgs, MaybeReadable, Writeable, Writer};
57 use util::chacha20::{ChaCha20, ChaChaReader};
58 use util::logger::Logger;
59 use util::errors::APIError;
60
61 use std::{cmp, mem};
62 use std::collections::{HashMap, hash_map, HashSet};
63 use std::io::{Cursor, Read};
64 use std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard};
65 use std::sync::atomic::{AtomicUsize, Ordering};
66 use std::time::Duration;
67 #[cfg(any(test, feature = "allow_wallclock_use"))]
68 use std::time::Instant;
69 use std::marker::{Sync, Send};
70 use std::ops::Deref;
71 use bitcoin::hashes::hex::ToHex;
72
73 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
74 //
75 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
76 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
77 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
78 //
79 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
80 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
81 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
82 // before we forward it.
83 //
84 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
85 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
86 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
87 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
88 // our payment, which we can use to decode errors or inform the user that the payment was sent.
89
90 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
91 enum PendingHTLCRouting {
92         Forward {
93                 onion_packet: msgs::OnionPacket,
94                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
95         },
96         Receive {
97                 payment_data: Option<msgs::FinalOnionHopData>,
98                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
99         },
100 }
101
102 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
103 pub(super) struct PendingHTLCInfo {
104         routing: PendingHTLCRouting,
105         incoming_shared_secret: [u8; 32],
106         payment_hash: PaymentHash,
107         pub(super) amt_to_forward: u64,
108         pub(super) outgoing_cltv_value: u32,
109 }
110
111 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
112 pub(super) enum HTLCFailureMsg {
113         Relay(msgs::UpdateFailHTLC),
114         Malformed(msgs::UpdateFailMalformedHTLC),
115 }
116
117 /// Stores whether we can't forward an HTLC or relevant forwarding info
118 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
119 pub(super) enum PendingHTLCStatus {
120         Forward(PendingHTLCInfo),
121         Fail(HTLCFailureMsg),
122 }
123
124 pub(super) enum HTLCForwardInfo {
125         AddHTLC {
126                 forward_info: PendingHTLCInfo,
127
128                 // These fields are produced in `forward_htlcs()` and consumed in
129                 // `process_pending_htlc_forwards()` for constructing the
130                 // `HTLCSource::PreviousHopData` for failed and forwarded
131                 // HTLCs.
132                 prev_short_channel_id: u64,
133                 prev_htlc_id: u64,
134                 prev_funding_outpoint: OutPoint,
135         },
136         FailHTLC {
137                 htlc_id: u64,
138                 err_packet: msgs::OnionErrorPacket,
139         },
140 }
141
142 /// Tracks the inbound corresponding to an outbound HTLC
143 #[derive(Clone, PartialEq)]
144 pub(crate) struct HTLCPreviousHopData {
145         short_channel_id: u64,
146         htlc_id: u64,
147         incoming_packet_shared_secret: [u8; 32],
148
149         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
150         // channel with a preimage provided by the forward channel.
151         outpoint: OutPoint,
152 }
153
154 struct ClaimableHTLC {
155         prev_hop: HTLCPreviousHopData,
156         value: u64,
157         /// Filled in when the HTLC was received with a payment_secret packet, which contains a
158         /// total_msat (which may differ from value if this is a Multi-Path Payment) and a
159         /// payment_secret which prevents path-probing attacks and can associate different HTLCs which
160         /// are part of the same payment.
161         payment_data: Option<msgs::FinalOnionHopData>,
162         cltv_expiry: u32,
163 }
164
165 /// Tracks the inbound corresponding to an outbound HTLC
166 #[derive(Clone, PartialEq)]
167 pub(crate) enum HTLCSource {
168         PreviousHopData(HTLCPreviousHopData),
169         OutboundRoute {
170                 path: Vec<RouteHop>,
171                 session_priv: SecretKey,
172                 /// Technically we can recalculate this from the route, but we cache it here to avoid
173                 /// doing a double-pass on route when we get a failure back
174                 first_hop_htlc_msat: u64,
175         },
176 }
177 #[cfg(test)]
178 impl HTLCSource {
179         pub fn dummy() -> Self {
180                 HTLCSource::OutboundRoute {
181                         path: Vec::new(),
182                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
183                         first_hop_htlc_msat: 0,
184                 }
185         }
186 }
187
188 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
189 pub(super) enum HTLCFailReason {
190         LightningError {
191                 err: msgs::OnionErrorPacket,
192         },
193         Reason {
194                 failure_code: u16,
195                 data: Vec<u8>,
196         }
197 }
198
199 /// payment_hash type, use to cross-lock hop
200 /// (C-not exported) as we just use [u8; 32] directly
201 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
202 pub struct PaymentHash(pub [u8;32]);
203 /// payment_preimage type, use to route payment between hop
204 /// (C-not exported) as we just use [u8; 32] directly
205 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
206 pub struct PaymentPreimage(pub [u8;32]);
207 /// payment_secret type, use to authenticate sender to the receiver and tie MPP HTLCs together
208 /// (C-not exported) as we just use [u8; 32] directly
209 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
210 pub struct PaymentSecret(pub [u8;32]);
211
212 type ShutdownResult = (Option<(OutPoint, ChannelMonitorUpdate)>, Vec<(HTLCSource, PaymentHash)>);
213
214 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
215 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
216 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
217 /// channel_state lock. We then return the set of things that need to be done outside the lock in
218 /// this struct and call handle_error!() on it.
219
220 struct MsgHandleErrInternal {
221         err: msgs::LightningError,
222         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
223 }
224 impl MsgHandleErrInternal {
225         #[inline]
226         fn send_err_msg_no_close(err: String, channel_id: [u8; 32]) -> Self {
227                 Self {
228                         err: LightningError {
229                                 err: err.clone(),
230                                 action: msgs::ErrorAction::SendErrorMessage {
231                                         msg: msgs::ErrorMessage {
232                                                 channel_id,
233                                                 data: err
234                                         },
235                                 },
236                         },
237                         shutdown_finish: None,
238                 }
239         }
240         #[inline]
241         fn ignore_no_close(err: String) -> Self {
242                 Self {
243                         err: LightningError {
244                                 err,
245                                 action: msgs::ErrorAction::IgnoreError,
246                         },
247                         shutdown_finish: None,
248                 }
249         }
250         #[inline]
251         fn from_no_close(err: msgs::LightningError) -> Self {
252                 Self { err, shutdown_finish: None }
253         }
254         #[inline]
255         fn from_finish_shutdown(err: String, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
256                 Self {
257                         err: LightningError {
258                                 err: err.clone(),
259                                 action: msgs::ErrorAction::SendErrorMessage {
260                                         msg: msgs::ErrorMessage {
261                                                 channel_id,
262                                                 data: err
263                                         },
264                                 },
265                         },
266                         shutdown_finish: Some((shutdown_res, channel_update)),
267                 }
268         }
269         #[inline]
270         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
271                 Self {
272                         err: match err {
273                                 ChannelError::Ignore(msg) => LightningError {
274                                         err: msg,
275                                         action: msgs::ErrorAction::IgnoreError,
276                                 },
277                                 ChannelError::Close(msg) => LightningError {
278                                         err: msg.clone(),
279                                         action: msgs::ErrorAction::SendErrorMessage {
280                                                 msg: msgs::ErrorMessage {
281                                                         channel_id,
282                                                         data: msg
283                                                 },
284                                         },
285                                 },
286                                 ChannelError::CloseDelayBroadcast(msg) => LightningError {
287                                         err: msg.clone(),
288                                         action: msgs::ErrorAction::SendErrorMessage {
289                                                 msg: msgs::ErrorMessage {
290                                                         channel_id,
291                                                         data: msg
292                                                 },
293                                         },
294                                 },
295                         },
296                         shutdown_finish: None,
297                 }
298         }
299 }
300
301 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
302 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
303 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
304 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
305 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
306
307 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
308 /// be sent in the order they appear in the return value, however sometimes the order needs to be
309 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
310 /// they were originally sent). In those cases, this enum is also returned.
311 #[derive(Clone, PartialEq)]
312 pub(super) enum RAACommitmentOrder {
313         /// Send the CommitmentUpdate messages first
314         CommitmentFirst,
315         /// Send the RevokeAndACK message first
316         RevokeAndACKFirst,
317 }
318
319 // Note this is only exposed in cfg(test):
320 pub(super) struct ChannelHolder<Signer: Sign> {
321         pub(super) by_id: HashMap<[u8; 32], Channel<Signer>>,
322         pub(super) short_to_id: HashMap<u64, [u8; 32]>,
323         /// short channel id -> forward infos. Key of 0 means payments received
324         /// Note that while this is held in the same mutex as the channels themselves, no consistency
325         /// guarantees are made about the existence of a channel with the short id here, nor the short
326         /// ids in the PendingHTLCInfo!
327         pub(super) forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
328         /// (payment_hash, payment_secret) -> Vec<HTLCs> for tracking HTLCs that
329         /// were to us and can be failed/claimed by the user
330         /// Note that while this is held in the same mutex as the channels themselves, no consistency
331         /// guarantees are made about the channels given here actually existing anymore by the time you
332         /// go to read them!
333         claimable_htlcs: HashMap<(PaymentHash, Option<PaymentSecret>), Vec<ClaimableHTLC>>,
334         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
335         /// for broadcast messages, where ordering isn't as strict).
336         pub(super) pending_msg_events: Vec<MessageSendEvent>,
337 }
338
339 /// Events which we process internally but cannot be procsesed immediately at the generation site
340 /// for some reason. They are handled in timer_chan_freshness_every_min, so may be processed with
341 /// quite some time lag.
342 enum BackgroundEvent {
343         /// Handle a ChannelMonitorUpdate that closes a channel, broadcasting its current latest holder
344         /// commitment transaction.
345         ClosingMonitorUpdate((OutPoint, ChannelMonitorUpdate)),
346 }
347
348 /// State we hold per-peer. In the future we should put channels in here, but for now we only hold
349 /// the latest Init features we heard from the peer.
350 struct PeerState {
351         latest_features: InitFeatures,
352 }
353
354 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
355 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
356
357 /// SimpleArcChannelManager is useful when you need a ChannelManager with a static lifetime, e.g.
358 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
359 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
360 /// SimpleRefChannelManager is the more appropriate type. Defining these type aliases prevents
361 /// issues such as overly long function definitions. Note that the ChannelManager can take any
362 /// type that implements KeysInterface for its keys manager, but this type alias chooses the
363 /// concrete type of the KeysManager.
364 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<InMemorySigner, Arc<M>, Arc<T>, Arc<KeysManager>, Arc<F>, Arc<L>>;
365
366 /// SimpleRefChannelManager is a type alias for a ChannelManager reference, and is the reference
367 /// counterpart to the SimpleArcChannelManager type alias. Use this type by default when you don't
368 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
369 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
370 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
371 /// helps with issues such as long function definitions. Note that the ChannelManager can take any
372 /// type that implements KeysInterface for its keys manager, but this type alias chooses the
373 /// concrete type of the KeysManager.
374 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManager<InMemorySigner, &'a M, &'b T, &'c KeysManager, &'d F, &'e L>;
375
376 /// Manager which keeps track of a number of channels and sends messages to the appropriate
377 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
378 ///
379 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
380 /// to individual Channels.
381 ///
382 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
383 /// all peers during write/read (though does not modify this instance, only the instance being
384 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
385 /// called funding_transaction_generated for outbound channels).
386 ///
387 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
388 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
389 /// returning from chain::Watch::watch_/update_channel, with ChannelManagers, writing updates
390 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
391 /// the serialization process). If the deserialized version is out-of-date compared to the
392 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
393 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
394 ///
395 /// Note that the deserializer is only implemented for (BlockHash, ChannelManager), which
396 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
397 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
398 /// block_connected() to step towards your best block) upon deserialization before using the
399 /// object!
400 ///
401 /// Note that ChannelManager is responsible for tracking liveness of its channels and generating
402 /// ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid
403 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
404 /// offline for a full minute. In order to track this, you must call
405 /// timer_chan_freshness_every_min roughly once per minute, though it doesn't have to be perfect.
406 ///
407 /// Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager
408 /// a SimpleRefChannelManager, for conciseness. See their documentation for more details, but
409 /// essentially you should default to using a SimpleRefChannelManager, and use a
410 /// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
411 /// you're using lightning-net-tokio.
412 pub struct ChannelManager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
413         where M::Target: chain::Watch<Signer>,
414         T::Target: BroadcasterInterface,
415         K::Target: KeysInterface<Signer = Signer>,
416         F::Target: FeeEstimator,
417                                 L::Target: Logger,
418 {
419         default_configuration: UserConfig,
420         genesis_hash: BlockHash,
421         fee_estimator: F,
422         chain_monitor: M,
423         tx_broadcaster: T,
424
425         #[cfg(test)]
426         pub(super) latest_block_height: AtomicUsize,
427         #[cfg(not(test))]
428         latest_block_height: AtomicUsize,
429         last_block_hash: RwLock<BlockHash>,
430         secp_ctx: Secp256k1<secp256k1::All>,
431
432         #[cfg(any(test, feature = "_test_utils"))]
433         pub(super) channel_state: Mutex<ChannelHolder<Signer>>,
434         #[cfg(not(any(test, feature = "_test_utils")))]
435         channel_state: Mutex<ChannelHolder<Signer>>,
436         our_network_key: SecretKey,
437
438         /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
439         /// value increases strictly since we don't assume access to a time source.
440         last_node_announcement_serial: AtomicUsize,
441
442         /// The bulk of our storage will eventually be here (channels and message queues and the like).
443         /// If we are connected to a peer we always at least have an entry here, even if no channels
444         /// are currently open with that peer.
445         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
446         /// operate on the inner value freely. Sadly, this prevents parallel operation when opening a
447         /// new channel.
448         per_peer_state: RwLock<HashMap<PublicKey, Mutex<PeerState>>>,
449
450         pending_events: Mutex<Vec<events::Event>>,
451         pending_background_events: Mutex<Vec<BackgroundEvent>>,
452         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
453         /// Essentially just when we're serializing ourselves out.
454         /// Taken first everywhere where we are making changes before any other locks.
455         /// When acquiring this lock in read mode, rather than acquiring it directly, call
456         /// `PersistenceNotifierGuard::new(..)` and pass the lock to it, to ensure the PersistenceNotifier
457         /// the lock contains sends out a notification when the lock is released.
458         total_consistency_lock: RwLock<()>,
459
460         persistence_notifier: PersistenceNotifier,
461
462         keys_manager: K,
463
464         logger: L,
465 }
466
467 /// Chain-related parameters used to construct a new `ChannelManager`.
468 ///
469 /// Typically, the block-specific parameters are derived from the best block hash for the network,
470 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
471 /// are not needed when deserializing a previously constructed `ChannelManager`.
472 pub struct ChainParameters {
473         /// The network for determining the `chain_hash` in Lightning messages.
474         pub network: Network,
475
476         /// The hash of the latest block successfully connected.
477         pub latest_hash: BlockHash,
478
479         /// The height of the latest block successfully connected.
480         ///
481         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
482         pub latest_height: usize,
483 }
484
485 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
486 /// desirable to notify any listeners on `await_persistable_update_timeout`/
487 /// `await_persistable_update` that new updates are available for persistence. Therefore, this
488 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
489 /// sending the aforementioned notification (since the lock being released indicates that the
490 /// updates are ready for persistence).
491 struct PersistenceNotifierGuard<'a> {
492         persistence_notifier: &'a PersistenceNotifier,
493         // We hold onto this result so the lock doesn't get released immediately.
494         _read_guard: RwLockReadGuard<'a, ()>,
495 }
496
497 impl<'a> PersistenceNotifierGuard<'a> {
498         fn new(lock: &'a RwLock<()>, notifier: &'a PersistenceNotifier) -> Self {
499                 let read_guard = lock.read().unwrap();
500
501                 Self {
502                         persistence_notifier: notifier,
503                         _read_guard: read_guard,
504                 }
505         }
506 }
507
508 impl<'a> Drop for PersistenceNotifierGuard<'a> {
509         fn drop(&mut self) {
510                 self.persistence_notifier.notify();
511         }
512 }
513
514 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
515 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
516 ///
517 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
518 ///
519 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
520 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
521 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
522 /// the maximum required amount in lnd as of March 2021.
523 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
524
525 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
526 /// HTLC's CLTV. The current default represents roughly six hours of blocks at six blocks/hour.
527 ///
528 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
529 ///
530 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
531 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
532 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
533 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
534 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
535 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6 * 6;
536 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
537
538 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
539 // ie that if the next-hop peer fails the HTLC within
540 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
541 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
542 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
543 // LATENCY_GRACE_PERIOD_BLOCKS.
544 #[deny(const_err)]
545 #[allow(dead_code)]
546 const CHECK_CLTV_EXPIRY_SANITY: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - CLTV_CLAIM_BUFFER - ANTI_REORG_DELAY - LATENCY_GRACE_PERIOD_BLOCKS;
547
548 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
549 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
550 #[deny(const_err)]
551 #[allow(dead_code)]
552 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
553
554 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
555 #[derive(Clone)]
556 pub struct ChannelDetails {
557         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
558         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
559         /// Note that this means this value is *not* persistent - it can change once during the
560         /// lifetime of the channel.
561         pub channel_id: [u8; 32],
562         /// The position of the funding transaction in the chain. None if the funding transaction has
563         /// not yet been confirmed and the channel fully opened.
564         pub short_channel_id: Option<u64>,
565         /// The node_id of our counterparty
566         pub remote_network_id: PublicKey,
567         /// The Features the channel counterparty provided upon last connection.
568         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
569         /// many routing-relevant features are present in the init context.
570         pub counterparty_features: InitFeatures,
571         /// The value, in satoshis, of this channel as appears in the funding output
572         pub channel_value_satoshis: u64,
573         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
574         pub user_id: u64,
575         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
576         /// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
577         /// available for inclusion in new outbound HTLCs). This further does not include any pending
578         /// outgoing HTLCs which are awaiting some other resolution to be sent.
579         pub outbound_capacity_msat: u64,
580         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
581         /// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
582         /// available for inclusion in new inbound HTLCs).
583         /// Note that there are some corner cases not fully handled here, so the actual available
584         /// inbound capacity may be slightly higher than this.
585         pub inbound_capacity_msat: u64,
586         /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
587         /// the peer is connected, and (c) no monitor update failure is pending resolution.
588         pub is_live: bool,
589
590         /// Information on the fees and requirements that the counterparty requires when forwarding
591         /// payments to us through this channel.
592         pub counterparty_forwarding_info: Option<CounterpartyForwardingInfo>,
593 }
594
595 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
596 /// Err() type describing which state the payment is in, see the description of individual enum
597 /// states for more.
598 #[derive(Clone, Debug)]
599 pub enum PaymentSendFailure {
600         /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
601         /// send the payment at all. No channel state has been changed or messages sent to peers, and
602         /// once you've changed the parameter at error, you can freely retry the payment in full.
603         ParameterError(APIError),
604         /// A parameter in a single path which was passed to send_payment was invalid, preventing us
605         /// from attempting to send the payment at all. No channel state has been changed or messages
606         /// sent to peers, and once you've changed the parameter at error, you can freely retry the
607         /// payment in full.
608         ///
609         /// The results here are ordered the same as the paths in the route object which was passed to
610         /// send_payment.
611         PathParameterError(Vec<Result<(), APIError>>),
612         /// All paths which were attempted failed to send, with no channel state change taking place.
613         /// You can freely retry the payment in full (though you probably want to do so over different
614         /// paths than the ones selected).
615         AllFailedRetrySafe(Vec<APIError>),
616         /// Some paths which were attempted failed to send, though possibly not all. At least some
617         /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
618         /// in over-/re-payment.
619         ///
620         /// The results here are ordered the same as the paths in the route object which was passed to
621         /// send_payment, and any Errs which are not APIError::MonitorUpdateFailed can be safely
622         /// retried (though there is currently no API with which to do so).
623         ///
624         /// Any entries which contain Err(APIError::MonitorUpdateFailed) or Ok(()) MUST NOT be retried
625         /// as they will result in over-/re-payment. These HTLCs all either successfully sent (in the
626         /// case of Ok(())) or will send once channel_monitor_updated is called on the next-hop channel
627         /// with the latest update_id.
628         PartialFailure(Vec<Result<(), APIError>>),
629 }
630
631 macro_rules! handle_error {
632         ($self: ident, $internal: expr, $counterparty_node_id: expr) => {
633                 match $internal {
634                         Ok(msg) => Ok(msg),
635                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
636                                 #[cfg(debug_assertions)]
637                                 {
638                                         // In testing, ensure there are no deadlocks where the lock is already held upon
639                                         // entering the macro.
640                                         assert!($self.channel_state.try_lock().is_ok());
641                                 }
642
643                                 let mut msg_events = Vec::with_capacity(2);
644
645                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
646                                         $self.finish_force_close_channel(shutdown_res);
647                                         if let Some(update) = update_option {
648                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
649                                                         msg: update
650                                                 });
651                                         }
652                                 }
653
654                                 log_error!($self.logger, "{}", err.err);
655                                 if let msgs::ErrorAction::IgnoreError = err.action {
656                                 } else {
657                                         msg_events.push(events::MessageSendEvent::HandleError {
658                                                 node_id: $counterparty_node_id,
659                                                 action: err.action.clone()
660                                         });
661                                 }
662
663                                 if !msg_events.is_empty() {
664                                         $self.channel_state.lock().unwrap().pending_msg_events.append(&mut msg_events);
665                                 }
666
667                                 // Return error in case higher-API need one
668                                 Err(err)
669                         },
670                 }
671         }
672 }
673
674 macro_rules! break_chan_entry {
675         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
676                 match $res {
677                         Ok(res) => res,
678                         Err(ChannelError::Ignore(msg)) => {
679                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
680                         },
681                         Err(ChannelError::Close(msg)) => {
682                                 log_trace!($self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
683                                 let (channel_id, mut chan) = $entry.remove_entry();
684                                 if let Some(short_id) = chan.get_short_channel_id() {
685                                         $channel_state.short_to_id.remove(&short_id);
686                                 }
687                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()))
688                         },
689                         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"); }
690                 }
691         }
692 }
693
694 macro_rules! try_chan_entry {
695         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
696                 match $res {
697                         Ok(res) => res,
698                         Err(ChannelError::Ignore(msg)) => {
699                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
700                         },
701                         Err(ChannelError::Close(msg)) => {
702                                 log_trace!($self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
703                                 let (channel_id, mut chan) = $entry.remove_entry();
704                                 if let Some(short_id) = chan.get_short_channel_id() {
705                                         $channel_state.short_to_id.remove(&short_id);
706                                 }
707                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()))
708                         },
709                         Err(ChannelError::CloseDelayBroadcast(msg)) => {
710                                 log_error!($self.logger, "Channel {} need to be shutdown but closing transactions not broadcast due to {}", log_bytes!($entry.key()[..]), msg);
711                                 let (channel_id, mut chan) = $entry.remove_entry();
712                                 if let Some(short_id) = chan.get_short_channel_id() {
713                                         $channel_state.short_to_id.remove(&short_id);
714                                 }
715                                 let shutdown_res = chan.force_shutdown(false);
716                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, shutdown_res, $self.get_channel_update(&chan).ok()))
717                         }
718                 }
719         }
720 }
721
722 macro_rules! handle_monitor_err {
723         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
724                 handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, Vec::new(), Vec::new())
725         };
726         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
727                 match $err {
728                         ChannelMonitorUpdateErr::PermanentFailure => {
729                                 log_error!($self.logger, "Closing channel {} due to monitor update PermanentFailure", log_bytes!($entry.key()[..]));
730                                 let (channel_id, mut chan) = $entry.remove_entry();
731                                 if let Some(short_id) = chan.get_short_channel_id() {
732                                         $channel_state.short_to_id.remove(&short_id);
733                                 }
734                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
735                                 // chain in a confused state! We need to move them into the ChannelMonitor which
736                                 // will be responsible for failing backwards once things confirm on-chain.
737                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
738                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
739                                 // us bother trying to claim it just to forward on to another peer. If we're
740                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
741                                 // given up the preimage yet, so might as well just wait until the payment is
742                                 // retried, avoiding the on-chain fees.
743                                 let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure".to_owned(), channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()));
744                                 res
745                         },
746                         ChannelMonitorUpdateErr::TemporaryFailure => {
747                                 log_info!($self.logger, "Disabling channel {} due to monitor update TemporaryFailure. On restore will send {} and process {} forwards and {} fails",
748                                                 log_bytes!($entry.key()[..]),
749                                                 if $resend_commitment && $resend_raa {
750                                                                 match $action_type {
751                                                                         RAACommitmentOrder::CommitmentFirst => { "commitment then RAA" },
752                                                                         RAACommitmentOrder::RevokeAndACKFirst => { "RAA then commitment" },
753                                                                 }
754                                                         } else if $resend_commitment { "commitment" }
755                                                         else if $resend_raa { "RAA" }
756                                                         else { "nothing" },
757                                                 (&$failed_forwards as &Vec<(PendingHTLCInfo, u64)>).len(),
758                                                 (&$failed_fails as &Vec<(HTLCSource, PaymentHash, HTLCFailReason)>).len());
759                                 if !$resend_commitment {
760                                         debug_assert!($action_type == RAACommitmentOrder::RevokeAndACKFirst || !$resend_raa);
761                                 }
762                                 if !$resend_raa {
763                                         debug_assert!($action_type == RAACommitmentOrder::CommitmentFirst || !$resend_commitment);
764                                 }
765                                 $entry.get_mut().monitor_update_failed($resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
766                                 Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor".to_owned()), *$entry.key()))
767                         },
768                 }
769         }
770 }
771
772 macro_rules! return_monitor_err {
773         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
774                 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment);
775         };
776         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
777                 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
778         }
779 }
780
781 // Does not break in case of TemporaryFailure!
782 macro_rules! maybe_break_monitor_err {
783         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
784                 match (handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment), $err) {
785                         (e, ChannelMonitorUpdateErr::PermanentFailure) => {
786                                 break e;
787                         },
788                         (_, ChannelMonitorUpdateErr::TemporaryFailure) => { },
789                 }
790         }
791 }
792
793 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
794         where M::Target: chain::Watch<Signer>,
795         T::Target: BroadcasterInterface,
796         K::Target: KeysInterface<Signer = Signer>,
797         F::Target: FeeEstimator,
798         L::Target: Logger,
799 {
800         /// Constructs a new ChannelManager to hold several channels and route between them.
801         ///
802         /// This is the main "logic hub" for all channel-related actions, and implements
803         /// ChannelMessageHandler.
804         ///
805         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
806         ///
807         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
808         ///
809         /// Users need to notify the new ChannelManager when a new block is connected or
810         /// disconnected using its `block_connected` and `block_disconnected` methods, starting
811         /// from after `params.latest_hash`.
812         pub fn new(fee_est: F, chain_monitor: M, tx_broadcaster: T, logger: L, keys_manager: K, config: UserConfig, params: ChainParameters) -> Self {
813                 let mut secp_ctx = Secp256k1::new();
814                 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
815
816                 ChannelManager {
817                         default_configuration: config.clone(),
818                         genesis_hash: genesis_block(params.network).header.block_hash(),
819                         fee_estimator: fee_est,
820                         chain_monitor,
821                         tx_broadcaster,
822
823                         latest_block_height: AtomicUsize::new(params.latest_height),
824                         last_block_hash: RwLock::new(params.latest_hash),
825                         secp_ctx,
826
827                         channel_state: Mutex::new(ChannelHolder{
828                                 by_id: HashMap::new(),
829                                 short_to_id: HashMap::new(),
830                                 forward_htlcs: HashMap::new(),
831                                 claimable_htlcs: HashMap::new(),
832                                 pending_msg_events: Vec::new(),
833                         }),
834                         our_network_key: keys_manager.get_node_secret(),
835
836                         last_node_announcement_serial: AtomicUsize::new(0),
837
838                         per_peer_state: RwLock::new(HashMap::new()),
839
840                         pending_events: Mutex::new(Vec::new()),
841                         pending_background_events: Mutex::new(Vec::new()),
842                         total_consistency_lock: RwLock::new(()),
843                         persistence_notifier: PersistenceNotifier::new(),
844
845                         keys_manager,
846
847                         logger,
848                 }
849         }
850
851         /// Creates a new outbound channel to the given remote node and with the given value.
852         ///
853         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
854         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
855         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
856         /// may wish to avoid using 0 for user_id here.
857         ///
858         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
859         /// PeerManager::process_events afterwards.
860         ///
861         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
862         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
863         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64, override_config: Option<UserConfig>) -> Result<(), APIError> {
864                 if channel_value_satoshis < 1000 {
865                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
866                 }
867
868                 let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
869                 let channel = Channel::new_outbound(&self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, config)?;
870                 let res = channel.get_open_channel(self.genesis_hash.clone());
871
872                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
873                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
874                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
875
876                 let mut channel_state = self.channel_state.lock().unwrap();
877                 match channel_state.by_id.entry(channel.channel_id()) {
878                         hash_map::Entry::Occupied(_) => {
879                                 if cfg!(feature = "fuzztarget") {
880                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
881                                 } else {
882                                         panic!("RNG is bad???");
883                                 }
884                         },
885                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
886                 }
887                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
888                         node_id: their_network_key,
889                         msg: res,
890                 });
891                 Ok(())
892         }
893
894         fn list_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<Signer>)) -> bool>(&self, f: Fn) -> Vec<ChannelDetails> {
895                 let mut res = Vec::new();
896                 {
897                         let channel_state = self.channel_state.lock().unwrap();
898                         res.reserve(channel_state.by_id.len());
899                         for (channel_id, channel) in channel_state.by_id.iter().filter(f) {
900                                 let (inbound_capacity_msat, outbound_capacity_msat) = channel.get_inbound_outbound_available_balance_msat();
901                                 res.push(ChannelDetails {
902                                         channel_id: (*channel_id).clone(),
903                                         short_channel_id: channel.get_short_channel_id(),
904                                         remote_network_id: channel.get_counterparty_node_id(),
905                                         counterparty_features: InitFeatures::empty(),
906                                         channel_value_satoshis: channel.get_value_satoshis(),
907                                         inbound_capacity_msat,
908                                         outbound_capacity_msat,
909                                         user_id: channel.get_user_id(),
910                                         is_live: channel.is_live(),
911                                         counterparty_forwarding_info: channel.counterparty_forwarding_info(),
912                                 });
913                         }
914                 }
915                 let per_peer_state = self.per_peer_state.read().unwrap();
916                 for chan in res.iter_mut() {
917                         if let Some(peer_state) = per_peer_state.get(&chan.remote_network_id) {
918                                 chan.counterparty_features = peer_state.lock().unwrap().latest_features.clone();
919                         }
920                 }
921                 res
922         }
923
924         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
925         /// more information.
926         pub fn list_channels(&self) -> Vec<ChannelDetails> {
927                 self.list_channels_with_filter(|_| true)
928         }
929
930         /// Gets the list of usable channels, in random order. Useful as an argument to
931         /// get_route to ensure non-announced channels are used.
932         ///
933         /// These are guaranteed to have their is_live value set to true, see the documentation for
934         /// ChannelDetails::is_live for more info on exactly what the criteria are.
935         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
936                 // Note we use is_live here instead of usable which leads to somewhat confused
937                 // internal/external nomenclature, but that's ok cause that's probably what the user
938                 // really wanted anyway.
939                 self.list_channels_with_filter(|&(_, ref channel)| channel.is_live())
940         }
941
942         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
943         /// will be accepted on the given channel, and after additional timeout/the closing of all
944         /// pending HTLCs, the channel will be closed on chain.
945         ///
946         /// May generate a SendShutdown message event on success, which should be relayed.
947         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
948                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
949
950                 let (mut failed_htlcs, chan_option) = {
951                         let mut channel_state_lock = self.channel_state.lock().unwrap();
952                         let channel_state = &mut *channel_state_lock;
953                         match channel_state.by_id.entry(channel_id.clone()) {
954                                 hash_map::Entry::Occupied(mut chan_entry) => {
955                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
956                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
957                                                 node_id: chan_entry.get().get_counterparty_node_id(),
958                                                 msg: shutdown_msg
959                                         });
960                                         if chan_entry.get().is_shutdown() {
961                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
962                                                         channel_state.short_to_id.remove(&short_id);
963                                                 }
964                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
965                                         } else { (failed_htlcs, None) }
966                                 },
967                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()})
968                         }
969                 };
970                 for htlc_source in failed_htlcs.drain(..) {
971                         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() });
972                 }
973                 let chan_update = if let Some(chan) = chan_option {
974                         if let Ok(update) = self.get_channel_update(&chan) {
975                                 Some(update)
976                         } else { None }
977                 } else { None };
978
979                 if let Some(update) = chan_update {
980                         let mut channel_state = self.channel_state.lock().unwrap();
981                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
982                                 msg: update
983                         });
984                 }
985
986                 Ok(())
987         }
988
989         #[inline]
990         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
991                 let (monitor_update_option, mut failed_htlcs) = shutdown_res;
992                 log_trace!(self.logger, "Finishing force-closure of channel {} HTLCs to fail", failed_htlcs.len());
993                 for htlc_source in failed_htlcs.drain(..) {
994                         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() });
995                 }
996                 if let Some((funding_txo, monitor_update)) = monitor_update_option {
997                         // There isn't anything we can do if we get an update failure - we're already
998                         // force-closing. The monitor update on the required in-memory copy should broadcast
999                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
1000                         // ignore the result here.
1001                         let _ = self.chain_monitor.update_channel(funding_txo, monitor_update);
1002                 }
1003         }
1004
1005         fn force_close_channel_with_peer(&self, channel_id: &[u8; 32], peer_node_id: Option<&PublicKey>) -> Result<(), APIError> {
1006                 let mut chan = {
1007                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1008                         let channel_state = &mut *channel_state_lock;
1009                         if let hash_map::Entry::Occupied(chan) = channel_state.by_id.entry(channel_id.clone()) {
1010                                 if let Some(node_id) = peer_node_id {
1011                                         if chan.get().get_counterparty_node_id() != *node_id {
1012                                                 // Error or Ok here doesn't matter - the result is only exposed publicly
1013                                                 // when peer_node_id is None anyway.
1014                                                 return Ok(());
1015                                         }
1016                                 }
1017                                 if let Some(short_id) = chan.get().get_short_channel_id() {
1018                                         channel_state.short_to_id.remove(&short_id);
1019                                 }
1020                                 chan.remove_entry().1
1021                         } else {
1022                                 return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()});
1023                         }
1024                 };
1025                 log_trace!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
1026                 self.finish_force_close_channel(chan.force_shutdown(true));
1027                 if let Ok(update) = self.get_channel_update(&chan) {
1028                         let mut channel_state = self.channel_state.lock().unwrap();
1029                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1030                                 msg: update
1031                         });
1032                 }
1033
1034                 Ok(())
1035         }
1036
1037         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
1038         /// the chain and rejecting new HTLCs on the given channel. Fails if channel_id is unknown to the manager.
1039         pub fn force_close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
1040                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1041                 self.force_close_channel_with_peer(channel_id, None)
1042         }
1043
1044         /// Force close all channels, immediately broadcasting the latest local commitment transaction
1045         /// for each to the chain and rejecting new HTLCs on each.
1046         pub fn force_close_all_channels(&self) {
1047                 for chan in self.list_channels() {
1048                         let _ = self.force_close_channel(&chan.channel_id);
1049                 }
1050         }
1051
1052         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder<Signer>>) {
1053                 macro_rules! return_malformed_err {
1054                         ($msg: expr, $err_code: expr) => {
1055                                 {
1056                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
1057                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
1058                                                 channel_id: msg.channel_id,
1059                                                 htlc_id: msg.htlc_id,
1060                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
1061                                                 failure_code: $err_code,
1062                                         })), self.channel_state.lock().unwrap());
1063                                 }
1064                         }
1065                 }
1066
1067                 if let Err(_) = msg.onion_routing_packet.public_key {
1068                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
1069                 }
1070
1071                 let shared_secret = {
1072                         let mut arr = [0; 32];
1073                         arr.copy_from_slice(&SharedSecret::new(&msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
1074                         arr
1075                 };
1076                 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(&shared_secret);
1077
1078                 if msg.onion_routing_packet.version != 0 {
1079                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1080                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1081                         //the hash doesn't really serve any purpose - in the case of hashing all data, the
1082                         //receiving node would have to brute force to figure out which version was put in the
1083                         //packet by the node that send us the message, in the case of hashing the hop_data, the
1084                         //node knows the HMAC matched, so they already know what is there...
1085                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
1086                 }
1087
1088                 let mut hmac = HmacEngine::<Sha256>::new(&mu);
1089                 hmac.input(&msg.onion_routing_packet.hop_data);
1090                 hmac.input(&msg.payment_hash.0[..]);
1091                 if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
1092                         return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
1093                 }
1094
1095                 let mut channel_state = None;
1096                 macro_rules! return_err {
1097                         ($msg: expr, $err_code: expr, $data: expr) => {
1098                                 {
1099                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
1100                                         if channel_state.is_none() {
1101                                                 channel_state = Some(self.channel_state.lock().unwrap());
1102                                         }
1103                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1104                                                 channel_id: msg.channel_id,
1105                                                 htlc_id: msg.htlc_id,
1106                                                 reason: onion_utils::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1107                                         })), channel_state.unwrap());
1108                                 }
1109                         }
1110                 }
1111
1112                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1113                 let mut chacha_stream = ChaChaReader { chacha: &mut chacha, read: Cursor::new(&msg.onion_routing_packet.hop_data[..]) };
1114                 let (next_hop_data, next_hop_hmac) = {
1115                         match msgs::OnionHopData::read(&mut chacha_stream) {
1116                                 Err(err) => {
1117                                         let error_code = match err {
1118                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1119                                                 msgs::DecodeError::UnknownRequiredFeature|
1120                                                 msgs::DecodeError::InvalidValue|
1121                                                 msgs::DecodeError::ShortRead => 0x4000 | 22, // invalid_onion_payload
1122                                                 _ => 0x2000 | 2, // Should never happen
1123                                         };
1124                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1125                                 },
1126                                 Ok(msg) => {
1127                                         let mut hmac = [0; 32];
1128                                         if let Err(_) = chacha_stream.read_exact(&mut hmac[..]) {
1129                                                 return_err!("Unable to decode hop data", 0x4000 | 22, &[0;0]);
1130                                         }
1131                                         (msg, hmac)
1132                                 },
1133                         }
1134                 };
1135
1136                 let pending_forward_info = if next_hop_hmac == [0; 32] {
1137                                 #[cfg(test)]
1138                                 {
1139                                         // In tests, make sure that the initial onion pcket data is, at least, non-0.
1140                                         // We could do some fancy randomness test here, but, ehh, whatever.
1141                                         // This checks for the issue where you can calculate the path length given the
1142                                         // onion data as all the path entries that the originator sent will be here
1143                                         // as-is (and were originally 0s).
1144                                         // Of course reverse path calculation is still pretty easy given naive routing
1145                                         // algorithms, but this fixes the most-obvious case.
1146                                         let mut next_bytes = [0; 32];
1147                                         chacha_stream.read_exact(&mut next_bytes).unwrap();
1148                                         assert_ne!(next_bytes[..], [0; 32][..]);
1149                                         chacha_stream.read_exact(&mut next_bytes).unwrap();
1150                                         assert_ne!(next_bytes[..], [0; 32][..]);
1151                                 }
1152
1153                                 // OUR PAYMENT!
1154                                 // final_expiry_too_soon
1155                                 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure we have at least
1156                                 // HTLC_FAIL_BACK_BUFFER blocks to go.
1157                                 // Also, ensure that, in the case of an unknown payment hash, our payment logic has enough time to fail the HTLC backward
1158                                 // before our onchain logic triggers a channel closure (see HTLC_FAIL_BACK_BUFFER rational).
1159                                 if (msg.cltv_expiry as u64) <= self.latest_block_height.load(Ordering::Acquire) as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1 {
1160                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1161                                 }
1162                                 // final_incorrect_htlc_amount
1163                                 if next_hop_data.amt_to_forward > msg.amount_msat {
1164                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1165                                 }
1166                                 // final_incorrect_cltv_expiry
1167                                 if next_hop_data.outgoing_cltv_value != msg.cltv_expiry {
1168                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1169                                 }
1170
1171                                 let payment_data = match next_hop_data.format {
1172                                         msgs::OnionHopDataFormat::Legacy { .. } => None,
1173                                         msgs::OnionHopDataFormat::NonFinalNode { .. } => return_err!("Got non final data with an HMAC of 0", 0x4000 | 22, &[0;0]),
1174                                         msgs::OnionHopDataFormat::FinalNode { payment_data } => payment_data,
1175                                 };
1176
1177                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1178                                 // message, however that would leak that we are the recipient of this payment, so
1179                                 // instead we stay symmetric with the forwarding case, only responding (after a
1180                                 // delay) once they've send us a commitment_signed!
1181
1182                                 PendingHTLCStatus::Forward(PendingHTLCInfo {
1183                                         routing: PendingHTLCRouting::Receive {
1184                                                 payment_data,
1185                                                 incoming_cltv_expiry: msg.cltv_expiry,
1186                                         },
1187                                         payment_hash: msg.payment_hash.clone(),
1188                                         incoming_shared_secret: shared_secret,
1189                                         amt_to_forward: next_hop_data.amt_to_forward,
1190                                         outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1191                                 })
1192                         } else {
1193                                 let mut new_packet_data = [0; 20*65];
1194                                 let read_pos = chacha_stream.read(&mut new_packet_data).unwrap();
1195                                 #[cfg(debug_assertions)]
1196                                 {
1197                                         // Check two things:
1198                                         // a) that the behavior of our stream here will return Ok(0) even if the TLV
1199                                         //    read above emptied out our buffer and the unwrap() wont needlessly panic
1200                                         // b) that we didn't somehow magically end up with extra data.
1201                                         let mut t = [0; 1];
1202                                         debug_assert!(chacha_stream.read(&mut t).unwrap() == 0);
1203                                 }
1204                                 // Once we've emptied the set of bytes our peer gave us, encrypt 0 bytes until we
1205                                 // fill the onion hop data we'll forward to our next-hop peer.
1206                                 chacha_stream.chacha.process_in_place(&mut new_packet_data[read_pos..]);
1207
1208                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1209
1210                                 let blinding_factor = {
1211                                         let mut sha = Sha256::engine();
1212                                         sha.input(&new_pubkey.serialize()[..]);
1213                                         sha.input(&shared_secret);
1214                                         Sha256::from_engine(sha).into_inner()
1215                                 };
1216
1217                                 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor[..]) {
1218                                         Err(e)
1219                                 } else { Ok(new_pubkey) };
1220
1221                                 let outgoing_packet = msgs::OnionPacket {
1222                                         version: 0,
1223                                         public_key,
1224                                         hop_data: new_packet_data,
1225                                         hmac: next_hop_hmac.clone(),
1226                                 };
1227
1228                                 let short_channel_id = match next_hop_data.format {
1229                                         msgs::OnionHopDataFormat::Legacy { short_channel_id } => short_channel_id,
1230                                         msgs::OnionHopDataFormat::NonFinalNode { short_channel_id } => short_channel_id,
1231                                         msgs::OnionHopDataFormat::FinalNode { .. } => {
1232                                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0;0]);
1233                                         },
1234                                 };
1235
1236                                 PendingHTLCStatus::Forward(PendingHTLCInfo {
1237                                         routing: PendingHTLCRouting::Forward {
1238                                                 onion_packet: outgoing_packet,
1239                                                 short_channel_id,
1240                                         },
1241                                         payment_hash: msg.payment_hash.clone(),
1242                                         incoming_shared_secret: shared_secret,
1243                                         amt_to_forward: next_hop_data.amt_to_forward,
1244                                         outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1245                                 })
1246                         };
1247
1248                 channel_state = Some(self.channel_state.lock().unwrap());
1249                 if let &PendingHTLCStatus::Forward(PendingHTLCInfo { ref routing, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1250                         // If short_channel_id is 0 here, we'll reject the HTLC as there cannot be a channel
1251                         // with a short_channel_id of 0. This is important as various things later assume
1252                         // short_channel_id is non-0 in any ::Forward.
1253                         if let &PendingHTLCRouting::Forward { ref short_channel_id, .. } = routing {
1254                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1255                                 let forwarding_id = match id_option {
1256                                         None => { // unknown_next_peer
1257                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1258                                         },
1259                                         Some(id) => id.clone(),
1260                                 };
1261                                 if let Some((err, code, chan_update)) = loop {
1262                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1263
1264                                         // Note that we could technically not return an error yet here and just hope
1265                                         // that the connection is reestablished or monitor updated by the time we get
1266                                         // around to doing the actual forward, but better to fail early if we can and
1267                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1268                                         // on a small/per-node/per-channel scale.
1269                                         if !chan.is_live() { // channel_disabled
1270                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1271                                         }
1272                                         if *amt_to_forward < chan.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
1273                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1274                                         }
1275                                         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_holder_fee_base_msat(&self.fee_estimator) as u64) });
1276                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1277                                                 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())));
1278                                         }
1279                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + chan.get_cltv_expiry_delta() as u64 { // incorrect_cltv_expiry
1280                                                 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())));
1281                                         }
1282                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1283                                         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now, but we want to be robust wrt to counterparty
1284                                         // packet sanitization (see HTLC_FAIL_BACK_BUFFER rational)
1285                                         if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
1286                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1287                                         }
1288                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1289                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1290                                         }
1291                                         // In theory, we would be safe against unitentional channel-closure, if we only required a margin of LATENCY_GRACE_PERIOD_BLOCKS.
1292                                         // But, to be safe against policy reception, we use a longuer delay.
1293                                         if (*outgoing_cltv_value) as u64 <= (cur_height + HTLC_FAIL_BACK_BUFFER) as u64 {
1294                                                 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1295                                         }
1296
1297                                         break None;
1298                                 }
1299                                 {
1300                                         let mut res = Vec::with_capacity(8 + 128);
1301                                         if let Some(chan_update) = chan_update {
1302                                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1303                                                         res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1304                                                 }
1305                                                 else if code == 0x1000 | 13 {
1306                                                         res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1307                                                 }
1308                                                 else if code == 0x1000 | 20 {
1309                                                         // TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
1310                                                         res.extend_from_slice(&byte_utils::be16_to_array(0));
1311                                                 }
1312                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1313                                         }
1314                                         return_err!(err, code, &res[..]);
1315                                 }
1316                         }
1317                 }
1318
1319                 (pending_forward_info, channel_state.unwrap())
1320         }
1321
1322         /// only fails if the channel does not yet have an assigned short_id
1323         /// May be called with channel_state already locked!
1324         fn get_channel_update(&self, chan: &Channel<Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
1325                 let short_channel_id = match chan.get_short_channel_id() {
1326                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
1327                         Some(id) => id,
1328                 };
1329
1330                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_counterparty_node_id().serialize()[..];
1331
1332                 let unsigned = msgs::UnsignedChannelUpdate {
1333                         chain_hash: self.genesis_hash,
1334                         short_channel_id,
1335                         timestamp: chan.get_update_time_counter(),
1336                         flags: (!were_node_one) as u8 | ((!chan.is_live() as u8) << 1),
1337                         cltv_expiry_delta: chan.get_cltv_expiry_delta(),
1338                         htlc_minimum_msat: chan.get_counterparty_htlc_minimum_msat(),
1339                         htlc_maximum_msat: OptionalField::Present(chan.get_announced_htlc_max_msat()),
1340                         fee_base_msat: chan.get_holder_fee_base_msat(&self.fee_estimator),
1341                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1342                         excess_data: Vec::new(),
1343                 };
1344
1345                 let msg_hash = Sha256dHash::hash(&unsigned.encode()[..]);
1346                 let sig = self.secp_ctx.sign(&hash_to_message!(&msg_hash[..]), &self.our_network_key);
1347
1348                 Ok(msgs::ChannelUpdate {
1349                         signature: sig,
1350                         contents: unsigned
1351                 })
1352         }
1353
1354         // Only public for testing, this should otherwise never be called direcly
1355         pub(crate) fn send_payment_along_path(&self, path: &Vec<RouteHop>, payment_hash: &PaymentHash, payment_secret: &Option<PaymentSecret>, total_value: u64, cur_height: u32) -> Result<(), APIError> {
1356                 log_trace!(self.logger, "Attempting to send payment for path with next hop {}", path.first().unwrap().short_channel_id);
1357                 let prng_seed = self.keys_manager.get_secure_random_bytes();
1358                 let session_priv = SecretKey::from_slice(&self.keys_manager.get_secure_random_bytes()[..]).expect("RNG is busted");
1359
1360                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
1361                         .map_err(|_| APIError::RouteError{err: "Pubkey along hop was maliciously selected"})?;
1362                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, payment_secret, cur_height)?;
1363                 if onion_utils::route_size_insane(&onion_payloads) {
1364                         return Err(APIError::RouteError{err: "Route size too large considering onion data"});
1365                 }
1366                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash);
1367
1368                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1369
1370                 let err: Result<(), _> = loop {
1371                         let mut channel_lock = self.channel_state.lock().unwrap();
1372                         let id = match channel_lock.short_to_id.get(&path.first().unwrap().short_channel_id) {
1373                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
1374                                 Some(id) => id.clone(),
1375                         };
1376
1377                         let channel_state = &mut *channel_lock;
1378                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1379                                 match {
1380                                         if chan.get().get_counterparty_node_id() != path.first().unwrap().pubkey {
1381                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1382                                         }
1383                                         if !chan.get().is_live() {
1384                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!".to_owned()});
1385                                         }
1386                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1387                                                 path: path.clone(),
1388                                                 session_priv: session_priv.clone(),
1389                                                 first_hop_htlc_msat: htlc_msat,
1390                                         }, onion_packet, &self.logger), channel_state, chan)
1391                                 } {
1392                                         Some((update_add, commitment_signed, monitor_update)) => {
1393                                                 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
1394                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true);
1395                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1396                                                         // that we will resend the commitment update once monitor updating
1397                                                         // is restored. Therefore, we must return an error indicating that
1398                                                         // it is unsafe to retry the payment wholesale, which we do in the
1399                                                         // send_payment check for MonitorUpdateFailed, below.
1400                                                         return Err(APIError::MonitorUpdateFailed);
1401                                                 }
1402
1403                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1404                                                         node_id: path.first().unwrap().pubkey,
1405                                                         updates: msgs::CommitmentUpdate {
1406                                                                 update_add_htlcs: vec![update_add],
1407                                                                 update_fulfill_htlcs: Vec::new(),
1408                                                                 update_fail_htlcs: Vec::new(),
1409                                                                 update_fail_malformed_htlcs: Vec::new(),
1410                                                                 update_fee: None,
1411                                                                 commitment_signed,
1412                                                         },
1413                                                 });
1414                                         },
1415                                         None => {},
1416                                 }
1417                         } else { unreachable!(); }
1418                         return Ok(());
1419                 };
1420
1421                 match handle_error!(self, err, path.first().unwrap().pubkey) {
1422                         Ok(_) => unreachable!(),
1423                         Err(e) => {
1424                                 Err(APIError::ChannelUnavailable { err: e.err })
1425                         },
1426                 }
1427         }
1428
1429         /// Sends a payment along a given route.
1430         ///
1431         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1432         /// fields for more info.
1433         ///
1434         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1435         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1436         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1437         /// specified in the last hop in the route! Thus, you should probably do your own
1438         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1439         /// payment") and prevent double-sends yourself.
1440         ///
1441         /// May generate SendHTLCs message(s) event on success, which should be relayed.
1442         ///
1443         /// Each path may have a different return value, and PaymentSendValue may return a Vec with
1444         /// each entry matching the corresponding-index entry in the route paths, see
1445         /// PaymentSendFailure for more info.
1446         ///
1447         /// In general, a path may raise:
1448         ///  * APIError::RouteError when an invalid route or forwarding parameter (cltv_delta, fee,
1449         ///    node public key) is specified.
1450         ///  * APIError::ChannelUnavailable if the next-hop channel is not available for updates
1451         ///    (including due to previous monitor update failure or new permanent monitor update
1452         ///    failure).
1453         ///  * APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1454         ///    relevant updates.
1455         ///
1456         /// Note that depending on the type of the PaymentSendFailure the HTLC may have been
1457         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
1458         /// different route unless you intend to pay twice!
1459         ///
1460         /// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
1461         /// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
1462         /// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
1463         /// must not contain multiple paths as multi-path payments require a recipient-provided
1464         /// payment_secret.
1465         /// If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
1466         /// bit set (either as required or as available). If multiple paths are present in the Route,
1467         /// we assume the invoice had the basic_mpp feature set.
1468         pub fn send_payment(&self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>) -> Result<(), PaymentSendFailure> {
1469                 if route.paths.len() < 1 {
1470                         return Err(PaymentSendFailure::ParameterError(APIError::RouteError{err: "There must be at least one path to send over"}));
1471                 }
1472                 if route.paths.len() > 10 {
1473                         // This limit is completely arbitrary - there aren't any real fundamental path-count
1474                         // limits. After we support retrying individual paths we should likely bump this, but
1475                         // for now more than 10 paths likely carries too much one-path failure.
1476                         return Err(PaymentSendFailure::ParameterError(APIError::RouteError{err: "Sending over more than 10 paths is not currently supported"}));
1477                 }
1478                 let mut total_value = 0;
1479                 let our_node_id = self.get_our_node_id();
1480                 let mut path_errs = Vec::with_capacity(route.paths.len());
1481                 'path_check: for path in route.paths.iter() {
1482                         if path.len() < 1 || path.len() > 20 {
1483                                 path_errs.push(Err(APIError::RouteError{err: "Path didn't go anywhere/had bogus size"}));
1484                                 continue 'path_check;
1485                         }
1486                         for (idx, hop) in path.iter().enumerate() {
1487                                 if idx != path.len() - 1 && hop.pubkey == our_node_id {
1488                                         path_errs.push(Err(APIError::RouteError{err: "Path went through us but wasn't a simple rebalance loop to us"}));
1489                                         continue 'path_check;
1490                                 }
1491                         }
1492                         total_value += path.last().unwrap().fee_msat;
1493                         path_errs.push(Ok(()));
1494                 }
1495                 if path_errs.iter().any(|e| e.is_err()) {
1496                         return Err(PaymentSendFailure::PathParameterError(path_errs));
1497                 }
1498
1499                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1500                 let mut results = Vec::new();
1501                 for path in route.paths.iter() {
1502                         results.push(self.send_payment_along_path(&path, &payment_hash, payment_secret, total_value, cur_height));
1503                 }
1504                 let mut has_ok = false;
1505                 let mut has_err = false;
1506                 for res in results.iter() {
1507                         if res.is_ok() { has_ok = true; }
1508                         if res.is_err() { has_err = true; }
1509                         if let &Err(APIError::MonitorUpdateFailed) = res {
1510                                 // MonitorUpdateFailed is inherently unsafe to retry, so we call it a
1511                                 // PartialFailure.
1512                                 has_err = true;
1513                                 has_ok = true;
1514                                 break;
1515                         }
1516                 }
1517                 if has_err && has_ok {
1518                         Err(PaymentSendFailure::PartialFailure(results))
1519                 } else if has_err {
1520                         Err(PaymentSendFailure::AllFailedRetrySafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1521                 } else {
1522                         Ok(())
1523                 }
1524         }
1525
1526         /// Call this upon creation of a funding transaction for the given channel.
1527         ///
1528         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1529         /// or your counterparty can steal your funds!
1530         ///
1531         /// Panics if a funding transaction has already been provided for this channel.
1532         ///
1533         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1534         /// be trivially prevented by using unique funding transaction keys per-channel).
1535         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1536                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1537
1538                 let (chan, msg) = {
1539                         let (res, chan) = match self.channel_state.lock().unwrap().by_id.remove(temporary_channel_id) {
1540                                 Some(mut chan) => {
1541                                         (chan.get_outbound_funding_created(funding_txo, &self.logger)
1542                                                 .map_err(|e| if let ChannelError::Close(msg) = e {
1543                                                         MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(true), None)
1544                                                 } else { unreachable!(); })
1545                                         , chan)
1546                                 },
1547                                 None => return
1548                         };
1549                         match handle_error!(self, res, chan.get_counterparty_node_id()) {
1550                                 Ok(funding_msg) => {
1551                                         (chan, funding_msg)
1552                                 },
1553                                 Err(_) => { return; }
1554                         }
1555                 };
1556
1557                 let mut channel_state = self.channel_state.lock().unwrap();
1558                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1559                         node_id: chan.get_counterparty_node_id(),
1560                         msg,
1561                 });
1562                 match channel_state.by_id.entry(chan.channel_id()) {
1563                         hash_map::Entry::Occupied(_) => {
1564                                 panic!("Generated duplicate funding txid?");
1565                         },
1566                         hash_map::Entry::Vacant(e) => {
1567                                 e.insert(chan);
1568                         }
1569                 }
1570         }
1571
1572         fn get_announcement_sigs(&self, chan: &Channel<Signer>) -> Option<msgs::AnnouncementSignatures> {
1573                 if !chan.should_announce() {
1574                         log_trace!(self.logger, "Can't send announcement_signatures for private channel {}", log_bytes!(chan.channel_id()));
1575                         return None
1576                 }
1577
1578                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1579                         Ok(res) => res,
1580                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1581                 };
1582                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1583                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1584
1585                 Some(msgs::AnnouncementSignatures {
1586                         channel_id: chan.channel_id(),
1587                         short_channel_id: chan.get_short_channel_id().unwrap(),
1588                         node_signature: our_node_sig,
1589                         bitcoin_signature: our_bitcoin_sig,
1590                 })
1591         }
1592
1593         #[allow(dead_code)]
1594         // Messages of up to 64KB should never end up more than half full with addresses, as that would
1595         // be absurd. We ensure this by checking that at least 500 (our stated public contract on when
1596         // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
1597         // message...
1598         const HALF_MESSAGE_IS_ADDRS: u32 = ::std::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
1599         #[deny(const_err)]
1600         #[allow(dead_code)]
1601         // ...by failing to compile if the number of addresses that would be half of a message is
1602         // smaller than 500:
1603         const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 500;
1604
1605         /// Generates a signed node_announcement from the given arguments and creates a
1606         /// BroadcastNodeAnnouncement event. Note that such messages will be ignored unless peers have
1607         /// seen a channel_announcement from us (ie unless we have public channels open).
1608         ///
1609         /// RGB is a node "color" and alias is a printable human-readable string to describe this node
1610         /// to humans. They carry no in-protocol meaning.
1611         ///
1612         /// addresses represent the set (possibly empty) of socket addresses on which this node accepts
1613         /// incoming connections. These will be broadcast to the network, publicly tying these
1614         /// addresses together. If you wish to preserve user privacy, addresses should likely contain
1615         /// only Tor Onion addresses.
1616         ///
1617         /// Panics if addresses is absurdly large (more than 500).
1618         pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: Vec<NetAddress>) {
1619                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1620
1621                 if addresses.len() > 500 {
1622                         panic!("More than half the message size was taken up by public addresses!");
1623                 }
1624
1625                 let announcement = msgs::UnsignedNodeAnnouncement {
1626                         features: NodeFeatures::known(),
1627                         timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1628                         node_id: self.get_our_node_id(),
1629                         rgb, alias, addresses,
1630                         excess_address_data: Vec::new(),
1631                         excess_data: Vec::new(),
1632                 };
1633                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1634
1635                 let mut channel_state = self.channel_state.lock().unwrap();
1636                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
1637                         msg: msgs::NodeAnnouncement {
1638                                 signature: self.secp_ctx.sign(&msghash, &self.our_network_key),
1639                                 contents: announcement
1640                         },
1641                 });
1642         }
1643
1644         /// Processes HTLCs which are pending waiting on random forward delay.
1645         ///
1646         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
1647         /// Will likely generate further events.
1648         pub fn process_pending_htlc_forwards(&self) {
1649                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1650
1651                 let mut new_events = Vec::new();
1652                 let mut failed_forwards = Vec::new();
1653                 let mut handle_errors = Vec::new();
1654                 {
1655                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1656                         let channel_state = &mut *channel_state_lock;
1657
1658                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1659                                 if short_chan_id != 0 {
1660                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1661                                                 Some(chan_id) => chan_id.clone(),
1662                                                 None => {
1663                                                         failed_forwards.reserve(pending_forwards.len());
1664                                                         for forward_info in pending_forwards.drain(..) {
1665                                                                 match forward_info {
1666                                                                         HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info,
1667                                                                                                    prev_funding_outpoint } => {
1668                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1669                                                                                         short_channel_id: prev_short_channel_id,
1670                                                                                         outpoint: prev_funding_outpoint,
1671                                                                                         htlc_id: prev_htlc_id,
1672                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1673                                                                                 });
1674                                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash,
1675                                                                                         HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() }
1676                                                                                 ));
1677                                                                         },
1678                                                                         HTLCForwardInfo::FailHTLC { .. } => {
1679                                                                                 // Channel went away before we could fail it. This implies
1680                                                                                 // the channel is now on chain and our counterparty is
1681                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
1682                                                                                 // problem, not ours.
1683                                                                         }
1684                                                                 }
1685                                                         }
1686                                                         continue;
1687                                                 }
1688                                         };
1689                                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(forward_chan_id) {
1690                                                 let mut add_htlc_msgs = Vec::new();
1691                                                 let mut fail_htlc_msgs = Vec::new();
1692                                                 for forward_info in pending_forwards.drain(..) {
1693                                                         match forward_info {
1694                                                                 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1695                                                                                 routing: PendingHTLCRouting::Forward {
1696                                                                                         onion_packet, ..
1697                                                                                 }, incoming_shared_secret, payment_hash, amt_to_forward, outgoing_cltv_value },
1698                                                                                 prev_funding_outpoint } => {
1699                                                                         log_trace!(self.logger, "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);
1700                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1701                                                                                 short_channel_id: prev_short_channel_id,
1702                                                                                 outpoint: prev_funding_outpoint,
1703                                                                                 htlc_id: prev_htlc_id,
1704                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
1705                                                                         });
1706                                                                         match chan.get_mut().send_htlc(amt_to_forward, payment_hash, outgoing_cltv_value, htlc_source.clone(), onion_packet) {
1707                                                                                 Err(e) => {
1708                                                                                         if let ChannelError::Ignore(msg) = e {
1709                                                                                                 log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
1710                                                                                         } else {
1711                                                                                                 panic!("Stated return value requirements in send_htlc() were not met");
1712                                                                                         }
1713                                                                                         let chan_update = self.get_channel_update(chan.get()).unwrap();
1714                                                                                         failed_forwards.push((htlc_source, payment_hash,
1715                                                                                                 HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.encode_with_len() }
1716                                                                                         ));
1717                                                                                         continue;
1718                                                                                 },
1719                                                                                 Ok(update_add) => {
1720                                                                                         match update_add {
1721                                                                                                 Some(msg) => { add_htlc_msgs.push(msg); },
1722                                                                                                 None => {
1723                                                                                                         // Nothing to do here...we're waiting on a remote
1724                                                                                                         // revoke_and_ack before we can add anymore HTLCs. The Channel
1725                                                                                                         // will automatically handle building the update_add_htlc and
1726                                                                                                         // commitment_signed messages when we can.
1727                                                                                                         // TODO: Do some kind of timer to set the channel as !is_live()
1728                                                                                                         // as we don't really want others relying on us relaying through
1729                                                                                                         // this channel currently :/.
1730                                                                                                 }
1731                                                                                         }
1732                                                                                 }
1733                                                                         }
1734                                                                 },
1735                                                                 HTLCForwardInfo::AddHTLC { .. } => {
1736                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
1737                                                                 },
1738                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
1739                                                                         log_trace!(self.logger, "Failing HTLC back to channel with short id {} after delay", short_chan_id);
1740                                                                         match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet) {
1741                                                                                 Err(e) => {
1742                                                                                         if let ChannelError::Ignore(msg) = e {
1743                                                                                                 log_trace!(self.logger, "Failed to fail backwards to short_id {}: {}", short_chan_id, msg);
1744                                                                                         } else {
1745                                                                                                 panic!("Stated return value requirements in get_update_fail_htlc() were not met");
1746                                                                                         }
1747                                                                                         // fail-backs are best-effort, we probably already have one
1748                                                                                         // pending, and if not that's OK, if not, the channel is on
1749                                                                                         // the chain and sending the HTLC-Timeout is their problem.
1750                                                                                         continue;
1751                                                                                 },
1752                                                                                 Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
1753                                                                                 Ok(None) => {
1754                                                                                         // Nothing to do here...we're waiting on a remote
1755                                                                                         // revoke_and_ack before we can update the commitment
1756                                                                                         // transaction. The Channel will automatically handle
1757                                                                                         // building the update_fail_htlc and commitment_signed
1758                                                                                         // messages when we can.
1759                                                                                         // We don't need any kind of timer here as they should fail
1760                                                                                         // the channel onto the chain if they can't get our
1761                                                                                         // update_fail_htlc in time, it's not our problem.
1762                                                                                 }
1763                                                                         }
1764                                                                 },
1765                                                         }
1766                                                 }
1767
1768                                                 if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
1769                                                         let (commitment_msg, monitor_update) = match chan.get_mut().send_commitment(&self.logger) {
1770                                                                 Ok(res) => res,
1771                                                                 Err(e) => {
1772                                                                         // We surely failed send_commitment due to bad keys, in that case
1773                                                                         // close channel and then send error message to peer.
1774                                                                         let counterparty_node_id = chan.get().get_counterparty_node_id();
1775                                                                         let err: Result<(), _>  = match e {
1776                                                                                 ChannelError::Ignore(_) => {
1777                                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1778                                                                                 },
1779                                                                                 ChannelError::Close(msg) => {
1780                                                                                         log_trace!(self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
1781                                                                                         let (channel_id, mut channel) = chan.remove_entry();
1782                                                                                         if let Some(short_id) = channel.get_short_channel_id() {
1783                                                                                                 channel_state.short_to_id.remove(&short_id);
1784                                                                                         }
1785                                                                                         Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, channel.force_shutdown(true), self.get_channel_update(&channel).ok()))
1786                                                                                 },
1787                                                                                 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"); }
1788                                                                         };
1789                                                                         handle_errors.push((counterparty_node_id, err));
1790                                                                         continue;
1791                                                                 }
1792                                                         };
1793                                                         if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
1794                                                                 handle_errors.push((chan.get().get_counterparty_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
1795                                                                 continue;
1796                                                         }
1797                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1798                                                                 node_id: chan.get().get_counterparty_node_id(),
1799                                                                 updates: msgs::CommitmentUpdate {
1800                                                                         update_add_htlcs: add_htlc_msgs,
1801                                                                         update_fulfill_htlcs: Vec::new(),
1802                                                                         update_fail_htlcs: fail_htlc_msgs,
1803                                                                         update_fail_malformed_htlcs: Vec::new(),
1804                                                                         update_fee: None,
1805                                                                         commitment_signed: commitment_msg,
1806                                                                 },
1807                                                         });
1808                                                 }
1809                                         } else {
1810                                                 unreachable!();
1811                                         }
1812                                 } else {
1813                                         for forward_info in pending_forwards.drain(..) {
1814                                                 match forward_info {
1815                                                         HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1816                                                                         routing: PendingHTLCRouting::Receive { payment_data, incoming_cltv_expiry },
1817                                                                         incoming_shared_secret, payment_hash, amt_to_forward, .. },
1818                                                                         prev_funding_outpoint } => {
1819                                                                 let prev_hop = HTLCPreviousHopData {
1820                                                                         short_channel_id: prev_short_channel_id,
1821                                                                         outpoint: prev_funding_outpoint,
1822                                                                         htlc_id: prev_htlc_id,
1823                                                                         incoming_packet_shared_secret: incoming_shared_secret,
1824                                                                 };
1825
1826                                                                 let mut total_value = 0;
1827                                                                 let payment_secret_opt =
1828                                                                         if let &Some(ref data) = &payment_data { Some(data.payment_secret.clone()) } else { None };
1829                                                                 let htlcs = channel_state.claimable_htlcs.entry((payment_hash, payment_secret_opt))
1830                                                                         .or_insert(Vec::new());
1831                                                                 htlcs.push(ClaimableHTLC {
1832                                                                         prev_hop,
1833                                                                         value: amt_to_forward,
1834                                                                         payment_data: payment_data.clone(),
1835                                                                         cltv_expiry: incoming_cltv_expiry,
1836                                                                 });
1837                                                                 if let &Some(ref data) = &payment_data {
1838                                                                         for htlc in htlcs.iter() {
1839                                                                                 total_value += htlc.value;
1840                                                                                 if htlc.payment_data.as_ref().unwrap().total_msat != data.total_msat {
1841                                                                                         total_value = msgs::MAX_VALUE_MSAT;
1842                                                                                 }
1843                                                                                 if total_value >= msgs::MAX_VALUE_MSAT { break; }
1844                                                                         }
1845                                                                         if total_value >= msgs::MAX_VALUE_MSAT || total_value > data.total_msat  {
1846                                                                                 for htlc in htlcs.iter() {
1847                                                                                         let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
1848                                                                                         htlc_msat_height_data.extend_from_slice(
1849                                                                                                 &byte_utils::be32_to_array(
1850                                                                                                         self.latest_block_height.load(Ordering::Acquire)
1851                                                                                                                 as u32,
1852                                                                                                 ),
1853                                                                                         );
1854                                                                                         failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
1855                                                                                                         short_channel_id: htlc.prev_hop.short_channel_id,
1856                                                                                                         outpoint: prev_funding_outpoint,
1857                                                                                                         htlc_id: htlc.prev_hop.htlc_id,
1858                                                                                                         incoming_packet_shared_secret: htlc.prev_hop.incoming_packet_shared_secret,
1859                                                                                                 }), payment_hash,
1860                                                                                                 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data }
1861                                                                                         ));
1862                                                                                 }
1863                                                                         } else if total_value == data.total_msat {
1864                                                                                 new_events.push(events::Event::PaymentReceived {
1865                                                                                         payment_hash,
1866                                                                                         payment_secret: Some(data.payment_secret),
1867                                                                                         amt: total_value,
1868                                                                                 });
1869                                                                         }
1870                                                                 } else {
1871                                                                         new_events.push(events::Event::PaymentReceived {
1872                                                                                 payment_hash,
1873                                                                                 payment_secret: None,
1874                                                                                 amt: amt_to_forward,
1875                                                                         });
1876                                                                 }
1877                                                         },
1878                                                         HTLCForwardInfo::AddHTLC { .. } => {
1879                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
1880                                                         },
1881                                                         HTLCForwardInfo::FailHTLC { .. } => {
1882                                                                 panic!("Got pending fail of our own HTLC");
1883                                                         }
1884                                                 }
1885                                         }
1886                                 }
1887                         }
1888                 }
1889
1890                 for (htlc_source, payment_hash, failure_reason) in failed_forwards.drain(..) {
1891                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, failure_reason);
1892                 }
1893
1894                 for (counterparty_node_id, err) in handle_errors.drain(..) {
1895                         let _ = handle_error!(self, err, counterparty_node_id);
1896                 }
1897
1898                 if new_events.is_empty() { return }
1899                 let mut events = self.pending_events.lock().unwrap();
1900                 events.append(&mut new_events);
1901         }
1902
1903         /// Free the background events, generally called from timer_chan_freshness_every_min.
1904         ///
1905         /// Exposed for testing to allow us to process events quickly without generating accidental
1906         /// BroadcastChannelUpdate events in timer_chan_freshness_every_min.
1907         ///
1908         /// Expects the caller to have a total_consistency_lock read lock.
1909         fn process_background_events(&self) {
1910                 let mut background_events = Vec::new();
1911                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
1912                 for event in background_events.drain(..) {
1913                         match event {
1914                                 BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)) => {
1915                                         // The channel has already been closed, so no use bothering to care about the
1916                                         // monitor updating completing.
1917                                         let _ = self.chain_monitor.update_channel(funding_txo, update);
1918                                 },
1919                         }
1920                 }
1921         }
1922
1923         #[cfg(any(test, feature = "_test_utils"))]
1924         pub(crate) fn test_process_background_events(&self) {
1925                 self.process_background_events();
1926         }
1927
1928         /// If a peer is disconnected we mark any channels with that peer as 'disabled'.
1929         /// After some time, if channels are still disabled we need to broadcast a ChannelUpdate
1930         /// to inform the network about the uselessness of these channels.
1931         ///
1932         /// This method handles all the details, and must be called roughly once per minute.
1933         ///
1934         /// Note that in some rare cases this may generate a `chain::Watch::update_channel` call.
1935         pub fn timer_chan_freshness_every_min(&self) {
1936                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1937                 self.process_background_events();
1938
1939                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1940                 let channel_state = &mut *channel_state_lock;
1941                 for (_, chan) in channel_state.by_id.iter_mut() {
1942                         if chan.is_disabled_staged() && !chan.is_live() {
1943                                 if let Ok(update) = self.get_channel_update(&chan) {
1944                                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1945                                                 msg: update
1946                                         });
1947                                 }
1948                                 chan.to_fresh();
1949                         } else if chan.is_disabled_staged() && chan.is_live() {
1950                                 chan.to_fresh();
1951                         } else if chan.is_disabled_marked() {
1952                                 chan.to_disabled_staged();
1953                         }
1954                 }
1955         }
1956
1957         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1958         /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
1959         /// along the path (including in our own channel on which we received it).
1960         /// Returns false if no payment was found to fail backwards, true if the process of failing the
1961         /// HTLC backwards has been started.
1962         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, payment_secret: &Option<PaymentSecret>) -> bool {
1963                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1964
1965                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1966                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(*payment_hash, *payment_secret));
1967                 if let Some(mut sources) = removed_source {
1968                         for htlc in sources.drain(..) {
1969                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1970                                 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
1971                                 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
1972                                         self.latest_block_height.load(Ordering::Acquire) as u32,
1973                                 ));
1974                                 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1975                                                 HTLCSource::PreviousHopData(htlc.prev_hop), payment_hash,
1976                                                 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data });
1977                         }
1978                         true
1979                 } else { false }
1980         }
1981
1982         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
1983         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
1984         // be surfaced to the user.
1985         fn fail_holding_cell_htlcs(&self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: [u8; 32]) {
1986                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
1987                         match htlc_src {
1988                                 HTLCSource::PreviousHopData(HTLCPreviousHopData { .. }) => {
1989                                         let (failure_code, onion_failure_data) =
1990                                                 match self.channel_state.lock().unwrap().by_id.entry(channel_id) {
1991                                                         hash_map::Entry::Occupied(chan_entry) => {
1992                                                                 if let Ok(upd) = self.get_channel_update(&chan_entry.get()) {
1993                                                                         (0x1000|7, upd.encode_with_len())
1994                                                                 } else {
1995                                                                         (0x4000|10, Vec::new())
1996                                                                 }
1997                                                         },
1998                                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
1999                                                 };
2000                                         let channel_state = self.channel_state.lock().unwrap();
2001                                         self.fail_htlc_backwards_internal(channel_state,
2002                                                 htlc_src, &payment_hash, HTLCFailReason::Reason { failure_code, data: onion_failure_data});
2003                                 },
2004                                 HTLCSource::OutboundRoute { .. } => {
2005                                         self.pending_events.lock().unwrap().push(
2006                                                 events::Event::PaymentFailed {
2007                                                         payment_hash,
2008                                                         rejected_by_dest: false,
2009 #[cfg(test)]
2010                                                         error_code: None,
2011 #[cfg(test)]
2012                                                         error_data: None,
2013                                                 }
2014                                         )
2015                                 },
2016                         };
2017                 }
2018         }
2019
2020         /// Fails an HTLC backwards to the sender of it to us.
2021         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
2022         /// There are several callsites that do stupid things like loop over a list of payment_hashes
2023         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
2024         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
2025         /// still-available channels.
2026         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
2027                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
2028                 //identify whether we sent it or not based on the (I presume) very different runtime
2029                 //between the branches here. We should make this async and move it into the forward HTLCs
2030                 //timer handling.
2031
2032                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
2033                 // from block_connected which may run during initialization prior to the chain_monitor
2034                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
2035                 match source {
2036                         HTLCSource::OutboundRoute { ref path, .. } => {
2037                                 log_trace!(self.logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
2038                                 mem::drop(channel_state_lock);
2039                                 match &onion_error {
2040                                         &HTLCFailReason::LightningError { ref err } => {
2041 #[cfg(test)]
2042                                                 let (channel_update, payment_retryable, onion_error_code, onion_error_data) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
2043 #[cfg(not(test))]
2044                                                 let (channel_update, payment_retryable, _, _) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
2045                                                 // TODO: If we decided to blame ourselves (or one of our channels) in
2046                                                 // process_onion_failure we should close that channel as it implies our
2047                                                 // next-hop is needlessly blaming us!
2048                                                 if let Some(update) = channel_update {
2049                                                         self.channel_state.lock().unwrap().pending_msg_events.push(
2050                                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate {
2051                                                                         update,
2052                                                                 }
2053                                                         );
2054                                                 }
2055                                                 self.pending_events.lock().unwrap().push(
2056                                                         events::Event::PaymentFailed {
2057                                                                 payment_hash: payment_hash.clone(),
2058                                                                 rejected_by_dest: !payment_retryable,
2059 #[cfg(test)]
2060                                                                 error_code: onion_error_code,
2061 #[cfg(test)]
2062                                                                 error_data: onion_error_data
2063                                                         }
2064                                                 );
2065                                         },
2066                                         &HTLCFailReason::Reason {
2067 #[cfg(test)]
2068                                                         ref failure_code,
2069 #[cfg(test)]
2070                                                         ref data,
2071                                                         .. } => {
2072                                                 // we get a fail_malformed_htlc from the first hop
2073                                                 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
2074                                                 // failures here, but that would be insufficient as get_route
2075                                                 // generally ignores its view of our own channels as we provide them via
2076                                                 // ChannelDetails.
2077                                                 // TODO: For non-temporary failures, we really should be closing the
2078                                                 // channel here as we apparently can't relay through them anyway.
2079                                                 self.pending_events.lock().unwrap().push(
2080                                                         events::Event::PaymentFailed {
2081                                                                 payment_hash: payment_hash.clone(),
2082                                                                 rejected_by_dest: path.len() == 1,
2083 #[cfg(test)]
2084                                                                 error_code: Some(*failure_code),
2085 #[cfg(test)]
2086                                                                 error_data: Some(data.clone()),
2087                                                         }
2088                                                 );
2089                                         }
2090                                 }
2091                         },
2092                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret, .. }) => {
2093                                 let err_packet = match onion_error {
2094                                         HTLCFailReason::Reason { failure_code, data } => {
2095                                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
2096                                                 let packet = onion_utils::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
2097                                                 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
2098                                         },
2099                                         HTLCFailReason::LightningError { err } => {
2100                                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards with pre-built LightningError", log_bytes!(payment_hash.0));
2101                                                 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
2102                                         }
2103                                 };
2104
2105                                 let mut forward_event = None;
2106                                 if channel_state_lock.forward_htlcs.is_empty() {
2107                                         forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
2108                                 }
2109                                 match channel_state_lock.forward_htlcs.entry(short_channel_id) {
2110                                         hash_map::Entry::Occupied(mut entry) => {
2111                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id, err_packet });
2112                                         },
2113                                         hash_map::Entry::Vacant(entry) => {
2114                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id, err_packet }));
2115                                         }
2116                                 }
2117                                 mem::drop(channel_state_lock);
2118                                 if let Some(time) = forward_event {
2119                                         let mut pending_events = self.pending_events.lock().unwrap();
2120                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2121                                                 time_forwardable: time
2122                                         });
2123                                 }
2124                         },
2125                 }
2126         }
2127
2128         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
2129         /// generating message events for the net layer to claim the payment, if possible. Thus, you
2130         /// should probably kick the net layer to go send messages if this returns true!
2131         ///
2132         /// You must specify the expected amounts for this HTLC, and we will only claim HTLCs
2133         /// available within a few percent of the expected amount. This is critical for several
2134         /// reasons : a) it avoids providing senders with `proof-of-payment` (in the form of the
2135         /// payment_preimage without having provided the full value and b) it avoids certain
2136         /// privacy-breaking recipient-probing attacks which may reveal payment activity to
2137         /// motivated attackers.
2138         ///
2139         /// Note that the privacy concerns in (b) are not relevant in payments with a payment_secret
2140         /// set. Thus, for such payments we will claim any payments which do not under-pay.
2141         ///
2142         /// May panic if called except in response to a PaymentReceived event.
2143         pub fn claim_funds(&self, payment_preimage: PaymentPreimage, payment_secret: &Option<PaymentSecret>, expected_amount: u64) -> bool {
2144                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
2145
2146                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
2147
2148                 let mut channel_state = Some(self.channel_state.lock().unwrap());
2149                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(payment_hash, *payment_secret));
2150                 if let Some(mut sources) = removed_source {
2151                         assert!(!sources.is_empty());
2152
2153                         // If we are claiming an MPP payment, we have to take special care to ensure that each
2154                         // channel exists before claiming all of the payments (inside one lock).
2155                         // Note that channel existance is sufficient as we should always get a monitor update
2156                         // which will take care of the real HTLC claim enforcement.
2157                         //
2158                         // If we find an HTLC which we would need to claim but for which we do not have a
2159                         // channel, we will fail all parts of the MPP payment. While we could wait and see if
2160                         // the sender retries the already-failed path(s), it should be a pretty rare case where
2161                         // we got all the HTLCs and then a channel closed while we were waiting for the user to
2162                         // provide the preimage, so worrying too much about the optimal handling isn't worth
2163                         // it.
2164
2165                         let (is_mpp, mut valid_mpp) = if let &Some(ref data) = &sources[0].payment_data {
2166                                 assert!(payment_secret.is_some());
2167                                 (true, data.total_msat >= expected_amount)
2168                         } else {
2169                                 assert!(payment_secret.is_none());
2170                                 (false, false)
2171                         };
2172
2173                         for htlc in sources.iter() {
2174                                 if !is_mpp || !valid_mpp { break; }
2175                                 if let None = channel_state.as_ref().unwrap().short_to_id.get(&htlc.prev_hop.short_channel_id) {
2176                                         valid_mpp = false;
2177                                 }
2178                         }
2179
2180                         let mut errs = Vec::new();
2181                         let mut claimed_any_htlcs = false;
2182                         for htlc in sources.drain(..) {
2183                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
2184                                 if (is_mpp && !valid_mpp) || (!is_mpp && (htlc.value < expected_amount || htlc.value > expected_amount * 2)) {
2185                                         let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
2186                                         htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
2187                                                 self.latest_block_height.load(Ordering::Acquire) as u32,
2188                                         ));
2189                                         self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
2190                                                                          HTLCSource::PreviousHopData(htlc.prev_hop), &payment_hash,
2191                                                                          HTLCFailReason::Reason { failure_code: 0x4000|15, data: htlc_msat_height_data });
2192                                 } else {
2193                                         match self.claim_funds_from_hop(channel_state.as_mut().unwrap(), htlc.prev_hop, payment_preimage) {
2194                                                 Err(Some(e)) => {
2195                                                         if let msgs::ErrorAction::IgnoreError = e.1.err.action {
2196                                                                 // We got a temporary failure updating monitor, but will claim the
2197                                                                 // HTLC when the monitor updating is restored (or on chain).
2198                                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", e.1.err.err);
2199                                                                 claimed_any_htlcs = true;
2200                                                         } else { errs.push(e); }
2201                                                 },
2202                                                 Err(None) if is_mpp => unreachable!("We already checked for channel existence, we can't fail here!"),
2203                                                 Err(None) => {
2204                                                         log_warn!(self.logger, "Channel we expected to claim an HTLC from was closed.");
2205                                                 },
2206                                                 Ok(()) => claimed_any_htlcs = true,
2207                                         }
2208                                 }
2209                         }
2210
2211                         // Now that we've done the entire above loop in one lock, we can handle any errors
2212                         // which were generated.
2213                         channel_state.take();
2214
2215                         for (counterparty_node_id, err) in errs.drain(..) {
2216                                 let res: Result<(), _> = Err(err);
2217                                 let _ = handle_error!(self, res, counterparty_node_id);
2218                         }
2219
2220                         claimed_any_htlcs
2221                 } else { false }
2222         }
2223
2224         fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard<ChannelHolder<Signer>>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> Result<(), Option<(PublicKey, MsgHandleErrInternal)>> {
2225                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
2226                 let channel_state = &mut **channel_state_lock;
2227                 let chan_id = match channel_state.short_to_id.get(&prev_hop.short_channel_id) {
2228                         Some(chan_id) => chan_id.clone(),
2229                         None => {
2230                                 return Err(None)
2231                         }
2232                 };
2233
2234                 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(chan_id) {
2235                         let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2236                         match chan.get_mut().get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger) {
2237                                 Ok((msgs, monitor_option)) => {
2238                                         if let Some(monitor_update) = monitor_option {
2239                                                 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2240                                                         if was_frozen_for_monitor {
2241                                                                 assert!(msgs.is_none());
2242                                                         } else {
2243                                                                 return Err(Some((chan.get().get_counterparty_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, msgs.is_some()).unwrap_err())));
2244                                                         }
2245                                                 }
2246                                         }
2247                                         if let Some((msg, commitment_signed)) = msgs {
2248                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2249                                                         node_id: chan.get().get_counterparty_node_id(),
2250                                                         updates: msgs::CommitmentUpdate {
2251                                                                 update_add_htlcs: Vec::new(),
2252                                                                 update_fulfill_htlcs: vec![msg],
2253                                                                 update_fail_htlcs: Vec::new(),
2254                                                                 update_fail_malformed_htlcs: Vec::new(),
2255                                                                 update_fee: None,
2256                                                                 commitment_signed,
2257                                                         }
2258                                                 });
2259                                         }
2260                                         return Ok(())
2261                                 },
2262                                 Err(e) => {
2263                                         // TODO: Do something with e?
2264                                         // This should only occur if we are claiming an HTLC at the same time as the
2265                                         // HTLC is being failed (eg because a block is being connected and this caused
2266                                         // an HTLC to time out). This should, of course, only occur if the user is the
2267                                         // one doing the claiming (as it being a part of a peer claim would imply we're
2268                                         // about to lose funds) and only if the lock in claim_funds was dropped as a
2269                                         // previous HTLC was failed (thus not for an MPP payment).
2270                                         debug_assert!(false, "This shouldn't be reachable except in absurdly rare cases between monitor updates and HTLC timeouts: {:?}", e);
2271                                         return Err(None)
2272                                 },
2273                         }
2274                 } else { unreachable!(); }
2275         }
2276
2277         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_preimage: PaymentPreimage) {
2278                 match source {
2279                         HTLCSource::OutboundRoute { .. } => {
2280                                 mem::drop(channel_state_lock);
2281                                 let mut pending_events = self.pending_events.lock().unwrap();
2282                                 pending_events.push(events::Event::PaymentSent {
2283                                         payment_preimage
2284                                 });
2285                         },
2286                         HTLCSource::PreviousHopData(hop_data) => {
2287                                 let prev_outpoint = hop_data.outpoint;
2288                                 if let Err((counterparty_node_id, err)) = match self.claim_funds_from_hop(&mut channel_state_lock, hop_data, payment_preimage) {
2289                                         Ok(()) => Ok(()),
2290                                         Err(None) => {
2291                                                 let preimage_update = ChannelMonitorUpdate {
2292                                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
2293                                                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
2294                                                                 payment_preimage: payment_preimage.clone(),
2295                                                         }],
2296                                                 };
2297                                                 // We update the ChannelMonitor on the backward link, after
2298                                                 // receiving an offchain preimage event from the forward link (the
2299                                                 // event being update_fulfill_htlc).
2300                                                 if let Err(e) = self.chain_monitor.update_channel(prev_outpoint, preimage_update) {
2301                                                         log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
2302                                                                    payment_preimage, e);
2303                                                 }
2304                                                 Ok(())
2305                                         },
2306                                         Err(Some(res)) => Err(res),
2307                                 } {
2308                                         mem::drop(channel_state_lock);
2309                                         let res: Result<(), _> = Err(err);
2310                                         let _ = handle_error!(self, res, counterparty_node_id);
2311                                 }
2312                         },
2313                 }
2314         }
2315
2316         /// Gets the node_id held by this ChannelManager
2317         pub fn get_our_node_id(&self) -> PublicKey {
2318                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
2319         }
2320
2321         /// Restores a single, given channel to normal operation after a
2322         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
2323         /// operation.
2324         ///
2325         /// All ChannelMonitor updates up to and including highest_applied_update_id must have been
2326         /// fully committed in every copy of the given channels' ChannelMonitors.
2327         ///
2328         /// Note that there is no effect to calling with a highest_applied_update_id other than the
2329         /// current latest ChannelMonitorUpdate and one call to this function after multiple
2330         /// ChannelMonitorUpdateErr::TemporaryFailures is fine. The highest_applied_update_id field
2331         /// exists largely only to prevent races between this and concurrent update_monitor calls.
2332         ///
2333         /// Thus, the anticipated use is, at a high level:
2334         ///  1) You register a chain::Watch with this ChannelManager,
2335         ///  2) it stores each update to disk, and begins updating any remote (eg watchtower) copies of
2336         ///     said ChannelMonitors as it can, returning ChannelMonitorUpdateErr::TemporaryFailures
2337         ///     any time it cannot do so instantly,
2338         ///  3) update(s) are applied to each remote copy of a ChannelMonitor,
2339         ///  4) once all remote copies are updated, you call this function with the update_id that
2340         ///     completed, and once it is the latest the Channel will be re-enabled.
2341         pub fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64) {
2342                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
2343
2344                 let mut close_results = Vec::new();
2345                 let mut htlc_forwards = Vec::new();
2346                 let mut htlc_failures = Vec::new();
2347                 let mut pending_events = Vec::new();
2348
2349                 {
2350                         let mut channel_lock = self.channel_state.lock().unwrap();
2351                         let channel_state = &mut *channel_lock;
2352                         let short_to_id = &mut channel_state.short_to_id;
2353                         let pending_msg_events = &mut channel_state.pending_msg_events;
2354                         let channel = match channel_state.by_id.get_mut(&funding_txo.to_channel_id()) {
2355                                 Some(chan) => chan,
2356                                 None => return,
2357                         };
2358                         if !channel.is_awaiting_monitor_update() || channel.get_latest_monitor_update_id() != highest_applied_update_id {
2359                                 return;
2360                         }
2361
2362                         let (raa, commitment_update, order, pending_forwards, mut pending_failures, needs_broadcast_safe, funding_locked) = channel.monitor_updating_restored(&self.logger);
2363                         if !pending_forwards.is_empty() {
2364                                 htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), funding_txo.clone(), pending_forwards));
2365                         }
2366                         htlc_failures.append(&mut pending_failures);
2367
2368                         macro_rules! handle_cs { () => {
2369                                 if let Some(update) = commitment_update {
2370                                         pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2371                                                 node_id: channel.get_counterparty_node_id(),
2372                                                 updates: update,
2373                                         });
2374                                 }
2375                         } }
2376                         macro_rules! handle_raa { () => {
2377                                 if let Some(revoke_and_ack) = raa {
2378                                         pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2379                                                 node_id: channel.get_counterparty_node_id(),
2380                                                 msg: revoke_and_ack,
2381                                         });
2382                                 }
2383                         } }
2384                         match order {
2385                                 RAACommitmentOrder::CommitmentFirst => {
2386                                         handle_cs!();
2387                                         handle_raa!();
2388                                 },
2389                                 RAACommitmentOrder::RevokeAndACKFirst => {
2390                                         handle_raa!();
2391                                         handle_cs!();
2392                                 },
2393                         }
2394                         if needs_broadcast_safe {
2395                                 pending_events.push(events::Event::FundingBroadcastSafe {
2396                                         funding_txo: channel.get_funding_txo().unwrap(),
2397                                         user_channel_id: channel.get_user_id(),
2398                                 });
2399                         }
2400                         if let Some(msg) = funding_locked {
2401                                 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2402                                         node_id: channel.get_counterparty_node_id(),
2403                                         msg,
2404                                 });
2405                                 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2406                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2407                                                 node_id: channel.get_counterparty_node_id(),
2408                                                 msg: announcement_sigs,
2409                                         });
2410                                 }
2411                                 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2412                         }
2413                 }
2414
2415                 self.pending_events.lock().unwrap().append(&mut pending_events);
2416
2417                 for failure in htlc_failures.drain(..) {
2418                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2419                 }
2420                 self.forward_htlcs(&mut htlc_forwards[..]);
2421
2422                 for res in close_results.drain(..) {
2423                         self.finish_force_close_channel(res);
2424                 }
2425         }
2426
2427         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
2428                 if msg.chain_hash != self.genesis_hash {
2429                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
2430                 }
2431
2432                 let channel = Channel::new_from_req(&self.fee_estimator, &self.keys_manager, counterparty_node_id.clone(), their_features, msg, 0, &self.default_configuration)
2433                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
2434                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2435                 let channel_state = &mut *channel_state_lock;
2436                 match channel_state.by_id.entry(channel.channel_id()) {
2437                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!".to_owned(), msg.temporary_channel_id.clone())),
2438                         hash_map::Entry::Vacant(entry) => {
2439                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
2440                                         node_id: counterparty_node_id.clone(),
2441                                         msg: channel.get_accept_channel(),
2442                                 });
2443                                 entry.insert(channel);
2444                         }
2445                 }
2446                 Ok(())
2447         }
2448
2449         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
2450                 let (value, output_script, user_id) = {
2451                         let mut channel_lock = self.channel_state.lock().unwrap();
2452                         let channel_state = &mut *channel_lock;
2453                         match channel_state.by_id.entry(msg.temporary_channel_id) {
2454                                 hash_map::Entry::Occupied(mut chan) => {
2455                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2456                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
2457                                         }
2458                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration, their_features), channel_state, chan);
2459                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
2460                                 },
2461                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
2462                         }
2463                 };
2464                 let mut pending_events = self.pending_events.lock().unwrap();
2465                 pending_events.push(events::Event::FundingGenerationReady {
2466                         temporary_channel_id: msg.temporary_channel_id,
2467                         channel_value_satoshis: value,
2468                         output_script,
2469                         user_channel_id: user_id,
2470                 });
2471                 Ok(())
2472         }
2473
2474         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
2475                 let ((funding_msg, monitor), mut chan) = {
2476                         let last_block_hash = *self.last_block_hash.read().unwrap();
2477                         let mut channel_lock = self.channel_state.lock().unwrap();
2478                         let channel_state = &mut *channel_lock;
2479                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
2480                                 hash_map::Entry::Occupied(mut chan) => {
2481                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2482                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
2483                                         }
2484                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg, last_block_hash, &self.logger), channel_state, chan), chan.remove())
2485                                 },
2486                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
2487                         }
2488                 };
2489                 // Because we have exclusive ownership of the channel here we can release the channel_state
2490                 // lock before watch_channel
2491                 if let Err(e) = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor) {
2492                         match e {
2493                                 ChannelMonitorUpdateErr::PermanentFailure => {
2494                                         // Note that we reply with the new channel_id in error messages if we gave up on the
2495                                         // channel, not the temporary_channel_id. This is compatible with ourselves, but the
2496                                         // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
2497                                         // any messages referencing a previously-closed channel anyway.
2498                                         // We do not do a force-close here as that would generate a monitor update for
2499                                         // a monitor that we didn't manage to store (and that we don't care about - we
2500                                         // don't respond with the funding_signed so the channel can never go on chain).
2501                                         let (_monitor_update, failed_htlcs) = chan.force_shutdown(true);
2502                                         assert!(failed_htlcs.is_empty());
2503                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("ChannelMonitor storage failure".to_owned(), funding_msg.channel_id));
2504                                 },
2505                                 ChannelMonitorUpdateErr::TemporaryFailure => {
2506                                         // There's no problem signing a counterparty's funding transaction if our monitor
2507                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
2508                                         // accepted payment from yet. We do, however, need to wait to send our funding_locked
2509                                         // until we have persisted our monitor.
2510                                         chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
2511                                 },
2512                         }
2513                 }
2514                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2515                 let channel_state = &mut *channel_state_lock;
2516                 match channel_state.by_id.entry(funding_msg.channel_id) {
2517                         hash_map::Entry::Occupied(_) => {
2518                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
2519                         },
2520                         hash_map::Entry::Vacant(e) => {
2521                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
2522                                         node_id: counterparty_node_id.clone(),
2523                                         msg: funding_msg,
2524                                 });
2525                                 e.insert(chan);
2526                         }
2527                 }
2528                 Ok(())
2529         }
2530
2531         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
2532                 let (funding_txo, user_id) = {
2533                         let last_block_hash = *self.last_block_hash.read().unwrap();
2534                         let mut channel_lock = self.channel_state.lock().unwrap();
2535                         let channel_state = &mut *channel_lock;
2536                         match channel_state.by_id.entry(msg.channel_id) {
2537                                 hash_map::Entry::Occupied(mut chan) => {
2538                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2539                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2540                                         }
2541                                         let monitor = match chan.get_mut().funding_signed(&msg, last_block_hash, &self.logger) {
2542                                                 Ok(update) => update,
2543                                                 Err(e) => try_chan_entry!(self, Err(e), channel_state, chan),
2544                                         };
2545                                         if let Err(e) = self.chain_monitor.watch_channel(chan.get().get_funding_txo().unwrap(), monitor) {
2546                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
2547                                         }
2548                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
2549                                 },
2550                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2551                         }
2552                 };
2553                 let mut pending_events = self.pending_events.lock().unwrap();
2554                 pending_events.push(events::Event::FundingBroadcastSafe {
2555                         funding_txo,
2556                         user_channel_id: user_id,
2557                 });
2558                 Ok(())
2559         }
2560
2561         fn internal_funding_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
2562                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2563                 let channel_state = &mut *channel_state_lock;
2564                 match channel_state.by_id.entry(msg.channel_id) {
2565                         hash_map::Entry::Occupied(mut chan) => {
2566                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2567                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2568                                 }
2569                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
2570                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
2571                                         log_trace!(self.logger, "Sending announcement_signatures for {} in response to funding_locked", log_bytes!(chan.get().channel_id()));
2572                                         // If we see locking block before receiving remote funding_locked, we broadcast our
2573                                         // announcement_sigs at remote funding_locked reception. If we receive remote
2574                                         // funding_locked before seeing locking block, we broadcast our announcement_sigs at locking
2575                                         // block connection. We should guanrantee to broadcast announcement_sigs to our peer whatever
2576                                         // the order of the events but our peer may not receive it due to disconnection. The specs
2577                                         // lacking an acknowledgement for announcement_sigs we may have to re-send them at peer
2578                                         // connection in the future if simultaneous misses by both peers due to network/hardware
2579                                         // failures is an issue. Note, to achieve its goal, only one of the announcement_sigs needs
2580                                         // to be received, from then sigs are going to be flood to the whole network.
2581                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2582                                                 node_id: counterparty_node_id.clone(),
2583                                                 msg: announcement_sigs,
2584                                         });
2585                                 }
2586                                 Ok(())
2587                         },
2588                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2589                 }
2590         }
2591
2592         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
2593                 let (mut dropped_htlcs, chan_option) = {
2594                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2595                         let channel_state = &mut *channel_state_lock;
2596
2597                         match channel_state.by_id.entry(msg.channel_id.clone()) {
2598                                 hash_map::Entry::Occupied(mut chan_entry) => {
2599                                         if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
2600                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2601                                         }
2602                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&self.fee_estimator, &their_features, &msg), channel_state, chan_entry);
2603                                         if let Some(msg) = shutdown {
2604                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2605                                                         node_id: counterparty_node_id.clone(),
2606                                                         msg,
2607                                                 });
2608                                         }
2609                                         if let Some(msg) = closing_signed {
2610                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2611                                                         node_id: counterparty_node_id.clone(),
2612                                                         msg,
2613                                                 });
2614                                         }
2615                                         if chan_entry.get().is_shutdown() {
2616                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2617                                                         channel_state.short_to_id.remove(&short_id);
2618                                                 }
2619                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
2620                                         } else { (dropped_htlcs, None) }
2621                                 },
2622                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2623                         }
2624                 };
2625                 for htlc_source in dropped_htlcs.drain(..) {
2626                         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() });
2627                 }
2628                 if let Some(chan) = chan_option {
2629                         if let Ok(update) = self.get_channel_update(&chan) {
2630                                 let mut channel_state = self.channel_state.lock().unwrap();
2631                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2632                                         msg: update
2633                                 });
2634                         }
2635                 }
2636                 Ok(())
2637         }
2638
2639         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
2640                 let (tx, chan_option) = {
2641                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2642                         let channel_state = &mut *channel_state_lock;
2643                         match channel_state.by_id.entry(msg.channel_id.clone()) {
2644                                 hash_map::Entry::Occupied(mut chan_entry) => {
2645                                         if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
2646                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2647                                         }
2648                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&self.fee_estimator, &msg), channel_state, chan_entry);
2649                                         if let Some(msg) = closing_signed {
2650                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2651                                                         node_id: counterparty_node_id.clone(),
2652                                                         msg,
2653                                                 });
2654                                         }
2655                                         if tx.is_some() {
2656                                                 // We're done with this channel, we've got a signed closing transaction and
2657                                                 // will send the closing_signed back to the remote peer upon return. This
2658                                                 // also implies there are no pending HTLCs left on the channel, so we can
2659                                                 // fully delete it from tracking (the channel monitor is still around to
2660                                                 // watch for old state broadcasts)!
2661                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2662                                                         channel_state.short_to_id.remove(&short_id);
2663                                                 }
2664                                                 (tx, Some(chan_entry.remove_entry().1))
2665                                         } else { (tx, None) }
2666                                 },
2667                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2668                         }
2669                 };
2670                 if let Some(broadcast_tx) = tx {
2671                         log_trace!(self.logger, "Broadcast onchain {}", log_tx!(broadcast_tx));
2672                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2673                 }
2674                 if let Some(chan) = chan_option {
2675                         if let Ok(update) = self.get_channel_update(&chan) {
2676                                 let mut channel_state = self.channel_state.lock().unwrap();
2677                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2678                                         msg: update
2679                                 });
2680                         }
2681                 }
2682                 Ok(())
2683         }
2684
2685         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2686                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2687                 //determine the state of the payment based on our response/if we forward anything/the time
2688                 //we take to respond. We should take care to avoid allowing such an attack.
2689                 //
2690                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2691                 //us repeatedly garbled in different ways, and compare our error messages, which are
2692                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
2693                 //but we should prevent it anyway.
2694
2695                 let (pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2696                 let channel_state = &mut *channel_state_lock;
2697
2698                 match channel_state.by_id.entry(msg.channel_id) {
2699                         hash_map::Entry::Occupied(mut chan) => {
2700                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2701                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2702                                 }
2703
2704                                 let create_pending_htlc_status = |chan: &Channel<Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
2705                                         // Ensure error_code has the UPDATE flag set, since by default we send a
2706                                         // channel update along as part of failing the HTLC.
2707                                         assert!((error_code & 0x1000) != 0);
2708                                         // If the update_add is completely bogus, the call will Err and we will close,
2709                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2710                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2711                                         match pending_forward_info {
2712                                                 PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
2713                                                         let reason = if let Ok(upd) = self.get_channel_update(chan) {
2714                                                                 onion_utils::build_first_hop_failure_packet(incoming_shared_secret, error_code, &{
2715                                                                         let mut res = Vec::with_capacity(8 + 128);
2716                                                                         // TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
2717                                                                         res.extend_from_slice(&byte_utils::be16_to_array(0));
2718                                                                         res.extend_from_slice(&upd.encode_with_len()[..]);
2719                                                                         res
2720                                                                 }[..])
2721                                                         } else {
2722                                                                 // The only case where we'd be unable to
2723                                                                 // successfully get a channel update is if the
2724                                                                 // channel isn't in the fully-funded state yet,
2725                                                                 // implying our counterparty is trying to route
2726                                                                 // payments over the channel back to themselves
2727                                                                 // (cause no one else should know the short_id
2728                                                                 // is a lightning channel yet). We should have
2729                                                                 // no problem just calling this
2730                                                                 // unknown_next_peer (0x4000|10).
2731                                                                 onion_utils::build_first_hop_failure_packet(incoming_shared_secret, 0x4000|10, &[])
2732                                                         };
2733                                                         let msg = msgs::UpdateFailHTLC {
2734                                                                 channel_id: msg.channel_id,
2735                                                                 htlc_id: msg.htlc_id,
2736                                                                 reason
2737                                                         };
2738                                                         PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
2739                                                 },
2740                                                 _ => pending_forward_info
2741                                         }
2742                                 };
2743                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.logger), channel_state, chan);
2744                         },
2745                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2746                 }
2747                 Ok(())
2748         }
2749
2750         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2751                 let mut channel_lock = self.channel_state.lock().unwrap();
2752                 let htlc_source = {
2753                         let channel_state = &mut *channel_lock;
2754                         match channel_state.by_id.entry(msg.channel_id) {
2755                                 hash_map::Entry::Occupied(mut chan) => {
2756                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2757                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2758                                         }
2759                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2760                                 },
2761                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2762                         }
2763                 };
2764                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2765                 Ok(())
2766         }
2767
2768         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2769                 let mut channel_lock = self.channel_state.lock().unwrap();
2770                 let channel_state = &mut *channel_lock;
2771                 match channel_state.by_id.entry(msg.channel_id) {
2772                         hash_map::Entry::Occupied(mut chan) => {
2773                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2774                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2775                                 }
2776                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::LightningError { err: msg.reason.clone() }), channel_state, chan);
2777                         },
2778                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2779                 }
2780                 Ok(())
2781         }
2782
2783         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2784                 let mut channel_lock = self.channel_state.lock().unwrap();
2785                 let channel_state = &mut *channel_lock;
2786                 match channel_state.by_id.entry(msg.channel_id) {
2787                         hash_map::Entry::Occupied(mut chan) => {
2788                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2789                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2790                                 }
2791                                 if (msg.failure_code & 0x8000) == 0 {
2792                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
2793                                         try_chan_entry!(self, Err(chan_err), channel_state, chan);
2794                                 }
2795                                 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);
2796                                 Ok(())
2797                         },
2798                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2799                 }
2800         }
2801
2802         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2803                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2804                 let channel_state = &mut *channel_state_lock;
2805                 match channel_state.by_id.entry(msg.channel_id) {
2806                         hash_map::Entry::Occupied(mut chan) => {
2807                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2808                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2809                                 }
2810                                 let (revoke_and_ack, commitment_signed, closing_signed, monitor_update) =
2811                                         match chan.get_mut().commitment_signed(&msg, &self.fee_estimator, &self.logger) {
2812                                                 Err((None, e)) => try_chan_entry!(self, Err(e), channel_state, chan),
2813                                                 Err((Some(update), e)) => {
2814                                                         assert!(chan.get().is_awaiting_monitor_update());
2815                                                         let _ = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), update);
2816                                                         try_chan_entry!(self, Err(e), channel_state, chan);
2817                                                         unreachable!();
2818                                                 },
2819                                                 Ok(res) => res
2820                                         };
2821                                 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2822                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some());
2823                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2824                                 }
2825                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2826                                         node_id: counterparty_node_id.clone(),
2827                                         msg: revoke_and_ack,
2828                                 });
2829                                 if let Some(msg) = commitment_signed {
2830                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2831                                                 node_id: counterparty_node_id.clone(),
2832                                                 updates: msgs::CommitmentUpdate {
2833                                                         update_add_htlcs: Vec::new(),
2834                                                         update_fulfill_htlcs: Vec::new(),
2835                                                         update_fail_htlcs: Vec::new(),
2836                                                         update_fail_malformed_htlcs: Vec::new(),
2837                                                         update_fee: None,
2838                                                         commitment_signed: msg,
2839                                                 },
2840                                         });
2841                                 }
2842                                 if let Some(msg) = closing_signed {
2843                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2844                                                 node_id: counterparty_node_id.clone(),
2845                                                 msg,
2846                                         });
2847                                 }
2848                                 Ok(())
2849                         },
2850                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2851                 }
2852         }
2853
2854         #[inline]
2855         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, Vec<(PendingHTLCInfo, u64)>)]) {
2856                 for &mut (prev_short_channel_id, prev_funding_outpoint, ref mut pending_forwards) in per_source_pending_forwards {
2857                         let mut forward_event = None;
2858                         if !pending_forwards.is_empty() {
2859                                 let mut channel_state = self.channel_state.lock().unwrap();
2860                                 if channel_state.forward_htlcs.is_empty() {
2861                                         forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS))
2862                                 }
2863                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2864                                         match channel_state.forward_htlcs.entry(match forward_info.routing {
2865                                                         PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
2866                                                         PendingHTLCRouting::Receive { .. } => 0,
2867                                         }) {
2868                                                 hash_map::Entry::Occupied(mut entry) => {
2869                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_funding_outpoint,
2870                                                                                                         prev_htlc_id, forward_info });
2871                                                 },
2872                                                 hash_map::Entry::Vacant(entry) => {
2873                                                         entry.insert(vec!(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_funding_outpoint,
2874                                                                                                      prev_htlc_id, forward_info }));
2875                                                 }
2876                                         }
2877                                 }
2878                         }
2879                         match forward_event {
2880                                 Some(time) => {
2881                                         let mut pending_events = self.pending_events.lock().unwrap();
2882                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2883                                                 time_forwardable: time
2884                                         });
2885                                 }
2886                                 None => {},
2887                         }
2888                 }
2889         }
2890
2891         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2892                 let mut htlcs_to_fail = Vec::new();
2893                 let res = loop {
2894                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2895                         let channel_state = &mut *channel_state_lock;
2896                         match channel_state.by_id.entry(msg.channel_id) {
2897                                 hash_map::Entry::Occupied(mut chan) => {
2898                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2899                                                 break Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2900                                         }
2901                                         let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2902                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, monitor_update, htlcs_to_fail_in) =
2903                                                 break_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &self.fee_estimator, &self.logger), channel_state, chan);
2904                                         htlcs_to_fail = htlcs_to_fail_in;
2905                                         if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2906                                                 if was_frozen_for_monitor {
2907                                                         assert!(commitment_update.is_none() && closing_signed.is_none() && pending_forwards.is_empty() && pending_failures.is_empty());
2908                                                         break Err(MsgHandleErrInternal::ignore_no_close("Previous monitor update failure prevented responses to RAA".to_owned()));
2909                                                 } else {
2910                                                         if let Err(e) = handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, commitment_update.is_some(), pending_forwards, pending_failures) {
2911                                                                 break Err(e);
2912                                                         } else { unreachable!(); }
2913                                                 }
2914                                         }
2915                                         if let Some(updates) = commitment_update {
2916                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2917                                                         node_id: counterparty_node_id.clone(),
2918                                                         updates,
2919                                                 });
2920                                         }
2921                                         if let Some(msg) = closing_signed {
2922                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2923                                                         node_id: counterparty_node_id.clone(),
2924                                                         msg,
2925                                                 });
2926                                         }
2927                                         break Ok((pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"), chan.get().get_funding_txo().unwrap()))
2928                                 },
2929                                 hash_map::Entry::Vacant(_) => break Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2930                         }
2931                 };
2932                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id);
2933                 match res {
2934                         Ok((pending_forwards, mut pending_failures, short_channel_id, channel_outpoint)) => {
2935                                 for failure in pending_failures.drain(..) {
2936                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2937                                 }
2938                                 self.forward_htlcs(&mut [(short_channel_id, channel_outpoint, pending_forwards)]);
2939                                 Ok(())
2940                         },
2941                         Err(e) => Err(e)
2942                 }
2943         }
2944
2945         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2946                 let mut channel_lock = self.channel_state.lock().unwrap();
2947                 let channel_state = &mut *channel_lock;
2948                 match channel_state.by_id.entry(msg.channel_id) {
2949                         hash_map::Entry::Occupied(mut chan) => {
2950                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2951                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2952                                 }
2953                                 try_chan_entry!(self, chan.get_mut().update_fee(&self.fee_estimator, &msg), channel_state, chan);
2954                         },
2955                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2956                 }
2957                 Ok(())
2958         }
2959
2960         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2961                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2962                 let channel_state = &mut *channel_state_lock;
2963
2964                 match channel_state.by_id.entry(msg.channel_id) {
2965                         hash_map::Entry::Occupied(mut chan) => {
2966                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2967                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2968                                 }
2969                                 if !chan.get().is_usable() {
2970                                         return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
2971                                 }
2972
2973                                 let our_node_id = self.get_our_node_id();
2974                                 let (announcement, our_bitcoin_sig) =
2975                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2976
2977                                 let were_node_one = announcement.node_id_1 == our_node_id;
2978                                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
2979                                 {
2980                                         let their_node_key = if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 };
2981                                         let their_bitcoin_key = if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 };
2982                                         match (self.secp_ctx.verify(&msghash, &msg.node_signature, their_node_key),
2983                                                    self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, their_bitcoin_key)) {
2984                                                 (Err(e), _) => {
2985                                                         let chan_err: ChannelError = ChannelError::Close(format!("Bad announcement_signatures. Failed to verify node_signature: {:?}. Maybe using different node_secret for transport and routing msg? UnsignedChannelAnnouncement used for verification is {:?}. their_node_key is {:?}", e, &announcement, their_node_key));
2986                                                         try_chan_entry!(self, Err(chan_err), channel_state, chan);
2987                                                 },
2988                                                 (_, Err(e)) => {
2989                                                         let chan_err: ChannelError = ChannelError::Close(format!("Bad announcement_signatures. Failed to verify bitcoin_signature: {:?}. UnsignedChannelAnnouncement used for verification is {:?}. their_bitcoin_key is ({:?})", e, &announcement, their_bitcoin_key));
2990                                                         try_chan_entry!(self, Err(chan_err), channel_state, chan);
2991                                                 },
2992                                                 _ => {}
2993                                         }
2994                                 }
2995
2996                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2997
2998                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2999                                         msg: msgs::ChannelAnnouncement {
3000                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
3001                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
3002                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
3003                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
3004                                                 contents: announcement,
3005                                         },
3006                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
3007                                 });
3008                         },
3009                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3010                 }
3011                 Ok(())
3012         }
3013
3014         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<(), MsgHandleErrInternal> {
3015                 let mut channel_state_lock = self.channel_state.lock().unwrap();
3016                 let channel_state = &mut *channel_state_lock;
3017                 let chan_id = match channel_state.short_to_id.get(&msg.contents.short_channel_id) {
3018                         Some(chan_id) => chan_id.clone(),
3019                         None => {
3020                                 // It's not a local channel
3021                                 return Ok(())
3022                         }
3023                 };
3024                 match channel_state.by_id.entry(chan_id) {
3025                         hash_map::Entry::Occupied(mut chan) => {
3026                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3027                                         // TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
3028                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), chan_id));
3029                                 }
3030                                 try_chan_entry!(self, chan.get_mut().channel_update(&msg), channel_state, chan);
3031                         },
3032                         hash_map::Entry::Vacant(_) => unreachable!()
3033                 }
3034                 Ok(())
3035         }
3036
3037         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
3038                 let mut channel_state_lock = self.channel_state.lock().unwrap();
3039                 let channel_state = &mut *channel_state_lock;
3040
3041                 match channel_state.by_id.entry(msg.channel_id) {
3042                         hash_map::Entry::Occupied(mut chan) => {
3043                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3044                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
3045                                 }
3046                                 // Currently, we expect all holding cell update_adds to be dropped on peer
3047                                 // disconnect, so Channel's reestablish will never hand us any holding cell
3048                                 // freed HTLCs to fail backwards. If in the future we no longer drop pending
3049                                 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
3050                                 let (funding_locked, revoke_and_ack, commitment_update, monitor_update_opt, mut order, shutdown) =
3051                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg, &self.logger), channel_state, chan);
3052                                 if let Some(monitor_update) = monitor_update_opt {
3053                                         if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3054                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
3055                                                 // for the messages it returns, but if we're setting what messages to
3056                                                 // re-transmit on monitor update success, we need to make sure it is sane.
3057                                                 if revoke_and_ack.is_none() {
3058                                                         order = RAACommitmentOrder::CommitmentFirst;
3059                                                 }
3060                                                 if commitment_update.is_none() {
3061                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
3062                                                 }
3063                                                 return_monitor_err!(self, e, channel_state, chan, order, revoke_and_ack.is_some(), commitment_update.is_some());
3064                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
3065                                         }
3066                                 }
3067                                 if let Some(msg) = funding_locked {
3068                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
3069                                                 node_id: counterparty_node_id.clone(),
3070                                                 msg
3071                                         });
3072                                 }
3073                                 macro_rules! send_raa { () => {
3074                                         if let Some(msg) = revoke_and_ack {
3075                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
3076                                                         node_id: counterparty_node_id.clone(),
3077                                                         msg
3078                                                 });
3079                                         }
3080                                 } }
3081                                 macro_rules! send_cu { () => {
3082                                         if let Some(updates) = commitment_update {
3083                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3084                                                         node_id: counterparty_node_id.clone(),
3085                                                         updates
3086                                                 });
3087                                         }
3088                                 } }
3089                                 match order {
3090                                         RAACommitmentOrder::RevokeAndACKFirst => {
3091                                                 send_raa!();
3092                                                 send_cu!();
3093                                         },
3094                                         RAACommitmentOrder::CommitmentFirst => {
3095                                                 send_cu!();
3096                                                 send_raa!();
3097                                         },
3098                                 }
3099                                 if let Some(msg) = shutdown {
3100                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
3101                                                 node_id: counterparty_node_id.clone(),
3102                                                 msg,
3103                                         });
3104                                 }
3105                                 Ok(())
3106                         },
3107                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3108                 }
3109         }
3110
3111         /// Begin Update fee process. Allowed only on an outbound channel.
3112         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
3113         /// PeerManager::process_events afterwards.
3114         /// Note: This API is likely to change!
3115         /// (C-not exported) Cause its doc(hidden) anyway
3116         #[doc(hidden)]
3117         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u32) -> Result<(), APIError> {
3118                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3119                 let counterparty_node_id;
3120                 let err: Result<(), _> = loop {
3121                         let mut channel_state_lock = self.channel_state.lock().unwrap();
3122                         let channel_state = &mut *channel_state_lock;
3123
3124                         match channel_state.by_id.entry(channel_id) {
3125                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: format!("Failed to find corresponding channel for id {}", channel_id.to_hex())}),
3126                                 hash_map::Entry::Occupied(mut chan) => {
3127                                         if !chan.get().is_outbound() {
3128                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel".to_owned()});
3129                                         }
3130                                         if chan.get().is_awaiting_monitor_update() {
3131                                                 return Err(APIError::MonitorUpdateFailed);
3132                                         }
3133                                         if !chan.get().is_live() {
3134                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected".to_owned()});
3135                                         }
3136                                         counterparty_node_id = chan.get().get_counterparty_node_id();
3137                                         if let Some((update_fee, commitment_signed, monitor_update)) =
3138                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw, &self.logger), channel_state, chan)
3139                                         {
3140                                                 if let Err(_e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3141                                                         unimplemented!();
3142                                                 }
3143                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3144                                                         node_id: chan.get().get_counterparty_node_id(),
3145                                                         updates: msgs::CommitmentUpdate {
3146                                                                 update_add_htlcs: Vec::new(),
3147                                                                 update_fulfill_htlcs: Vec::new(),
3148                                                                 update_fail_htlcs: Vec::new(),
3149                                                                 update_fail_malformed_htlcs: Vec::new(),
3150                                                                 update_fee: Some(update_fee),
3151                                                                 commitment_signed,
3152                                                         },
3153                                                 });
3154                                         }
3155                                 },
3156                         }
3157                         return Ok(())
3158                 };
3159
3160                 match handle_error!(self, err, counterparty_node_id) {
3161                         Ok(_) => unreachable!(),
3162                         Err(e) => { Err(APIError::APIMisuseError { err: e.err })}
3163                 }
3164         }
3165
3166         /// Process pending events from the `chain::Watch`.
3167         fn process_pending_monitor_events(&self) {
3168                 let mut failed_channels = Vec::new();
3169                 {
3170                         for monitor_event in self.chain_monitor.release_pending_monitor_events() {
3171                                 match monitor_event {
3172                                         MonitorEvent::HTLCEvent(htlc_update) => {
3173                                                 if let Some(preimage) = htlc_update.payment_preimage {
3174                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
3175                                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
3176                                                 } else {
3177                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
3178                                                         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() });
3179                                                 }
3180                                         },
3181                                         MonitorEvent::CommitmentTxBroadcasted(funding_outpoint) => {
3182                                                 let mut channel_lock = self.channel_state.lock().unwrap();
3183                                                 let channel_state = &mut *channel_lock;
3184                                                 let by_id = &mut channel_state.by_id;
3185                                                 let short_to_id = &mut channel_state.short_to_id;
3186                                                 let pending_msg_events = &mut channel_state.pending_msg_events;
3187                                                 if let Some(mut chan) = by_id.remove(&funding_outpoint.to_channel_id()) {
3188                                                         if let Some(short_id) = chan.get_short_channel_id() {
3189                                                                 short_to_id.remove(&short_id);
3190                                                         }
3191                                                         failed_channels.push(chan.force_shutdown(false));
3192                                                         if let Ok(update) = self.get_channel_update(&chan) {
3193                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3194                                                                         msg: update
3195                                                                 });
3196                                                         }
3197                                                 }
3198                                         },
3199                                 }
3200                         }
3201                 }
3202
3203                 for failure in failed_channels.drain(..) {
3204                         self.finish_force_close_channel(failure);
3205                 }
3206         }
3207
3208         /// Handle a list of channel failures during a block_connected or block_disconnected call,
3209         /// pushing the channel monitor update (if any) to the background events queue and removing the
3210         /// Channel object.
3211         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
3212                 for mut failure in failed_channels.drain(..) {
3213                         // Either a commitment transactions has been confirmed on-chain or
3214                         // Channel::block_disconnected detected that the funding transaction has been
3215                         // reorganized out of the main chain.
3216                         // We cannot broadcast our latest local state via monitor update (as
3217                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
3218                         // so we track the update internally and handle it when the user next calls
3219                         // timer_chan_freshness_every_min, guaranteeing we're running normally.
3220                         if let Some((funding_txo, update)) = failure.0.take() {
3221                                 assert_eq!(update.updates.len(), 1);
3222                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
3223                                         assert!(should_broadcast);
3224                                 } else { unreachable!(); }
3225                                 self.pending_background_events.lock().unwrap().push(BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)));
3226                         }
3227                         self.finish_force_close_channel(failure);
3228                 }
3229         }
3230 }
3231
3232 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> MessageSendEventsProvider for ChannelManager<Signer, M, T, K, F, L>
3233         where M::Target: chain::Watch<Signer>,
3234         T::Target: BroadcasterInterface,
3235         K::Target: KeysInterface<Signer = Signer>,
3236         F::Target: FeeEstimator,
3237                                 L::Target: Logger,
3238 {
3239         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
3240                 //TODO: This behavior should be documented. It's non-intuitive that we query
3241                 // ChannelMonitors when clearing other events.
3242                 self.process_pending_monitor_events();
3243
3244                 let mut ret = Vec::new();
3245                 let mut channel_state = self.channel_state.lock().unwrap();
3246                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
3247                 ret
3248         }
3249 }
3250
3251 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> EventsProvider for ChannelManager<Signer, M, T, K, F, L>
3252         where M::Target: chain::Watch<Signer>,
3253         T::Target: BroadcasterInterface,
3254         K::Target: KeysInterface<Signer = Signer>,
3255         F::Target: FeeEstimator,
3256                                 L::Target: Logger,
3257 {
3258         fn get_and_clear_pending_events(&self) -> Vec<Event> {
3259                 //TODO: This behavior should be documented. It's non-intuitive that we query
3260                 // ChannelMonitors when clearing other events.
3261                 self.process_pending_monitor_events();
3262
3263                 let mut ret = Vec::new();
3264                 let mut pending_events = self.pending_events.lock().unwrap();
3265                 mem::swap(&mut ret, &mut *pending_events);
3266                 ret
3267         }
3268 }
3269
3270 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> chain::Listen for ChannelManager<Signer, M, T, K, F, L>
3271 where
3272         M::Target: chain::Watch<Signer>,
3273         T::Target: BroadcasterInterface,
3274         K::Target: KeysInterface<Signer = Signer>,
3275         F::Target: FeeEstimator,
3276         L::Target: Logger,
3277 {
3278         fn block_connected(&self, block: &Block, height: u32) {
3279                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
3280                 ChannelManager::block_connected(self, &block.header, &txdata, height);
3281         }
3282
3283         fn block_disconnected(&self, header: &BlockHeader, _height: u32) {
3284                 ChannelManager::block_disconnected(self, header);
3285         }
3286 }
3287
3288 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
3289         where M::Target: chain::Watch<Signer>,
3290         T::Target: BroadcasterInterface,
3291         K::Target: KeysInterface<Signer = Signer>,
3292         F::Target: FeeEstimator,
3293         L::Target: Logger,
3294 {
3295         /// Updates channel state based on transactions seen in a connected block.
3296         pub fn block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3297                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3298                 // during initialization prior to the chain_monitor being fully configured in some cases.
3299                 // See the docs for `ChannelManagerReadArgs` for more.
3300                 let block_hash = header.block_hash();
3301                 log_trace!(self.logger, "Block {} at height {} connected", block_hash, height);
3302
3303                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3304
3305                 assert_eq!(*self.last_block_hash.read().unwrap(), header.prev_blockhash,
3306                         "Blocks must be connected in chain-order - the connected header must build on the last connected header");
3307                 assert_eq!(self.latest_block_height.load(Ordering::Acquire) as u64, height as u64 - 1,
3308                         "Blocks must be connected in chain-order - the connected header must build on the last connected header");
3309                 self.latest_block_height.store(height as usize, Ordering::Release);
3310                 *self.last_block_hash.write().unwrap() = block_hash;
3311
3312                 let mut failed_channels = Vec::new();
3313                 let mut timed_out_htlcs = Vec::new();
3314                 {
3315                         let mut channel_lock = self.channel_state.lock().unwrap();
3316                         let channel_state = &mut *channel_lock;
3317                         let short_to_id = &mut channel_state.short_to_id;
3318                         let pending_msg_events = &mut channel_state.pending_msg_events;
3319                         channel_state.by_id.retain(|_, channel| {
3320                                 let res = channel.block_connected(header, txdata, height);
3321                                 if let Ok((chan_res, mut timed_out_pending_htlcs)) = res {
3322                                         for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
3323                                                 let chan_update = self.get_channel_update(&channel).map(|u| u.encode_with_len()).unwrap(); // Cannot add/recv HTLCs before we have a short_id so unwrap is safe
3324                                                 timed_out_htlcs.push((source, payment_hash,  HTLCFailReason::Reason {
3325                                                         failure_code: 0x1000 | 14, // expiry_too_soon, or at least it is now
3326                                                         data: chan_update,
3327                                                 }));
3328                                         }
3329                                         if let Some(funding_locked) = chan_res {
3330                                                 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
3331                                                         node_id: channel.get_counterparty_node_id(),
3332                                                         msg: funding_locked,
3333                                                 });
3334                                                 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
3335                                                         log_trace!(self.logger, "Sending funding_locked and announcement_signatures for {}", log_bytes!(channel.channel_id()));
3336                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
3337                                                                 node_id: channel.get_counterparty_node_id(),
3338                                                                 msg: announcement_sigs,
3339                                                         });
3340                                                 } else {
3341                                                         log_trace!(self.logger, "Sending funding_locked WITHOUT announcement_signatures for {}", log_bytes!(channel.channel_id()));
3342                                                 }
3343                                                 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
3344                                         }
3345                                 } else if let Err(e) = res {
3346                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
3347                                                 node_id: channel.get_counterparty_node_id(),
3348                                                 action: msgs::ErrorAction::SendErrorMessage { msg: e },
3349                                         });
3350                                         return false;
3351                                 }
3352                                 if let Some(funding_txo) = channel.get_funding_txo() {
3353                                         for &(_, tx) in txdata.iter() {
3354                                                 for inp in tx.input.iter() {
3355                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
3356                                                                 log_trace!(self.logger, "Detected channel-closing tx {} spending {}:{}, closing channel {}", tx.txid(), inp.previous_output.txid, inp.previous_output.vout, log_bytes!(channel.channel_id()));
3357                                                                 if let Some(short_id) = channel.get_short_channel_id() {
3358                                                                         short_to_id.remove(&short_id);
3359                                                                 }
3360                                                                 // It looks like our counterparty went on-chain. Close the channel.
3361                                                                 failed_channels.push(channel.force_shutdown(true));
3362                                                                 if let Ok(update) = self.get_channel_update(&channel) {
3363                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3364                                                                                 msg: update
3365                                                                         });
3366                                                                 }
3367                                                                 return false;
3368                                                         }
3369                                                 }
3370                                         }
3371                                 }
3372                                 true
3373                         });
3374
3375                         channel_state.claimable_htlcs.retain(|&(ref payment_hash, _), htlcs| {
3376                                 htlcs.retain(|htlc| {
3377                                         // If height is approaching the number of blocks we think it takes us to get
3378                                         // our commitment transaction confirmed before the HTLC expires, plus the
3379                                         // number of blocks we generally consider it to take to do a commitment update,
3380                                         // just give up on it and fail the HTLC.
3381                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
3382                                                 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
3383                                                 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(height));
3384                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(), HTLCFailReason::Reason {
3385                                                         failure_code: 0x4000 | 15,
3386                                                         data: htlc_msat_height_data
3387                                                 }));
3388                                                 false
3389                                         } else { true }
3390                                 });
3391                                 !htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
3392                         });
3393                 }
3394
3395                 self.handle_init_event_channel_failures(failed_channels);
3396
3397                 for (source, payment_hash, reason) in timed_out_htlcs.drain(..) {
3398                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, reason);
3399                 }
3400
3401                 loop {
3402                         // Update last_node_announcement_serial to be the max of its current value and the
3403                         // block timestamp. This should keep us close to the current time without relying on
3404                         // having an explicit local time source.
3405                         // Just in case we end up in a race, we loop until we either successfully update
3406                         // last_node_announcement_serial or decide we don't need to.
3407                         let old_serial = self.last_node_announcement_serial.load(Ordering::Acquire);
3408                         if old_serial >= header.time as usize { break; }
3409                         if self.last_node_announcement_serial.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
3410                                 break;
3411                         }
3412                 }
3413         }
3414
3415         /// Updates channel state based on a disconnected block.
3416         ///
3417         /// If necessary, the channel may be force-closed without letting the counterparty participate
3418         /// in the shutdown.
3419         pub fn block_disconnected(&self, header: &BlockHeader) {
3420                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3421                 // during initialization prior to the chain_monitor being fully configured in some cases.
3422                 // See the docs for `ChannelManagerReadArgs` for more.
3423                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3424
3425                 assert_eq!(*self.last_block_hash.read().unwrap(), header.block_hash(),
3426                         "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
3427                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
3428                 *self.last_block_hash.write().unwrap() = header.prev_blockhash;
3429
3430                 let mut failed_channels = Vec::new();
3431                 {
3432                         let mut channel_lock = self.channel_state.lock().unwrap();
3433                         let channel_state = &mut *channel_lock;
3434                         let short_to_id = &mut channel_state.short_to_id;
3435                         let pending_msg_events = &mut channel_state.pending_msg_events;
3436                         channel_state.by_id.retain(|_,  v| {
3437                                 if v.block_disconnected(header) {
3438                                         if let Some(short_id) = v.get_short_channel_id() {
3439                                                 short_to_id.remove(&short_id);
3440                                         }
3441                                         failed_channels.push(v.force_shutdown(true));
3442                                         if let Ok(update) = self.get_channel_update(&v) {
3443                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3444                                                         msg: update
3445                                                 });
3446                                         }
3447                                         false
3448                                 } else {
3449                                         true
3450                                 }
3451                         });
3452                 }
3453
3454                 self.handle_init_event_channel_failures(failed_channels);
3455         }
3456
3457         /// Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool
3458         /// indicating whether persistence is necessary. Only one listener on
3459         /// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
3460         /// up.
3461         /// Note that the feature `allow_wallclock_use` must be enabled to use this function.
3462         #[cfg(any(test, feature = "allow_wallclock_use"))]
3463         pub fn await_persistable_update_timeout(&self, max_wait: Duration) -> bool {
3464                 self.persistence_notifier.wait_timeout(max_wait)
3465         }
3466
3467         /// Blocks until ChannelManager needs to be persisted. Only one listener on
3468         /// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
3469         /// up.
3470         pub fn await_persistable_update(&self) {
3471                 self.persistence_notifier.wait()
3472         }
3473
3474         #[cfg(any(test, feature = "_test_utils"))]
3475         pub fn get_persistence_condvar_value(&self) -> bool {
3476                 let mutcond = &self.persistence_notifier.persistence_lock;
3477                 let &(ref mtx, _) = mutcond;
3478                 let guard = mtx.lock().unwrap();
3479                 *guard
3480         }
3481 }
3482
3483 impl<Signer: Sign, M: Deref + Sync + Send, T: Deref + Sync + Send, K: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send>
3484         ChannelMessageHandler for ChannelManager<Signer, M, T, K, F, L>
3485         where M::Target: chain::Watch<Signer>,
3486         T::Target: BroadcasterInterface,
3487         K::Target: KeysInterface<Signer = Signer>,
3488         F::Target: FeeEstimator,
3489         L::Target: Logger,
3490 {
3491         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) {
3492                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3493                 let _ = handle_error!(self, self.internal_open_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
3494         }
3495
3496         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) {
3497                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3498                 let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
3499         }
3500
3501         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
3502                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3503                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
3504         }
3505
3506         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
3507                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3508                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
3509         }
3510
3511         fn handle_funding_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingLocked) {
3512                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3513                 let _ = handle_error!(self, self.internal_funding_locked(counterparty_node_id, msg), *counterparty_node_id);
3514         }
3515
3516         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) {
3517                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3518                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, their_features, msg), *counterparty_node_id);
3519         }
3520
3521         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
3522                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3523                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
3524         }
3525
3526         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
3527                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3528                 let _ = handle_error!(self, self.internal_update_add_htlc(counterparty_node_id, msg), *counterparty_node_id);
3529         }
3530
3531         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
3532                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3533                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
3534         }
3535
3536         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
3537                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3538                 let _ = handle_error!(self, self.internal_update_fail_htlc(counterparty_node_id, msg), *counterparty_node_id);
3539         }
3540
3541         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
3542                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3543                 let _ = handle_error!(self, self.internal_update_fail_malformed_htlc(counterparty_node_id, msg), *counterparty_node_id);
3544         }
3545
3546         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
3547                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3548                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
3549         }
3550
3551         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
3552                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3553                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
3554         }
3555
3556         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
3557                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3558                 let _ = handle_error!(self, self.internal_update_fee(counterparty_node_id, msg), *counterparty_node_id);
3559         }
3560
3561         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
3562                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3563                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
3564         }
3565
3566         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
3567                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3568                 let _ = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id);
3569         }
3570
3571         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
3572                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3573                 let _ = handle_error!(self, self.internal_channel_reestablish(counterparty_node_id, msg), *counterparty_node_id);
3574         }
3575
3576         fn peer_disconnected(&self, counterparty_node_id: &PublicKey, no_connection_possible: bool) {
3577                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3578                 let mut failed_channels = Vec::new();
3579                 let mut failed_payments = Vec::new();
3580                 let mut no_channels_remain = true;
3581                 {
3582                         let mut channel_state_lock = self.channel_state.lock().unwrap();
3583                         let channel_state = &mut *channel_state_lock;
3584                         let short_to_id = &mut channel_state.short_to_id;
3585                         let pending_msg_events = &mut channel_state.pending_msg_events;
3586                         if no_connection_possible {
3587                                 log_debug!(self.logger, "Failing all channels with {} due to no_connection_possible", log_pubkey!(counterparty_node_id));
3588                                 channel_state.by_id.retain(|_, chan| {
3589                                         if chan.get_counterparty_node_id() == *counterparty_node_id {
3590                                                 if let Some(short_id) = chan.get_short_channel_id() {
3591                                                         short_to_id.remove(&short_id);
3592                                                 }
3593                                                 failed_channels.push(chan.force_shutdown(true));
3594                                                 if let Ok(update) = self.get_channel_update(&chan) {
3595                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3596                                                                 msg: update
3597                                                         });
3598                                                 }
3599                                                 false
3600                                         } else {
3601                                                 true
3602                                         }
3603                                 });
3604                         } else {
3605                                 log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(counterparty_node_id));
3606                                 channel_state.by_id.retain(|_, chan| {
3607                                         if chan.get_counterparty_node_id() == *counterparty_node_id {
3608                                                 // Note that currently on channel reestablish we assert that there are no
3609                                                 // holding cell add-HTLCs, so if in the future we stop removing uncommitted HTLCs
3610                                                 // on peer disconnect here, there will need to be corresponding changes in
3611                                                 // reestablish logic.
3612                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger);
3613                                                 chan.to_disabled_marked();
3614                                                 if !failed_adds.is_empty() {
3615                                                         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
3616                                                         failed_payments.push((chan_update, failed_adds));
3617                                                 }
3618                                                 if chan.is_shutdown() {
3619                                                         if let Some(short_id) = chan.get_short_channel_id() {
3620                                                                 short_to_id.remove(&short_id);
3621                                                         }
3622                                                         return false;
3623                                                 } else {
3624                                                         no_channels_remain = false;
3625                                                 }
3626                                         }
3627                                         true
3628                                 })
3629                         }
3630                         pending_msg_events.retain(|msg| {
3631                                 match msg {
3632                                         &events::MessageSendEvent::SendAcceptChannel { ref node_id, .. } => node_id != counterparty_node_id,
3633                                         &events::MessageSendEvent::SendOpenChannel { ref node_id, .. } => node_id != counterparty_node_id,
3634                                         &events::MessageSendEvent::SendFundingCreated { ref node_id, .. } => node_id != counterparty_node_id,
3635                                         &events::MessageSendEvent::SendFundingSigned { ref node_id, .. } => node_id != counterparty_node_id,
3636                                         &events::MessageSendEvent::SendFundingLocked { ref node_id, .. } => node_id != counterparty_node_id,
3637                                         &events::MessageSendEvent::SendAnnouncementSignatures { ref node_id, .. } => node_id != counterparty_node_id,
3638                                         &events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => node_id != counterparty_node_id,
3639                                         &events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => node_id != counterparty_node_id,
3640                                         &events::MessageSendEvent::SendClosingSigned { ref node_id, .. } => node_id != counterparty_node_id,
3641                                         &events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != counterparty_node_id,
3642                                         &events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != counterparty_node_id,
3643                                         &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
3644                                         &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
3645                                         &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
3646                                         &events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != counterparty_node_id,
3647                                         &events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
3648                                         &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
3649                                         &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
3650                                         &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
3651                                 }
3652                         });
3653                 }
3654                 if no_channels_remain {
3655                         self.per_peer_state.write().unwrap().remove(counterparty_node_id);
3656                 }
3657
3658                 for failure in failed_channels.drain(..) {
3659                         self.finish_force_close_channel(failure);
3660                 }
3661                 for (chan_update, mut htlc_sources) in failed_payments {
3662                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
3663                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
3664                         }
3665                 }
3666         }
3667
3668         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init) {
3669                 log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
3670
3671                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3672
3673                 {
3674                         let mut peer_state_lock = self.per_peer_state.write().unwrap();
3675                         match peer_state_lock.entry(counterparty_node_id.clone()) {
3676                                 hash_map::Entry::Vacant(e) => {
3677                                         e.insert(Mutex::new(PeerState {
3678                                                 latest_features: init_msg.features.clone(),
3679                                         }));
3680                                 },
3681                                 hash_map::Entry::Occupied(e) => {
3682                                         e.get().lock().unwrap().latest_features = init_msg.features.clone();
3683                                 },
3684                         }
3685                 }
3686
3687                 let mut channel_state_lock = self.channel_state.lock().unwrap();
3688                 let channel_state = &mut *channel_state_lock;
3689                 let pending_msg_events = &mut channel_state.pending_msg_events;
3690                 channel_state.by_id.retain(|_, chan| {
3691                         if chan.get_counterparty_node_id() == *counterparty_node_id {
3692                                 if !chan.have_received_message() {
3693                                         // If we created this (outbound) channel while we were disconnected from the
3694                                         // peer we probably failed to send the open_channel message, which is now
3695                                         // lost. We can't have had anything pending related to this channel, so we just
3696                                         // drop it.
3697                                         false
3698                                 } else {
3699                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
3700                                                 node_id: chan.get_counterparty_node_id(),
3701                                                 msg: chan.get_channel_reestablish(&self.logger),
3702                                         });
3703                                         true
3704                                 }
3705                         } else { true }
3706                 });
3707                 //TODO: Also re-broadcast announcement_signatures
3708         }
3709
3710         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
3711                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3712
3713                 if msg.channel_id == [0; 32] {
3714                         for chan in self.list_channels() {
3715                                 if chan.remote_network_id == *counterparty_node_id {
3716                                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
3717                                         let _ = self.force_close_channel_with_peer(&chan.channel_id, Some(counterparty_node_id));
3718                                 }
3719                         }
3720                 } else {
3721                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
3722                         let _ = self.force_close_channel_with_peer(&msg.channel_id, Some(counterparty_node_id));
3723                 }
3724         }
3725 }
3726
3727 /// Used to signal to the ChannelManager persister that the manager needs to be re-persisted to
3728 /// disk/backups, through `await_persistable_update_timeout` and `await_persistable_update`.
3729 struct PersistenceNotifier {
3730         /// Users won't access the persistence_lock directly, but rather wait on its bool using
3731         /// `wait_timeout` and `wait`.
3732         persistence_lock: (Mutex<bool>, Condvar),
3733 }
3734
3735 impl PersistenceNotifier {
3736         fn new() -> Self {
3737                 Self {
3738                         persistence_lock: (Mutex::new(false), Condvar::new()),
3739                 }
3740         }
3741
3742         fn wait(&self) {
3743                 loop {
3744                         let &(ref mtx, ref cvar) = &self.persistence_lock;
3745                         let mut guard = mtx.lock().unwrap();
3746                         guard = cvar.wait(guard).unwrap();
3747                         let result = *guard;
3748                         if result {
3749                                 *guard = false;
3750                                 return
3751                         }
3752                 }
3753         }
3754
3755         #[cfg(any(test, feature = "allow_wallclock_use"))]
3756         fn wait_timeout(&self, max_wait: Duration) -> bool {
3757                 let current_time = Instant::now();
3758                 loop {
3759                         let &(ref mtx, ref cvar) = &self.persistence_lock;
3760                         let mut guard = mtx.lock().unwrap();
3761                         guard = cvar.wait_timeout(guard, max_wait).unwrap().0;
3762                         // Due to spurious wakeups that can happen on `wait_timeout`, here we need to check if the
3763                         // desired wait time has actually passed, and if not then restart the loop with a reduced wait
3764                         // time. Note that this logic can be highly simplified through the use of
3765                         // `Condvar::wait_while` and `Condvar::wait_timeout_while`, if and when our MSRV is raised to
3766                         // 1.42.0.
3767                         let elapsed = current_time.elapsed();
3768                         let result = *guard;
3769                         if result || elapsed >= max_wait {
3770                                 *guard = false;
3771                                 return result;
3772                         }
3773                         match max_wait.checked_sub(elapsed) {
3774                                 None => return result,
3775                                 Some(_) => continue
3776                         }
3777                 }
3778         }
3779
3780         // Signal to the ChannelManager persister that there are updates necessitating persisting to disk.
3781         fn notify(&self) {
3782                 let &(ref persist_mtx, ref cnd) = &self.persistence_lock;
3783                 let mut persistence_lock = persist_mtx.lock().unwrap();
3784                 *persistence_lock = true;
3785                 mem::drop(persistence_lock);
3786                 cnd.notify_all();
3787         }
3788 }
3789
3790 const SERIALIZATION_VERSION: u8 = 1;
3791 const MIN_SERIALIZATION_VERSION: u8 = 1;
3792
3793 impl Writeable for PendingHTLCInfo {
3794         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3795                 match &self.routing {
3796                         &PendingHTLCRouting::Forward { ref onion_packet, ref short_channel_id } => {
3797                                 0u8.write(writer)?;
3798                                 onion_packet.write(writer)?;
3799                                 short_channel_id.write(writer)?;
3800                         },
3801                         &PendingHTLCRouting::Receive { ref payment_data, ref incoming_cltv_expiry } => {
3802                                 1u8.write(writer)?;
3803                                 payment_data.write(writer)?;
3804                                 incoming_cltv_expiry.write(writer)?;
3805                         },
3806                 }
3807                 self.incoming_shared_secret.write(writer)?;
3808                 self.payment_hash.write(writer)?;
3809                 self.amt_to_forward.write(writer)?;
3810                 self.outgoing_cltv_value.write(writer)?;
3811                 Ok(())
3812         }
3813 }
3814
3815 impl Readable for PendingHTLCInfo {
3816         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<PendingHTLCInfo, DecodeError> {
3817                 Ok(PendingHTLCInfo {
3818                         routing: match Readable::read(reader)? {
3819                                 0u8 => PendingHTLCRouting::Forward {
3820                                         onion_packet: Readable::read(reader)?,
3821                                         short_channel_id: Readable::read(reader)?,
3822                                 },
3823                                 1u8 => PendingHTLCRouting::Receive {
3824                                         payment_data: Readable::read(reader)?,
3825                                         incoming_cltv_expiry: Readable::read(reader)?,
3826                                 },
3827                                 _ => return Err(DecodeError::InvalidValue),
3828                         },
3829                         incoming_shared_secret: Readable::read(reader)?,
3830                         payment_hash: Readable::read(reader)?,
3831                         amt_to_forward: Readable::read(reader)?,
3832                         outgoing_cltv_value: Readable::read(reader)?,
3833                 })
3834         }
3835 }
3836
3837 impl Writeable for HTLCFailureMsg {
3838         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3839                 match self {
3840                         &HTLCFailureMsg::Relay(ref fail_msg) => {
3841                                 0u8.write(writer)?;
3842                                 fail_msg.write(writer)?;
3843                         },
3844                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
3845                                 1u8.write(writer)?;
3846                                 fail_msg.write(writer)?;
3847                         }
3848                 }
3849                 Ok(())
3850         }
3851 }
3852
3853 impl Readable for HTLCFailureMsg {
3854         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3855                 match <u8 as Readable>::read(reader)? {
3856                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3857                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3858                         _ => Err(DecodeError::InvalidValue),
3859                 }
3860         }
3861 }
3862
3863 impl Writeable for PendingHTLCStatus {
3864         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3865                 match self {
3866                         &PendingHTLCStatus::Forward(ref forward_info) => {
3867                                 0u8.write(writer)?;
3868                                 forward_info.write(writer)?;
3869                         },
3870                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3871                                 1u8.write(writer)?;
3872                                 fail_msg.write(writer)?;
3873                         }
3874                 }
3875                 Ok(())
3876         }
3877 }
3878
3879 impl Readable for PendingHTLCStatus {
3880         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3881                 match <u8 as Readable>::read(reader)? {
3882                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3883                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3884                         _ => Err(DecodeError::InvalidValue),
3885                 }
3886         }
3887 }
3888
3889 impl_writeable!(HTLCPreviousHopData, 0, {
3890         short_channel_id,
3891         outpoint,
3892         htlc_id,
3893         incoming_packet_shared_secret
3894 });
3895
3896 impl_writeable!(ClaimableHTLC, 0, {
3897         prev_hop,
3898         value,
3899         payment_data,
3900         cltv_expiry
3901 });
3902
3903 impl Writeable for HTLCSource {
3904         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3905                 match self {
3906                         &HTLCSource::PreviousHopData(ref hop_data) => {
3907                                 0u8.write(writer)?;
3908                                 hop_data.write(writer)?;
3909                         },
3910                         &HTLCSource::OutboundRoute { ref path, ref session_priv, ref first_hop_htlc_msat } => {
3911                                 1u8.write(writer)?;
3912                                 path.write(writer)?;
3913                                 session_priv.write(writer)?;
3914                                 first_hop_htlc_msat.write(writer)?;
3915                         }
3916                 }
3917                 Ok(())
3918         }
3919 }
3920
3921 impl Readable for HTLCSource {
3922         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3923                 match <u8 as Readable>::read(reader)? {
3924                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3925                         1 => Ok(HTLCSource::OutboundRoute {
3926                                 path: Readable::read(reader)?,
3927                                 session_priv: Readable::read(reader)?,
3928                                 first_hop_htlc_msat: Readable::read(reader)?,
3929                         }),
3930                         _ => Err(DecodeError::InvalidValue),
3931                 }
3932         }
3933 }
3934
3935 impl Writeable for HTLCFailReason {
3936         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3937                 match self {
3938                         &HTLCFailReason::LightningError { ref err } => {
3939                                 0u8.write(writer)?;
3940                                 err.write(writer)?;
3941                         },
3942                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3943                                 1u8.write(writer)?;
3944                                 failure_code.write(writer)?;
3945                                 data.write(writer)?;
3946                         }
3947                 }
3948                 Ok(())
3949         }
3950 }
3951
3952 impl Readable for HTLCFailReason {
3953         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3954                 match <u8 as Readable>::read(reader)? {
3955                         0 => Ok(HTLCFailReason::LightningError { err: Readable::read(reader)? }),
3956                         1 => Ok(HTLCFailReason::Reason {
3957                                 failure_code: Readable::read(reader)?,
3958                                 data: Readable::read(reader)?,
3959                         }),
3960                         _ => Err(DecodeError::InvalidValue),
3961                 }
3962         }
3963 }
3964
3965 impl Writeable for HTLCForwardInfo {
3966         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3967                 match self {
3968                         &HTLCForwardInfo::AddHTLC { ref prev_short_channel_id, ref prev_funding_outpoint, ref prev_htlc_id, ref forward_info } => {
3969                                 0u8.write(writer)?;
3970                                 prev_short_channel_id.write(writer)?;
3971                                 prev_funding_outpoint.write(writer)?;
3972                                 prev_htlc_id.write(writer)?;
3973                                 forward_info.write(writer)?;
3974                         },
3975                         &HTLCForwardInfo::FailHTLC { ref htlc_id, ref err_packet } => {
3976                                 1u8.write(writer)?;
3977                                 htlc_id.write(writer)?;
3978                                 err_packet.write(writer)?;
3979                         },
3980                 }
3981                 Ok(())
3982         }
3983 }
3984
3985 impl Readable for HTLCForwardInfo {
3986         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCForwardInfo, DecodeError> {
3987                 match <u8 as Readable>::read(reader)? {
3988                         0 => Ok(HTLCForwardInfo::AddHTLC {
3989                                 prev_short_channel_id: Readable::read(reader)?,
3990                                 prev_funding_outpoint: Readable::read(reader)?,
3991                                 prev_htlc_id: Readable::read(reader)?,
3992                                 forward_info: Readable::read(reader)?,
3993                         }),
3994                         1 => Ok(HTLCForwardInfo::FailHTLC {
3995                                 htlc_id: Readable::read(reader)?,
3996                                 err_packet: Readable::read(reader)?,
3997                         }),
3998                         _ => Err(DecodeError::InvalidValue),
3999                 }
4000         }
4001 }
4002
4003 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable for ChannelManager<Signer, M, T, K, F, L>
4004         where M::Target: chain::Watch<Signer>,
4005         T::Target: BroadcasterInterface,
4006         K::Target: KeysInterface<Signer = Signer>,
4007         F::Target: FeeEstimator,
4008         L::Target: Logger,
4009 {
4010         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
4011                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
4012
4013                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
4014                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
4015
4016                 self.genesis_hash.write(writer)?;
4017                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
4018                 self.last_block_hash.read().unwrap().write(writer)?;
4019
4020                 let channel_state = self.channel_state.lock().unwrap();
4021                 let mut unfunded_channels = 0;
4022                 for (_, channel) in channel_state.by_id.iter() {
4023                         if !channel.is_funding_initiated() {
4024                                 unfunded_channels += 1;
4025                         }
4026                 }
4027                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
4028                 for (_, channel) in channel_state.by_id.iter() {
4029                         if channel.is_funding_initiated() {
4030                                 channel.write(writer)?;
4031                         }
4032                 }
4033
4034                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
4035                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
4036                         short_channel_id.write(writer)?;
4037                         (pending_forwards.len() as u64).write(writer)?;
4038                         for forward in pending_forwards {
4039                                 forward.write(writer)?;
4040                         }
4041                 }
4042
4043                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
4044                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
4045                         payment_hash.write(writer)?;
4046                         (previous_hops.len() as u64).write(writer)?;
4047                         for htlc in previous_hops.iter() {
4048                                 htlc.write(writer)?;
4049                         }
4050                 }
4051
4052                 let per_peer_state = self.per_peer_state.write().unwrap();
4053                 (per_peer_state.len() as u64).write(writer)?;
4054                 for (peer_pubkey, peer_state_mutex) in per_peer_state.iter() {
4055                         peer_pubkey.write(writer)?;
4056                         let peer_state = peer_state_mutex.lock().unwrap();
4057                         peer_state.latest_features.write(writer)?;
4058                 }
4059
4060                 let events = self.pending_events.lock().unwrap();
4061                 (events.len() as u64).write(writer)?;
4062                 for event in events.iter() {
4063                         event.write(writer)?;
4064                 }
4065
4066                 let background_events = self.pending_background_events.lock().unwrap();
4067                 (background_events.len() as u64).write(writer)?;
4068                 for event in background_events.iter() {
4069                         match event {
4070                                 BackgroundEvent::ClosingMonitorUpdate((funding_txo, monitor_update)) => {
4071                                         0u8.write(writer)?;
4072                                         funding_txo.write(writer)?;
4073                                         monitor_update.write(writer)?;
4074                                 },
4075                         }
4076                 }
4077
4078                 (self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
4079
4080                 Ok(())
4081         }
4082 }
4083
4084 /// Arguments for the creation of a ChannelManager that are not deserialized.
4085 ///
4086 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
4087 /// is:
4088 /// 1) Deserialize all stored ChannelMonitors.
4089 /// 2) Deserialize the ChannelManager by filling in this struct and calling:
4090 ///    <(BlockHash, ChannelManager)>::read(reader, args)
4091 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
4092 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
4093 /// 3) If you are not fetching full blocks, register all relevant ChannelMonitor outpoints the same
4094 ///    way you would handle a `chain::Filter` call using ChannelMonitor::get_outputs_to_watch() and
4095 ///    ChannelMonitor::get_funding_txo().
4096 /// 4) Reconnect blocks on your ChannelMonitors.
4097 /// 5) Disconnect/connect blocks on the ChannelManager.
4098 /// 6) Move the ChannelMonitors into your local chain::Watch.
4099 ///
4100 /// Note that the ordering of #4-6 is not of importance, however all three must occur before you
4101 /// call any other methods on the newly-deserialized ChannelManager.
4102 ///
4103 /// Note that because some channels may be closed during deserialization, it is critical that you
4104 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
4105 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
4106 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
4107 /// not force-close the same channels but consider them live), you may end up revoking a state for
4108 /// which you've already broadcasted the transaction.
4109 pub struct ChannelManagerReadArgs<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4110         where M::Target: chain::Watch<Signer>,
4111         T::Target: BroadcasterInterface,
4112         K::Target: KeysInterface<Signer = Signer>,
4113         F::Target: FeeEstimator,
4114         L::Target: Logger,
4115 {
4116         /// The keys provider which will give us relevant keys. Some keys will be loaded during
4117         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
4118         /// signing data.
4119         pub keys_manager: K,
4120
4121         /// The fee_estimator for use in the ChannelManager in the future.
4122         ///
4123         /// No calls to the FeeEstimator will be made during deserialization.
4124         pub fee_estimator: F,
4125         /// The chain::Watch for use in the ChannelManager in the future.
4126         ///
4127         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
4128         /// you have deserialized ChannelMonitors separately and will add them to your
4129         /// chain::Watch after deserializing this ChannelManager.
4130         pub chain_monitor: M,
4131
4132         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
4133         /// used to broadcast the latest local commitment transactions of channels which must be
4134         /// force-closed during deserialization.
4135         pub tx_broadcaster: T,
4136         /// The Logger for use in the ChannelManager and which may be used to log information during
4137         /// deserialization.
4138         pub logger: L,
4139         /// Default settings used for new channels. Any existing channels will continue to use the
4140         /// runtime settings which were stored when the ChannelManager was serialized.
4141         pub default_config: UserConfig,
4142
4143         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
4144         /// value.get_funding_txo() should be the key).
4145         ///
4146         /// If a monitor is inconsistent with the channel state during deserialization the channel will
4147         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
4148         /// is true for missing channels as well. If there is a monitor missing for which we find
4149         /// channel data Err(DecodeError::InvalidValue) will be returned.
4150         ///
4151         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
4152         /// this struct.
4153         ///
4154         /// (C-not exported) because we have no HashMap bindings
4155         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<Signer>>,
4156 }
4157
4158 impl<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4159                 ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>
4160         where M::Target: chain::Watch<Signer>,
4161                 T::Target: BroadcasterInterface,
4162                 K::Target: KeysInterface<Signer = Signer>,
4163                 F::Target: FeeEstimator,
4164                 L::Target: Logger,
4165         {
4166         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
4167         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
4168         /// populate a HashMap directly from C.
4169         pub fn new(keys_manager: K, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, logger: L, default_config: UserConfig,
4170                         mut channel_monitors: Vec<&'a mut ChannelMonitor<Signer>>) -> Self {
4171                 Self {
4172                         keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, default_config,
4173                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
4174                 }
4175         }
4176 }
4177
4178 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
4179 // SipmleArcChannelManager type:
4180 impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4181         ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, Arc<ChannelManager<Signer, M, T, K, F, L>>)
4182         where M::Target: chain::Watch<Signer>,
4183         T::Target: BroadcasterInterface,
4184         K::Target: KeysInterface<Signer = Signer>,
4185         F::Target: FeeEstimator,
4186         L::Target: Logger,
4187 {
4188         fn read<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
4189                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<Signer, M, T, K, F, L>)>::read(reader, args)?;
4190                 Ok((blockhash, Arc::new(chan_manager)))
4191         }
4192 }
4193
4194 impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4195         ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, ChannelManager<Signer, M, T, K, F, L>)
4196         where M::Target: chain::Watch<Signer>,
4197         T::Target: BroadcasterInterface,
4198         K::Target: KeysInterface<Signer = Signer>,
4199         F::Target: FeeEstimator,
4200         L::Target: Logger,
4201 {
4202         fn read<R: ::std::io::Read>(reader: &mut R, mut args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
4203                 let _ver: u8 = Readable::read(reader)?;
4204                 let min_ver: u8 = Readable::read(reader)?;
4205                 if min_ver > SERIALIZATION_VERSION {
4206                         return Err(DecodeError::UnknownVersion);
4207                 }
4208
4209                 let genesis_hash: BlockHash = Readable::read(reader)?;
4210                 let latest_block_height: u32 = Readable::read(reader)?;
4211                 let last_block_hash: BlockHash = Readable::read(reader)?;
4212
4213                 let mut failed_htlcs = Vec::new();
4214
4215                 let channel_count: u64 = Readable::read(reader)?;
4216                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
4217                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
4218                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
4219                 for _ in 0..channel_count {
4220                         let mut channel: Channel<Signer> = Channel::read(reader, &args.keys_manager)?;
4221                         let funding_txo = channel.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
4222                         funding_txo_set.insert(funding_txo.clone());
4223                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
4224                                 if channel.get_cur_holder_commitment_transaction_number() < monitor.get_cur_holder_commitment_number() ||
4225                                                 channel.get_revoked_counterparty_commitment_transaction_number() < monitor.get_min_seen_secret() ||
4226                                                 channel.get_cur_counterparty_commitment_transaction_number() < monitor.get_cur_counterparty_commitment_number() ||
4227                                                 channel.get_latest_monitor_update_id() > monitor.get_latest_update_id() {
4228                                         // If the channel is ahead of the monitor, return InvalidValue:
4229                                         return Err(DecodeError::InvalidValue);
4230                                 } else if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
4231                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
4232                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
4233                                                 channel.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
4234                                         // But if the channel is behind of the monitor, close the channel:
4235                                         let (_, mut new_failed_htlcs) = channel.force_shutdown(true);
4236                                         failed_htlcs.append(&mut new_failed_htlcs);
4237                                         monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
4238                                 } else {
4239                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
4240                                                 short_to_id.insert(short_channel_id, channel.channel_id());
4241                                         }
4242                                         by_id.insert(channel.channel_id(), channel);
4243                                 }
4244                         } else {
4245                                 return Err(DecodeError::InvalidValue);
4246                         }
4247                 }
4248
4249                 for (ref funding_txo, ref mut monitor) in args.channel_monitors.iter_mut() {
4250                         if !funding_txo_set.contains(funding_txo) {
4251                                 monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
4252                         }
4253                 }
4254
4255                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
4256                 let forward_htlcs_count: u64 = Readable::read(reader)?;
4257                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
4258                 for _ in 0..forward_htlcs_count {
4259                         let short_channel_id = Readable::read(reader)?;
4260                         let pending_forwards_count: u64 = Readable::read(reader)?;
4261                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
4262                         for _ in 0..pending_forwards_count {
4263                                 pending_forwards.push(Readable::read(reader)?);
4264                         }
4265                         forward_htlcs.insert(short_channel_id, pending_forwards);
4266                 }
4267
4268                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
4269                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
4270                 for _ in 0..claimable_htlcs_count {
4271                         let payment_hash = Readable::read(reader)?;
4272                         let previous_hops_len: u64 = Readable::read(reader)?;
4273                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
4274                         for _ in 0..previous_hops_len {
4275                                 previous_hops.push(Readable::read(reader)?);
4276                         }
4277                         claimable_htlcs.insert(payment_hash, previous_hops);
4278                 }
4279
4280                 let peer_count: u64 = Readable::read(reader)?;
4281                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState>)>()));
4282                 for _ in 0..peer_count {
4283                         let peer_pubkey = Readable::read(reader)?;
4284                         let peer_state = PeerState {
4285                                 latest_features: Readable::read(reader)?,
4286                         };
4287                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
4288                 }
4289
4290                 let event_count: u64 = Readable::read(reader)?;
4291                 let mut pending_events_read: Vec<events::Event> = Vec::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<events::Event>()));
4292                 for _ in 0..event_count {
4293                         match MaybeReadable::read(reader)? {
4294                                 Some(event) => pending_events_read.push(event),
4295                                 None => continue,
4296                         }
4297                 }
4298
4299                 let background_event_count: u64 = Readable::read(reader)?;
4300                 let mut pending_background_events_read: Vec<BackgroundEvent> = Vec::with_capacity(cmp::min(background_event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<BackgroundEvent>()));
4301                 for _ in 0..background_event_count {
4302                         match <u8 as Readable>::read(reader)? {
4303                                 0 => pending_background_events_read.push(BackgroundEvent::ClosingMonitorUpdate((Readable::read(reader)?, Readable::read(reader)?))),
4304                                 _ => return Err(DecodeError::InvalidValue),
4305                         }
4306                 }
4307
4308                 let last_node_announcement_serial: u32 = Readable::read(reader)?;
4309
4310                 let mut secp_ctx = Secp256k1::new();
4311                 secp_ctx.seeded_randomize(&args.keys_manager.get_secure_random_bytes());
4312
4313                 let channel_manager = ChannelManager {
4314                         genesis_hash,
4315                         fee_estimator: args.fee_estimator,
4316                         chain_monitor: args.chain_monitor,
4317                         tx_broadcaster: args.tx_broadcaster,
4318
4319                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
4320                         last_block_hash: RwLock::new(last_block_hash),
4321                         secp_ctx,
4322
4323                         channel_state: Mutex::new(ChannelHolder {
4324                                 by_id,
4325                                 short_to_id,
4326                                 forward_htlcs,
4327                                 claimable_htlcs,
4328                                 pending_msg_events: Vec::new(),
4329                         }),
4330                         our_network_key: args.keys_manager.get_node_secret(),
4331
4332                         last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
4333
4334                         per_peer_state: RwLock::new(per_peer_state),
4335
4336                         pending_events: Mutex::new(pending_events_read),
4337                         pending_background_events: Mutex::new(pending_background_events_read),
4338                         total_consistency_lock: RwLock::new(()),
4339                         persistence_notifier: PersistenceNotifier::new(),
4340
4341                         keys_manager: args.keys_manager,
4342                         logger: args.logger,
4343                         default_configuration: args.default_config,
4344                 };
4345
4346                 for htlc_source in failed_htlcs.drain(..) {
4347                         channel_manager.fail_htlc_backwards_internal(channel_manager.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
4348                 }
4349
4350                 //TODO: Broadcast channel update for closed channels, but only after we've made a
4351                 //connection or two.
4352
4353                 Ok((last_block_hash.clone(), channel_manager))
4354         }
4355 }
4356
4357 #[cfg(test)]
4358 mod tests {
4359         use ln::channelmanager::PersistenceNotifier;
4360         use std::sync::Arc;
4361         use std::sync::atomic::{AtomicBool, Ordering};
4362         use std::thread;
4363         use std::time::Duration;
4364
4365         #[test]
4366         fn test_wait_timeout() {
4367                 let persistence_notifier = Arc::new(PersistenceNotifier::new());
4368                 let thread_notifier = Arc::clone(&persistence_notifier);
4369
4370                 let exit_thread = Arc::new(AtomicBool::new(false));
4371                 let exit_thread_clone = exit_thread.clone();
4372                 thread::spawn(move || {
4373                         loop {
4374                                 let &(ref persist_mtx, ref cnd) = &thread_notifier.persistence_lock;
4375                                 let mut persistence_lock = persist_mtx.lock().unwrap();
4376                                 *persistence_lock = true;
4377                                 cnd.notify_all();
4378
4379                                 if exit_thread_clone.load(Ordering::SeqCst) {
4380                                         break
4381                                 }
4382                         }
4383                 });
4384
4385                 // Check that we can block indefinitely until updates are available.
4386                 let _ = persistence_notifier.wait();
4387
4388                 // Check that the PersistenceNotifier will return after the given duration if updates are
4389                 // available.
4390                 loop {
4391                         if persistence_notifier.wait_timeout(Duration::from_millis(100)) {
4392                                 break
4393                         }
4394                 }
4395
4396                 exit_thread.store(true, Ordering::SeqCst);
4397
4398                 // Check that the PersistenceNotifier will return after the given duration even if no updates
4399                 // are available.
4400                 loop {
4401                         if !persistence_notifier.wait_timeout(Duration::from_millis(100)) {
4402                                 break
4403                         }
4404                 }
4405         }
4406 }