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