]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/channelmanager.rs
3a399844a63c42f4854b51d5eeab8c29e3258cde
[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 [`Router`] 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 use bitcoin::blockdata::block::BlockHeader;
21 use bitcoin::blockdata::transaction::Transaction;
22 use bitcoin::blockdata::constants::genesis_block;
23 use bitcoin::network::constants::Network;
24
25 use bitcoin::hashes::Hash;
26 use bitcoin::hashes::sha256::Hash as Sha256;
27 use bitcoin::hash_types::{BlockHash, Txid};
28
29 use bitcoin::secp256k1::{SecretKey,PublicKey};
30 use bitcoin::secp256k1::Secp256k1;
31 use bitcoin::{LockTime, secp256k1, Sequence};
32
33 use crate::chain;
34 use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
35 use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
36 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent, CLOSED_CHANNEL_UPDATE_ID};
37 use crate::chain::transaction::{OutPoint, TransactionData};
38 // Since this struct is returned in `list_channels` methods, expose it here in case users want to
39 // construct one themselves.
40 use crate::ln::{inbound_payment, PaymentHash, PaymentPreimage, PaymentSecret};
41 use crate::ln::channel::{Channel, ChannelError, ChannelUpdateStatus, UpdateFulfillCommitFetch};
42 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
43 #[cfg(any(feature = "_test_utils", test))]
44 use crate::ln::features::InvoiceFeatures;
45 use crate::routing::gossip::NetworkGraph;
46 use crate::routing::router::{DefaultRouter, InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters, RoutePath, Router};
47 use crate::routing::scoring::ProbabilisticScorer;
48 use crate::ln::msgs;
49 use crate::ln::onion_utils;
50 use crate::ln::onion_utils::HTLCFailReason;
51 use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, MAX_VALUE_MSAT};
52 #[cfg(test)]
53 use crate::ln::outbound_payment;
54 use crate::ln::outbound_payment::{OutboundPayments, PaymentAttempts, PendingOutboundPayment};
55 use crate::ln::wire::Encode;
56 use crate::chain::keysinterface::{EntropySource, KeysManager, NodeSigner, Recipient, SignerProvider, ChannelSigner, WriteableEcdsaChannelSigner};
57 use crate::util::config::{UserConfig, ChannelConfig};
58 use crate::util::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
59 use crate::util::events;
60 use crate::util::wakers::{Future, Notifier};
61 use crate::util::scid_utils::fake_scid;
62 use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
63 use crate::util::logger::{Level, Logger};
64 use crate::util::errors::APIError;
65
66 use alloc::collections::BTreeMap;
67
68 use crate::io;
69 use crate::prelude::*;
70 use core::{cmp, mem};
71 use core::cell::RefCell;
72 use crate::io::Read;
73 use crate::sync::{Arc, Mutex, RwLock, RwLockReadGuard, FairRwLock, LockTestExt, LockHeldState};
74 use core::sync::atomic::{AtomicUsize, Ordering};
75 use core::time::Duration;
76 use core::ops::Deref;
77
78 // Re-export this for use in the public API.
79 pub use crate::ln::outbound_payment::{PaymentSendFailure, Retry, RetryableSendFailure};
80
81 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
82 //
83 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
84 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
85 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
86 //
87 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
88 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
89 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
90 // before we forward it.
91 //
92 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
93 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
94 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
95 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
96 // our payment, which we can use to decode errors or inform the user that the payment was sent.
97
98 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
99 pub(super) enum PendingHTLCRouting {
100         Forward {
101                 onion_packet: msgs::OnionPacket,
102                 /// The SCID from the onion that we should forward to. This could be a real SCID or a fake one
103                 /// generated using `get_fake_scid` from the scid_utils::fake_scid module.
104                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
105         },
106         Receive {
107                 payment_data: msgs::FinalOnionHopData,
108                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
109                 phantom_shared_secret: Option<[u8; 32]>,
110         },
111         ReceiveKeysend {
112                 payment_preimage: PaymentPreimage,
113                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
114         },
115 }
116
117 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
118 pub(super) struct PendingHTLCInfo {
119         pub(super) routing: PendingHTLCRouting,
120         pub(super) incoming_shared_secret: [u8; 32],
121         payment_hash: PaymentHash,
122         pub(super) incoming_amt_msat: Option<u64>, // Added in 0.0.113
123         pub(super) outgoing_amt_msat: u64,
124         pub(super) outgoing_cltv_value: u32,
125 }
126
127 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
128 pub(super) enum HTLCFailureMsg {
129         Relay(msgs::UpdateFailHTLC),
130         Malformed(msgs::UpdateFailMalformedHTLC),
131 }
132
133 /// Stores whether we can't forward an HTLC or relevant forwarding info
134 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
135 pub(super) enum PendingHTLCStatus {
136         Forward(PendingHTLCInfo),
137         Fail(HTLCFailureMsg),
138 }
139
140 pub(super) struct PendingAddHTLCInfo {
141         pub(super) forward_info: PendingHTLCInfo,
142
143         // These fields are produced in `forward_htlcs()` and consumed in
144         // `process_pending_htlc_forwards()` for constructing the
145         // `HTLCSource::PreviousHopData` for failed and forwarded
146         // HTLCs.
147         //
148         // Note that this may be an outbound SCID alias for the associated channel.
149         prev_short_channel_id: u64,
150         prev_htlc_id: u64,
151         prev_funding_outpoint: OutPoint,
152         prev_user_channel_id: u128,
153 }
154
155 pub(super) enum HTLCForwardInfo {
156         AddHTLC(PendingAddHTLCInfo),
157         FailHTLC {
158                 htlc_id: u64,
159                 err_packet: msgs::OnionErrorPacket,
160         },
161 }
162
163 /// Tracks the inbound corresponding to an outbound HTLC
164 #[derive(Clone, Hash, PartialEq, Eq)]
165 pub(crate) struct HTLCPreviousHopData {
166         // Note that this may be an outbound SCID alias for the associated channel.
167         short_channel_id: u64,
168         htlc_id: u64,
169         incoming_packet_shared_secret: [u8; 32],
170         phantom_shared_secret: Option<[u8; 32]>,
171
172         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
173         // channel with a preimage provided by the forward channel.
174         outpoint: OutPoint,
175 }
176
177 enum OnionPayload {
178         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
179         Invoice {
180                 /// This is only here for backwards-compatibility in serialization, in the future it can be
181                 /// removed, breaking clients running 0.0.106 and earlier.
182                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
183         },
184         /// Contains the payer-provided preimage.
185         Spontaneous(PaymentPreimage),
186 }
187
188 /// HTLCs that are to us and can be failed/claimed by the user
189 struct ClaimableHTLC {
190         prev_hop: HTLCPreviousHopData,
191         cltv_expiry: u32,
192         /// The amount (in msats) of this MPP part
193         value: u64,
194         onion_payload: OnionPayload,
195         timer_ticks: u8,
196         /// The sum total of all MPP parts
197         total_msat: u64,
198 }
199
200 /// A payment identifier used to uniquely identify a payment to LDK.
201 ///
202 /// This is not exported to bindings users as we just use [u8; 32] directly
203 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
204 pub struct PaymentId(pub [u8; 32]);
205
206 impl Writeable for PaymentId {
207         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
208                 self.0.write(w)
209         }
210 }
211
212 impl Readable for PaymentId {
213         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
214                 let buf: [u8; 32] = Readable::read(r)?;
215                 Ok(PaymentId(buf))
216         }
217 }
218
219 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
220 ///
221 /// This is not exported to bindings users as we just use [u8; 32] directly
222 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
223 pub struct InterceptId(pub [u8; 32]);
224
225 impl Writeable for InterceptId {
226         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
227                 self.0.write(w)
228         }
229 }
230
231 impl Readable for InterceptId {
232         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
233                 let buf: [u8; 32] = Readable::read(r)?;
234                 Ok(InterceptId(buf))
235         }
236 }
237
238 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
239 /// Uniquely describes an HTLC by its source. Just the guaranteed-unique subset of [`HTLCSource`].
240 pub(crate) enum SentHTLCId {
241         PreviousHopData { short_channel_id: u64, htlc_id: u64 },
242         OutboundRoute { session_priv: SecretKey },
243 }
244 impl SentHTLCId {
245         pub(crate) fn from_source(source: &HTLCSource) -> Self {
246                 match source {
247                         HTLCSource::PreviousHopData(hop_data) => Self::PreviousHopData {
248                                 short_channel_id: hop_data.short_channel_id,
249                                 htlc_id: hop_data.htlc_id,
250                         },
251                         HTLCSource::OutboundRoute { session_priv, .. } =>
252                                 Self::OutboundRoute { session_priv: *session_priv },
253                 }
254         }
255 }
256 impl_writeable_tlv_based_enum!(SentHTLCId,
257         (0, PreviousHopData) => {
258                 (0, short_channel_id, required),
259                 (2, htlc_id, required),
260         },
261         (2, OutboundRoute) => {
262                 (0, session_priv, required),
263         };
264 );
265
266
267 /// Tracks the inbound corresponding to an outbound HTLC
268 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
269 #[derive(Clone, PartialEq, Eq)]
270 pub(crate) enum HTLCSource {
271         PreviousHopData(HTLCPreviousHopData),
272         OutboundRoute {
273                 path: Vec<RouteHop>,
274                 session_priv: SecretKey,
275                 /// Technically we can recalculate this from the route, but we cache it here to avoid
276                 /// doing a double-pass on route when we get a failure back
277                 first_hop_htlc_msat: u64,
278                 payment_id: PaymentId,
279                 payment_secret: Option<PaymentSecret>,
280         },
281 }
282 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
283 impl core::hash::Hash for HTLCSource {
284         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
285                 match self {
286                         HTLCSource::PreviousHopData(prev_hop_data) => {
287                                 0u8.hash(hasher);
288                                 prev_hop_data.hash(hasher);
289                         },
290                         HTLCSource::OutboundRoute { path, session_priv, payment_id, payment_secret, first_hop_htlc_msat } => {
291                                 1u8.hash(hasher);
292                                 path.hash(hasher);
293                                 session_priv[..].hash(hasher);
294                                 payment_id.hash(hasher);
295                                 payment_secret.hash(hasher);
296                                 first_hop_htlc_msat.hash(hasher);
297                         },
298                 }
299         }
300 }
301 #[cfg(not(feature = "grind_signatures"))]
302 #[cfg(test)]
303 impl HTLCSource {
304         pub fn dummy() -> Self {
305                 HTLCSource::OutboundRoute {
306                         path: Vec::new(),
307                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
308                         first_hop_htlc_msat: 0,
309                         payment_id: PaymentId([2; 32]),
310                         payment_secret: None,
311                 }
312         }
313 }
314
315 struct ReceiveError {
316         err_code: u16,
317         err_data: Vec<u8>,
318         msg: &'static str,
319 }
320
321 /// This enum is used to specify which error data to send to peers when failing back an HTLC
322 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
323 ///
324 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
325 #[derive(Clone, Copy)]
326 pub enum FailureCode {
327         /// We had a temporary error processing the payment. Useful if no other error codes fit
328         /// and you want to indicate that the payer may want to retry.
329         TemporaryNodeFailure             = 0x2000 | 2,
330         /// We have a required feature which was not in this onion. For example, you may require
331         /// some additional metadata that was not provided with this payment.
332         RequiredNodeFeatureMissing       = 0x4000 | 0x2000 | 3,
333         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
334         /// the HTLC is too close to the current block height for safe handling.
335         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
336         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
337         IncorrectOrUnknownPaymentDetails = 0x4000 | 15,
338 }
339
340 type ShutdownResult = (Option<(OutPoint, ChannelMonitorUpdate)>, Vec<(HTLCSource, PaymentHash, PublicKey, [u8; 32])>);
341
342 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
343 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
344 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
345 /// peer_state lock. We then return the set of things that need to be done outside the lock in
346 /// this struct and call handle_error!() on it.
347
348 struct MsgHandleErrInternal {
349         err: msgs::LightningError,
350         chan_id: Option<([u8; 32], u128)>, // If Some a channel of ours has been closed
351         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
352 }
353 impl MsgHandleErrInternal {
354         #[inline]
355         fn send_err_msg_no_close(err: String, channel_id: [u8; 32]) -> Self {
356                 Self {
357                         err: LightningError {
358                                 err: err.clone(),
359                                 action: msgs::ErrorAction::SendErrorMessage {
360                                         msg: msgs::ErrorMessage {
361                                                 channel_id,
362                                                 data: err
363                                         },
364                                 },
365                         },
366                         chan_id: None,
367                         shutdown_finish: None,
368                 }
369         }
370         #[inline]
371         fn from_no_close(err: msgs::LightningError) -> Self {
372                 Self { err, chan_id: None, shutdown_finish: None }
373         }
374         #[inline]
375         fn from_finish_shutdown(err: String, channel_id: [u8; 32], user_channel_id: u128, shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
376                 Self {
377                         err: LightningError {
378                                 err: err.clone(),
379                                 action: msgs::ErrorAction::SendErrorMessage {
380                                         msg: msgs::ErrorMessage {
381                                                 channel_id,
382                                                 data: err
383                                         },
384                                 },
385                         },
386                         chan_id: Some((channel_id, user_channel_id)),
387                         shutdown_finish: Some((shutdown_res, channel_update)),
388                 }
389         }
390         #[inline]
391         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
392                 Self {
393                         err: match err {
394                                 ChannelError::Warn(msg) =>  LightningError {
395                                         err: msg.clone(),
396                                         action: msgs::ErrorAction::SendWarningMessage {
397                                                 msg: msgs::WarningMessage {
398                                                         channel_id,
399                                                         data: msg
400                                                 },
401                                                 log_level: Level::Warn,
402                                         },
403                                 },
404                                 ChannelError::Ignore(msg) => LightningError {
405                                         err: msg,
406                                         action: msgs::ErrorAction::IgnoreError,
407                                 },
408                                 ChannelError::Close(msg) => LightningError {
409                                         err: msg.clone(),
410                                         action: msgs::ErrorAction::SendErrorMessage {
411                                                 msg: msgs::ErrorMessage {
412                                                         channel_id,
413                                                         data: msg
414                                                 },
415                                         },
416                                 },
417                         },
418                         chan_id: None,
419                         shutdown_finish: None,
420                 }
421         }
422 }
423
424 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
425 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
426 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
427 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
428 pub(super) const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
429
430 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
431 /// be sent in the order they appear in the return value, however sometimes the order needs to be
432 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
433 /// they were originally sent). In those cases, this enum is also returned.
434 #[derive(Clone, PartialEq)]
435 pub(super) enum RAACommitmentOrder {
436         /// Send the CommitmentUpdate messages first
437         CommitmentFirst,
438         /// Send the RevokeAndACK message first
439         RevokeAndACKFirst,
440 }
441
442 /// Information about a payment which is currently being claimed.
443 struct ClaimingPayment {
444         amount_msat: u64,
445         payment_purpose: events::PaymentPurpose,
446         receiver_node_id: PublicKey,
447 }
448 impl_writeable_tlv_based!(ClaimingPayment, {
449         (0, amount_msat, required),
450         (2, payment_purpose, required),
451         (4, receiver_node_id, required),
452 });
453
454 /// Information about claimable or being-claimed payments
455 struct ClaimablePayments {
456         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
457         /// failed/claimed by the user.
458         ///
459         /// Note that, no consistency guarantees are made about the channels given here actually
460         /// existing anymore by the time you go to read them!
461         ///
462         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
463         /// we don't get a duplicate payment.
464         claimable_htlcs: HashMap<PaymentHash, (events::PaymentPurpose, Vec<ClaimableHTLC>)>,
465
466         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
467         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
468         /// as an [`events::Event::PaymentClaimed`].
469         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
470 }
471
472 /// Events which we process internally but cannot be procsesed immediately at the generation site
473 /// for some reason. They are handled in timer_tick_occurred, so may be processed with
474 /// quite some time lag.
475 enum BackgroundEvent {
476         /// Handle a ChannelMonitorUpdate that closes a channel, broadcasting its current latest holder
477         /// commitment transaction.
478         ClosingMonitorUpdate((OutPoint, ChannelMonitorUpdate)),
479 }
480
481 #[derive(Debug)]
482 pub(crate) enum MonitorUpdateCompletionAction {
483         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
484         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
485         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
486         /// event can be generated.
487         PaymentClaimed { payment_hash: PaymentHash },
488         /// Indicates an [`events::Event`] should be surfaced to the user.
489         EmitEvent { event: events::Event },
490 }
491
492 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
493         (0, PaymentClaimed) => { (0, payment_hash, required) },
494         (2, EmitEvent) => { (0, event, upgradable_required) },
495 );
496
497 /// State we hold per-peer.
498 pub(super) struct PeerState<Signer: ChannelSigner> {
499         /// `temporary_channel_id` or `channel_id` -> `channel`.
500         ///
501         /// Holds all channels where the peer is the counterparty. Once a channel has been assigned a
502         /// `channel_id`, the `temporary_channel_id` key in the map is updated and is replaced by the
503         /// `channel_id`.
504         pub(super) channel_by_id: HashMap<[u8; 32], Channel<Signer>>,
505         /// The latest `InitFeatures` we heard from the peer.
506         latest_features: InitFeatures,
507         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
508         /// for broadcast messages, where ordering isn't as strict).
509         pub(super) pending_msg_events: Vec<MessageSendEvent>,
510         /// Map from a specific channel to some action(s) that should be taken when all pending
511         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
512         ///
513         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
514         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
515         /// channels with a peer this will just be one allocation and will amount to a linear list of
516         /// channels to walk, avoiding the whole hashing rigmarole.
517         ///
518         /// Note that the channel may no longer exist. For example, if a channel was closed but we
519         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
520         /// for a missing channel. While a malicious peer could construct a second channel with the
521         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
522         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
523         /// duplicates do not occur, so such channels should fail without a monitor update completing.
524         monitor_update_blocked_actions: BTreeMap<[u8; 32], Vec<MonitorUpdateCompletionAction>>,
525         /// The peer is currently connected (i.e. we've seen a
526         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
527         /// [`ChannelMessageHandler::peer_disconnected`].
528         is_connected: bool,
529 }
530
531 impl <Signer: ChannelSigner> PeerState<Signer> {
532         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
533         /// If true is passed for `require_disconnected`, the function will return false if we haven't
534         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
535         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
536                 if require_disconnected && self.is_connected {
537                         return false
538                 }
539                 self.channel_by_id.is_empty() && self.monitor_update_blocked_actions.is_empty()
540         }
541 }
542
543 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
544 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
545 ///
546 /// For users who don't want to bother doing their own payment preimage storage, we also store that
547 /// here.
548 ///
549 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
550 /// and instead encoding it in the payment secret.
551 struct PendingInboundPayment {
552         /// The payment secret that the sender must use for us to accept this payment
553         payment_secret: PaymentSecret,
554         /// Time at which this HTLC expires - blocks with a header time above this value will result in
555         /// this payment being removed.
556         expiry_time: u64,
557         /// Arbitrary identifier the user specifies (or not)
558         user_payment_id: u64,
559         // Other required attributes of the payment, optionally enforced:
560         payment_preimage: Option<PaymentPreimage>,
561         min_value_msat: Option<u64>,
562 }
563
564 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
565 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
566 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
567 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
568 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
569 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
570 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
571 /// of [`KeysManager`] and [`DefaultRouter`].
572 ///
573 /// This is not exported to bindings users as Arcs don't make sense in bindings
574 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
575         Arc<M>,
576         Arc<T>,
577         Arc<KeysManager>,
578         Arc<KeysManager>,
579         Arc<KeysManager>,
580         Arc<F>,
581         Arc<DefaultRouter<
582                 Arc<NetworkGraph<Arc<L>>>,
583                 Arc<L>,
584                 Arc<Mutex<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>
585         >>,
586         Arc<L>
587 >;
588
589 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
590 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
591 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
592 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
593 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
594 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
595 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
596 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
597 /// of [`KeysManager`] and [`DefaultRouter`].
598 ///
599 /// This is not exported to bindings users as Arcs don't make sense in bindings
600 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> = ChannelManager<&'a M, &'b T, &'c KeysManager, &'c KeysManager, &'c KeysManager, &'d F, &'e DefaultRouter<&'f NetworkGraph<&'g L>, &'g L, &'h Mutex<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>>, &'g L>;
601
602 /// Manager which keeps track of a number of channels and sends messages to the appropriate
603 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
604 ///
605 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
606 /// to individual Channels.
607 ///
608 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
609 /// all peers during write/read (though does not modify this instance, only the instance being
610 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
611 /// called [`funding_transaction_generated`] for outbound channels) being closed.
612 ///
613 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
614 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST write each monitor update out to disk before
615 /// returning from [`chain::Watch::watch_channel`]/[`update_channel`], with ChannelManagers, writing updates
616 /// happens out-of-band (and will prevent any other `ChannelManager` operations from occurring during
617 /// the serialization process). If the deserialized version is out-of-date compared to the
618 /// [`ChannelMonitor`] passed by reference to [`read`], those channels will be force-closed based on the
619 /// `ChannelMonitor` state and no funds will be lost (mod on-chain transaction fees).
620 ///
621 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
622 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
623 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
624 ///
625 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
626 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
627 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
628 /// offline for a full minute. In order to track this, you must call
629 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
630 ///
631 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
632 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
633 /// not have a channel with being unable to connect to us or open new channels with us if we have
634 /// many peers with unfunded channels.
635 ///
636 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
637 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
638 /// never limited. Please ensure you limit the count of such channels yourself.
639 ///
640 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
641 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
642 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
643 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
644 /// you're using lightning-net-tokio.
645 ///
646 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
647 /// [`funding_created`]: msgs::FundingCreated
648 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
649 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
650 /// [`update_channel`]: chain::Watch::update_channel
651 /// [`ChannelUpdate`]: msgs::ChannelUpdate
652 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
653 /// [`read`]: ReadableArgs::read
654 //
655 // Lock order:
656 // The tree structure below illustrates the lock order requirements for the different locks of the
657 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
658 // and should then be taken in the order of the lowest to the highest level in the tree.
659 // Note that locks on different branches shall not be taken at the same time, as doing so will
660 // create a new lock order for those specific locks in the order they were taken.
661 //
662 // Lock order tree:
663 //
664 // `total_consistency_lock`
665 //  |
666 //  |__`forward_htlcs`
667 //  |   |
668 //  |   |__`pending_intercepted_htlcs`
669 //  |
670 //  |__`per_peer_state`
671 //  |   |
672 //  |   |__`pending_inbound_payments`
673 //  |       |
674 //  |       |__`claimable_payments`
675 //  |       |
676 //  |       |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
677 //  |           |
678 //  |           |__`peer_state`
679 //  |               |
680 //  |               |__`id_to_peer`
681 //  |               |
682 //  |               |__`short_to_chan_info`
683 //  |               |
684 //  |               |__`outbound_scid_aliases`
685 //  |               |
686 //  |               |__`best_block`
687 //  |               |
688 //  |               |__`pending_events`
689 //  |                   |
690 //  |                   |__`pending_background_events`
691 //
692 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
693 where
694         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
695         T::Target: BroadcasterInterface,
696         ES::Target: EntropySource,
697         NS::Target: NodeSigner,
698         SP::Target: SignerProvider,
699         F::Target: FeeEstimator,
700         R::Target: Router,
701         L::Target: Logger,
702 {
703         default_configuration: UserConfig,
704         genesis_hash: BlockHash,
705         fee_estimator: LowerBoundedFeeEstimator<F>,
706         chain_monitor: M,
707         tx_broadcaster: T,
708         #[allow(unused)]
709         router: R,
710
711         /// See `ChannelManager` struct-level documentation for lock order requirements.
712         #[cfg(test)]
713         pub(super) best_block: RwLock<BestBlock>,
714         #[cfg(not(test))]
715         best_block: RwLock<BestBlock>,
716         secp_ctx: Secp256k1<secp256k1::All>,
717
718         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
719         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
720         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
721         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
722         ///
723         /// See `ChannelManager` struct-level documentation for lock order requirements.
724         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
725
726         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
727         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
728         /// (if the channel has been force-closed), however we track them here to prevent duplicative
729         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
730         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
731         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
732         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
733         /// after reloading from disk while replaying blocks against ChannelMonitors.
734         ///
735         /// See `PendingOutboundPayment` documentation for more info.
736         ///
737         /// See `ChannelManager` struct-level documentation for lock order requirements.
738         pending_outbound_payments: OutboundPayments,
739
740         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
741         ///
742         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
743         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
744         /// and via the classic SCID.
745         ///
746         /// Note that no consistency guarantees are made about the existence of a channel with the
747         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
748         ///
749         /// See `ChannelManager` struct-level documentation for lock order requirements.
750         #[cfg(test)]
751         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
752         #[cfg(not(test))]
753         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
754         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
755         /// until the user tells us what we should do with them.
756         ///
757         /// See `ChannelManager` struct-level documentation for lock order requirements.
758         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
759
760         /// The sets of payments which are claimable or currently being claimed. See
761         /// [`ClaimablePayments`]' individual field docs for more info.
762         ///
763         /// See `ChannelManager` struct-level documentation for lock order requirements.
764         claimable_payments: Mutex<ClaimablePayments>,
765
766         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
767         /// and some closed channels which reached a usable state prior to being closed. This is used
768         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
769         /// active channel list on load.
770         ///
771         /// See `ChannelManager` struct-level documentation for lock order requirements.
772         outbound_scid_aliases: Mutex<HashSet<u64>>,
773
774         /// `channel_id` -> `counterparty_node_id`.
775         ///
776         /// Only `channel_id`s are allowed as keys in this map, and not `temporary_channel_id`s. As
777         /// multiple channels with the same `temporary_channel_id` to different peers can exist,
778         /// allowing `temporary_channel_id`s in this map would cause collisions for such channels.
779         ///
780         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
781         /// the corresponding channel for the event, as we only have access to the `channel_id` during
782         /// the handling of the events.
783         ///
784         /// Note that no consistency guarantees are made about the existence of a peer with the
785         /// `counterparty_node_id` in our other maps.
786         ///
787         /// TODO:
788         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
789         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
790         /// would break backwards compatability.
791         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
792         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
793         /// required to access the channel with the `counterparty_node_id`.
794         ///
795         /// See `ChannelManager` struct-level documentation for lock order requirements.
796         id_to_peer: Mutex<HashMap<[u8; 32], PublicKey>>,
797
798         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
799         ///
800         /// Outbound SCID aliases are added here once the channel is available for normal use, with
801         /// SCIDs being added once the funding transaction is confirmed at the channel's required
802         /// confirmation depth.
803         ///
804         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
805         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
806         /// channel with the `channel_id` in our other maps.
807         ///
808         /// See `ChannelManager` struct-level documentation for lock order requirements.
809         #[cfg(test)]
810         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, [u8; 32])>>,
811         #[cfg(not(test))]
812         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, [u8; 32])>>,
813
814         our_network_pubkey: PublicKey,
815
816         inbound_payment_key: inbound_payment::ExpandedKey,
817
818         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
819         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
820         /// we encrypt the namespace identifier using these bytes.
821         ///
822         /// [fake scids]: crate::util::scid_utils::fake_scid
823         fake_scid_rand_bytes: [u8; 32],
824
825         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
826         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
827         /// keeping additional state.
828         probing_cookie_secret: [u8; 32],
829
830         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
831         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
832         /// very far in the past, and can only ever be up to two hours in the future.
833         highest_seen_timestamp: AtomicUsize,
834
835         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
836         /// basis, as well as the peer's latest features.
837         ///
838         /// If we are connected to a peer we always at least have an entry here, even if no channels
839         /// are currently open with that peer.
840         ///
841         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
842         /// operate on the inner value freely. This opens up for parallel per-peer operation for
843         /// channels.
844         ///
845         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
846         ///
847         /// See `ChannelManager` struct-level documentation for lock order requirements.
848         #[cfg(not(any(test, feature = "_test_utils")))]
849         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<<SP::Target as SignerProvider>::Signer>>>>,
850         #[cfg(any(test, feature = "_test_utils"))]
851         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<<SP::Target as SignerProvider>::Signer>>>>,
852
853         /// See `ChannelManager` struct-level documentation for lock order requirements.
854         pending_events: Mutex<Vec<events::Event>>,
855         /// See `ChannelManager` struct-level documentation for lock order requirements.
856         pending_background_events: Mutex<Vec<BackgroundEvent>>,
857         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
858         /// Essentially just when we're serializing ourselves out.
859         /// Taken first everywhere where we are making changes before any other locks.
860         /// When acquiring this lock in read mode, rather than acquiring it directly, call
861         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
862         /// Notifier the lock contains sends out a notification when the lock is released.
863         total_consistency_lock: RwLock<()>,
864
865         persistence_notifier: Notifier,
866
867         entropy_source: ES,
868         node_signer: NS,
869         signer_provider: SP,
870
871         logger: L,
872 }
873
874 /// Chain-related parameters used to construct a new `ChannelManager`.
875 ///
876 /// Typically, the block-specific parameters are derived from the best block hash for the network,
877 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
878 /// are not needed when deserializing a previously constructed `ChannelManager`.
879 #[derive(Clone, Copy, PartialEq)]
880 pub struct ChainParameters {
881         /// The network for determining the `chain_hash` in Lightning messages.
882         pub network: Network,
883
884         /// The hash and height of the latest block successfully connected.
885         ///
886         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
887         pub best_block: BestBlock,
888 }
889
890 #[derive(Copy, Clone, PartialEq)]
891 enum NotifyOption {
892         DoPersist,
893         SkipPersist,
894 }
895
896 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
897 /// desirable to notify any listeners on `await_persistable_update_timeout`/
898 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
899 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
900 /// sending the aforementioned notification (since the lock being released indicates that the
901 /// updates are ready for persistence).
902 ///
903 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
904 /// notify or not based on whether relevant changes have been made, providing a closure to
905 /// `optionally_notify` which returns a `NotifyOption`.
906 struct PersistenceNotifierGuard<'a, F: Fn() -> NotifyOption> {
907         persistence_notifier: &'a Notifier,
908         should_persist: F,
909         // We hold onto this result so the lock doesn't get released immediately.
910         _read_guard: RwLockReadGuard<'a, ()>,
911 }
912
913 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
914         fn notify_on_drop(lock: &'a RwLock<()>, notifier: &'a Notifier) -> PersistenceNotifierGuard<'a, impl Fn() -> NotifyOption> {
915                 PersistenceNotifierGuard::optionally_notify(lock, notifier, || -> NotifyOption { NotifyOption::DoPersist })
916         }
917
918         fn optionally_notify<F: Fn() -> NotifyOption>(lock: &'a RwLock<()>, notifier: &'a Notifier, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
919                 let read_guard = lock.read().unwrap();
920
921                 PersistenceNotifierGuard {
922                         persistence_notifier: notifier,
923                         should_persist: persist_check,
924                         _read_guard: read_guard,
925                 }
926         }
927 }
928
929 impl<'a, F: Fn() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
930         fn drop(&mut self) {
931                 if (self.should_persist)() == NotifyOption::DoPersist {
932                         self.persistence_notifier.notify();
933                 }
934         }
935 }
936
937 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
938 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
939 ///
940 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
941 ///
942 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
943 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
944 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
945 /// the maximum required amount in lnd as of March 2021.
946 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
947
948 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
949 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
950 ///
951 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
952 ///
953 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
954 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
955 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
956 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
957 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
958 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
959 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
960 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
961 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
962 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
963 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
964 // routing failure for any HTLC sender picking up an LDK node among the first hops.
965 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
966
967 /// Minimum CLTV difference between the current block height and received inbound payments.
968 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
969 /// this value.
970 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
971 // any payments to succeed. Further, we don't want payments to fail if a block was found while
972 // a payment was being routed, so we add an extra block to be safe.
973 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
974
975 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
976 // ie that if the next-hop peer fails the HTLC within
977 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
978 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
979 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
980 // LATENCY_GRACE_PERIOD_BLOCKS.
981 #[deny(const_err)]
982 #[allow(dead_code)]
983 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;
984
985 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
986 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
987 #[deny(const_err)]
988 #[allow(dead_code)]
989 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
990
991 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
992 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
993
994 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until we time-out the
995 /// idempotency of payments by [`PaymentId`]. See
996 /// [`OutboundPayments::remove_stale_resolved_payments`].
997 pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
998
999 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1000 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1001 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1002 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1003
1004 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1005 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1006 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1007
1008 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1009 /// many peers we reject new (inbound) connections.
1010 const MAX_NO_CHANNEL_PEERS: usize = 250;
1011
1012 /// Information needed for constructing an invoice route hint for this channel.
1013 #[derive(Clone, Debug, PartialEq)]
1014 pub struct CounterpartyForwardingInfo {
1015         /// Base routing fee in millisatoshis.
1016         pub fee_base_msat: u32,
1017         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1018         pub fee_proportional_millionths: u32,
1019         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1020         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1021         /// `cltv_expiry_delta` for more details.
1022         pub cltv_expiry_delta: u16,
1023 }
1024
1025 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1026 /// to better separate parameters.
1027 #[derive(Clone, Debug, PartialEq)]
1028 pub struct ChannelCounterparty {
1029         /// The node_id of our counterparty
1030         pub node_id: PublicKey,
1031         /// The Features the channel counterparty provided upon last connection.
1032         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1033         /// many routing-relevant features are present in the init context.
1034         pub features: InitFeatures,
1035         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1036         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1037         /// claiming at least this value on chain.
1038         ///
1039         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1040         ///
1041         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1042         pub unspendable_punishment_reserve: u64,
1043         /// Information on the fees and requirements that the counterparty requires when forwarding
1044         /// payments to us through this channel.
1045         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1046         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1047         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1048         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1049         pub outbound_htlc_minimum_msat: Option<u64>,
1050         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1051         pub outbound_htlc_maximum_msat: Option<u64>,
1052 }
1053
1054 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1055 #[derive(Clone, Debug, PartialEq)]
1056 pub struct ChannelDetails {
1057         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1058         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1059         /// Note that this means this value is *not* persistent - it can change once during the
1060         /// lifetime of the channel.
1061         pub channel_id: [u8; 32],
1062         /// Parameters which apply to our counterparty. See individual fields for more information.
1063         pub counterparty: ChannelCounterparty,
1064         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1065         /// our counterparty already.
1066         ///
1067         /// Note that, if this has been set, `channel_id` will be equivalent to
1068         /// `funding_txo.unwrap().to_channel_id()`.
1069         pub funding_txo: Option<OutPoint>,
1070         /// The features which this channel operates with. See individual features for more info.
1071         ///
1072         /// `None` until negotiation completes and the channel type is finalized.
1073         pub channel_type: Option<ChannelTypeFeatures>,
1074         /// The position of the funding transaction in the chain. None if the funding transaction has
1075         /// not yet been confirmed and the channel fully opened.
1076         ///
1077         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1078         /// payments instead of this. See [`get_inbound_payment_scid`].
1079         ///
1080         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1081         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1082         ///
1083         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1084         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1085         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1086         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1087         /// [`confirmations_required`]: Self::confirmations_required
1088         pub short_channel_id: Option<u64>,
1089         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1090         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1091         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1092         /// `Some(0)`).
1093         ///
1094         /// This will be `None` as long as the channel is not available for routing outbound payments.
1095         ///
1096         /// [`short_channel_id`]: Self::short_channel_id
1097         /// [`confirmations_required`]: Self::confirmations_required
1098         pub outbound_scid_alias: Option<u64>,
1099         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1100         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1101         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1102         /// when they see a payment to be routed to us.
1103         ///
1104         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1105         /// previous values for inbound payment forwarding.
1106         ///
1107         /// [`short_channel_id`]: Self::short_channel_id
1108         pub inbound_scid_alias: Option<u64>,
1109         /// The value, in satoshis, of this channel as appears in the funding output
1110         pub channel_value_satoshis: u64,
1111         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1112         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1113         /// this value on chain.
1114         ///
1115         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1116         ///
1117         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1118         ///
1119         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1120         pub unspendable_punishment_reserve: Option<u64>,
1121         /// The `user_channel_id` passed in to create_channel, or a random value if the channel was
1122         /// inbound. This may be zero for inbound channels serialized with LDK versions prior to
1123         /// 0.0.113.
1124         pub user_channel_id: u128,
1125         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1126         /// which is applied to commitment and HTLC transactions.
1127         ///
1128         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1129         pub feerate_sat_per_1000_weight: Option<u32>,
1130         /// Our total balance.  This is the amount we would get if we close the channel.
1131         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1132         /// amount is not likely to be recoverable on close.
1133         ///
1134         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1135         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1136         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1137         /// This does not consider any on-chain fees.
1138         ///
1139         /// See also [`ChannelDetails::outbound_capacity_msat`]
1140         pub balance_msat: u64,
1141         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1142         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1143         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1144         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1145         ///
1146         /// See also [`ChannelDetails::balance_msat`]
1147         ///
1148         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1149         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1150         /// should be able to spend nearly this amount.
1151         pub outbound_capacity_msat: u64,
1152         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1153         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1154         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1155         /// to use a limit as close as possible to the HTLC limit we can currently send.
1156         ///
1157         /// See also [`ChannelDetails::balance_msat`] and [`ChannelDetails::outbound_capacity_msat`].
1158         pub next_outbound_htlc_limit_msat: u64,
1159         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1160         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1161         /// available for inclusion in new inbound HTLCs).
1162         /// Note that there are some corner cases not fully handled here, so the actual available
1163         /// inbound capacity may be slightly higher than this.
1164         ///
1165         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1166         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1167         /// However, our counterparty should be able to spend nearly this amount.
1168         pub inbound_capacity_msat: u64,
1169         /// The number of required confirmations on the funding transaction before the funding will be
1170         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1171         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1172         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1173         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1174         ///
1175         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1176         ///
1177         /// [`is_outbound`]: ChannelDetails::is_outbound
1178         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1179         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1180         pub confirmations_required: Option<u32>,
1181         /// The current number of confirmations on the funding transaction.
1182         ///
1183         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1184         pub confirmations: Option<u32>,
1185         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1186         /// until we can claim our funds after we force-close the channel. During this time our
1187         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1188         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1189         /// time to claim our non-HTLC-encumbered funds.
1190         ///
1191         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1192         pub force_close_spend_delay: Option<u16>,
1193         /// True if the channel was initiated (and thus funded) by us.
1194         pub is_outbound: bool,
1195         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1196         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1197         /// required confirmation count has been reached (and we were connected to the peer at some
1198         /// point after the funding transaction received enough confirmations). The required
1199         /// confirmation count is provided in [`confirmations_required`].
1200         ///
1201         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1202         pub is_channel_ready: bool,
1203         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1204         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1205         ///
1206         /// This is a strict superset of `is_channel_ready`.
1207         pub is_usable: bool,
1208         /// True if this channel is (or will be) publicly-announced.
1209         pub is_public: bool,
1210         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1211         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1212         pub inbound_htlc_minimum_msat: Option<u64>,
1213         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1214         pub inbound_htlc_maximum_msat: Option<u64>,
1215         /// Set of configurable parameters that affect channel operation.
1216         ///
1217         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1218         pub config: Option<ChannelConfig>,
1219 }
1220
1221 impl ChannelDetails {
1222         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1223         /// This should be used for providing invoice hints or in any other context where our
1224         /// counterparty will forward a payment to us.
1225         ///
1226         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1227         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1228         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1229                 self.inbound_scid_alias.or(self.short_channel_id)
1230         }
1231
1232         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1233         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1234         /// we're sending or forwarding a payment outbound over this channel.
1235         ///
1236         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1237         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1238         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1239                 self.short_channel_id.or(self.outbound_scid_alias)
1240         }
1241
1242         fn from_channel<Signer: WriteableEcdsaChannelSigner>(channel: &Channel<Signer>,
1243                 best_block_height: u32, latest_features: InitFeatures) -> Self {
1244
1245                 let balance = channel.get_available_balances();
1246                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1247                         channel.get_holder_counterparty_selected_channel_reserve_satoshis();
1248                 ChannelDetails {
1249                         channel_id: channel.channel_id(),
1250                         counterparty: ChannelCounterparty {
1251                                 node_id: channel.get_counterparty_node_id(),
1252                                 features: latest_features,
1253                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1254                                 forwarding_info: channel.counterparty_forwarding_info(),
1255                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1256                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1257                                 // message (as they are always the first message from the counterparty).
1258                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1259                                 // default `0` value set by `Channel::new_outbound`.
1260                                 outbound_htlc_minimum_msat: if channel.have_received_message() {
1261                                         Some(channel.get_counterparty_htlc_minimum_msat()) } else { None },
1262                                 outbound_htlc_maximum_msat: channel.get_counterparty_htlc_maximum_msat(),
1263                         },
1264                         funding_txo: channel.get_funding_txo(),
1265                         // Note that accept_channel (or open_channel) is always the first message, so
1266                         // `have_received_message` indicates that type negotiation has completed.
1267                         channel_type: if channel.have_received_message() { Some(channel.get_channel_type().clone()) } else { None },
1268                         short_channel_id: channel.get_short_channel_id(),
1269                         outbound_scid_alias: if channel.is_usable() { Some(channel.outbound_scid_alias()) } else { None },
1270                         inbound_scid_alias: channel.latest_inbound_scid_alias(),
1271                         channel_value_satoshis: channel.get_value_satoshis(),
1272                         feerate_sat_per_1000_weight: Some(channel.get_feerate_sat_per_1000_weight()),
1273                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1274                         balance_msat: balance.balance_msat,
1275                         inbound_capacity_msat: balance.inbound_capacity_msat,
1276                         outbound_capacity_msat: balance.outbound_capacity_msat,
1277                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1278                         user_channel_id: channel.get_user_id(),
1279                         confirmations_required: channel.minimum_depth(),
1280                         confirmations: Some(channel.get_funding_tx_confirmations(best_block_height)),
1281                         force_close_spend_delay: channel.get_counterparty_selected_contest_delay(),
1282                         is_outbound: channel.is_outbound(),
1283                         is_channel_ready: channel.is_usable(),
1284                         is_usable: channel.is_live(),
1285                         is_public: channel.should_announce(),
1286                         inbound_htlc_minimum_msat: Some(channel.get_holder_htlc_minimum_msat()),
1287                         inbound_htlc_maximum_msat: channel.get_holder_htlc_maximum_msat(),
1288                         config: Some(channel.config()),
1289                 }
1290         }
1291 }
1292
1293 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1294 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1295 #[derive(Debug, PartialEq)]
1296 pub enum RecentPaymentDetails {
1297         /// When a payment is still being sent and awaiting successful delivery.
1298         Pending {
1299                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1300                 /// abandoned.
1301                 payment_hash: PaymentHash,
1302                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1303                 /// not just the amount currently inflight.
1304                 total_msat: u64,
1305         },
1306         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1307         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1308         /// payment is removed from tracking.
1309         Fulfilled {
1310                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1311                 /// made before LDK version 0.0.104.
1312                 payment_hash: Option<PaymentHash>,
1313         },
1314         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1315         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1316         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1317         Abandoned {
1318                 /// Hash of the payment that we have given up trying to send.
1319                 payment_hash: PaymentHash,
1320         },
1321 }
1322
1323 /// Route hints used in constructing invoices for [phantom node payents].
1324 ///
1325 /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
1326 #[derive(Clone)]
1327 pub struct PhantomRouteHints {
1328         /// The list of channels to be included in the invoice route hints.
1329         pub channels: Vec<ChannelDetails>,
1330         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1331         /// route hints.
1332         pub phantom_scid: u64,
1333         /// The pubkey of the real backing node that would ultimately receive the payment.
1334         pub real_node_pubkey: PublicKey,
1335 }
1336
1337 macro_rules! handle_error {
1338         ($self: ident, $internal: expr, $counterparty_node_id: expr) => {
1339                 match $internal {
1340                         Ok(msg) => Ok(msg),
1341                         Err(MsgHandleErrInternal { err, chan_id, shutdown_finish }) => {
1342                                 // In testing, ensure there are no deadlocks where the lock is already held upon
1343                                 // entering the macro.
1344                                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1345                                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1346
1347                                 let mut msg_events = Vec::with_capacity(2);
1348
1349                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1350                                         $self.finish_force_close_channel(shutdown_res);
1351                                         if let Some(update) = update_option {
1352                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1353                                                         msg: update
1354                                                 });
1355                                         }
1356                                         if let Some((channel_id, user_channel_id)) = chan_id {
1357                                                 $self.pending_events.lock().unwrap().push(events::Event::ChannelClosed {
1358                                                         channel_id, user_channel_id,
1359                                                         reason: ClosureReason::ProcessingError { err: err.err.clone() }
1360                                                 });
1361                                         }
1362                                 }
1363
1364                                 log_error!($self.logger, "{}", err.err);
1365                                 if let msgs::ErrorAction::IgnoreError = err.action {
1366                                 } else {
1367                                         msg_events.push(events::MessageSendEvent::HandleError {
1368                                                 node_id: $counterparty_node_id,
1369                                                 action: err.action.clone()
1370                                         });
1371                                 }
1372
1373                                 if !msg_events.is_empty() {
1374                                         let per_peer_state = $self.per_peer_state.read().unwrap();
1375                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
1376                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
1377                                                 peer_state.pending_msg_events.append(&mut msg_events);
1378                                         }
1379                                 }
1380
1381                                 // Return error in case higher-API need one
1382                                 Err(err)
1383                         },
1384                 }
1385         }
1386 }
1387
1388 macro_rules! update_maps_on_chan_removal {
1389         ($self: expr, $channel: expr) => {{
1390                 $self.id_to_peer.lock().unwrap().remove(&$channel.channel_id());
1391                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1392                 if let Some(short_id) = $channel.get_short_channel_id() {
1393                         short_to_chan_info.remove(&short_id);
1394                 } else {
1395                         // If the channel was never confirmed on-chain prior to its closure, remove the
1396                         // outbound SCID alias we used for it from the collision-prevention set. While we
1397                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
1398                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
1399                         // opening a million channels with us which are closed before we ever reach the funding
1400                         // stage.
1401                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel.outbound_scid_alias());
1402                         debug_assert!(alias_removed);
1403                 }
1404                 short_to_chan_info.remove(&$channel.outbound_scid_alias());
1405         }}
1406 }
1407
1408 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
1409 macro_rules! convert_chan_err {
1410         ($self: ident, $err: expr, $channel: expr, $channel_id: expr) => {
1411                 match $err {
1412                         ChannelError::Warn(msg) => {
1413                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), $channel_id.clone()))
1414                         },
1415                         ChannelError::Ignore(msg) => {
1416                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $channel_id.clone()))
1417                         },
1418                         ChannelError::Close(msg) => {
1419                                 log_error!($self.logger, "Closing channel {} due to close-required error: {}", log_bytes!($channel_id[..]), msg);
1420                                 update_maps_on_chan_removal!($self, $channel);
1421                                 let shutdown_res = $channel.force_shutdown(true);
1422                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, $channel.get_user_id(),
1423                                         shutdown_res, $self.get_channel_update_for_broadcast(&$channel).ok()))
1424                         },
1425                 }
1426         }
1427 }
1428
1429 macro_rules! break_chan_entry {
1430         ($self: ident, $res: expr, $entry: expr) => {
1431                 match $res {
1432                         Ok(res) => res,
1433                         Err(e) => {
1434                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut(), $entry.key());
1435                                 if drop {
1436                                         $entry.remove_entry();
1437                                 }
1438                                 break Err(res);
1439                         }
1440                 }
1441         }
1442 }
1443
1444 macro_rules! try_chan_entry {
1445         ($self: ident, $res: expr, $entry: expr) => {
1446                 match $res {
1447                         Ok(res) => res,
1448                         Err(e) => {
1449                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut(), $entry.key());
1450                                 if drop {
1451                                         $entry.remove_entry();
1452                                 }
1453                                 return Err(res);
1454                         }
1455                 }
1456         }
1457 }
1458
1459 macro_rules! remove_channel {
1460         ($self: expr, $entry: expr) => {
1461                 {
1462                         let channel = $entry.remove_entry().1;
1463                         update_maps_on_chan_removal!($self, channel);
1464                         channel
1465                 }
1466         }
1467 }
1468
1469 macro_rules! send_channel_ready {
1470         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
1471                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
1472                         node_id: $channel.get_counterparty_node_id(),
1473                         msg: $channel_ready_msg,
1474                 });
1475                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
1476                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
1477                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1478                 let outbound_alias_insert = short_to_chan_info.insert($channel.outbound_scid_alias(), ($channel.get_counterparty_node_id(), $channel.channel_id()));
1479                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.get_counterparty_node_id(), $channel.channel_id()),
1480                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
1481                 if let Some(real_scid) = $channel.get_short_channel_id() {
1482                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.get_counterparty_node_id(), $channel.channel_id()));
1483                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.get_counterparty_node_id(), $channel.channel_id()),
1484                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
1485                 }
1486         }}
1487 }
1488
1489 macro_rules! emit_channel_ready_event {
1490         ($self: expr, $channel: expr) => {
1491                 if $channel.should_emit_channel_ready_event() {
1492                         {
1493                                 let mut pending_events = $self.pending_events.lock().unwrap();
1494                                 pending_events.push(events::Event::ChannelReady {
1495                                         channel_id: $channel.channel_id(),
1496                                         user_channel_id: $channel.get_user_id(),
1497                                         counterparty_node_id: $channel.get_counterparty_node_id(),
1498                                         channel_type: $channel.get_channel_type().clone(),
1499                                 });
1500                         }
1501                         $channel.set_channel_ready_event_emitted();
1502                 }
1503         }
1504 }
1505
1506 macro_rules! handle_monitor_update_completion {
1507         ($self: ident, $update_id: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
1508                 let mut updates = $chan.monitor_updating_restored(&$self.logger,
1509                         &$self.node_signer, $self.genesis_hash, &$self.default_configuration,
1510                         $self.best_block.read().unwrap().height());
1511                 let counterparty_node_id = $chan.get_counterparty_node_id();
1512                 let channel_update = if updates.channel_ready.is_some() && $chan.is_usable() {
1513                         // We only send a channel_update in the case where we are just now sending a
1514                         // channel_ready and the channel is in a usable state. We may re-send a
1515                         // channel_update later through the announcement_signatures process for public
1516                         // channels, but there's no reason not to just inform our counterparty of our fees
1517                         // now.
1518                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
1519                                 Some(events::MessageSendEvent::SendChannelUpdate {
1520                                         node_id: counterparty_node_id,
1521                                         msg,
1522                                 })
1523                         } else { None }
1524                 } else { None };
1525
1526                 let update_actions = $peer_state.monitor_update_blocked_actions
1527                         .remove(&$chan.channel_id()).unwrap_or(Vec::new());
1528
1529                 let htlc_forwards = $self.handle_channel_resumption(
1530                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
1531                         updates.commitment_update, updates.order, updates.accepted_htlcs,
1532                         updates.funding_broadcastable, updates.channel_ready,
1533                         updates.announcement_sigs);
1534                 if let Some(upd) = channel_update {
1535                         $peer_state.pending_msg_events.push(upd);
1536                 }
1537
1538                 let channel_id = $chan.channel_id();
1539                 core::mem::drop($peer_state_lock);
1540                 core::mem::drop($per_peer_state_lock);
1541
1542                 $self.handle_monitor_update_completion_actions(update_actions);
1543
1544                 if let Some(forwards) = htlc_forwards {
1545                         $self.forward_htlcs(&mut [forwards][..]);
1546                 }
1547                 $self.finalize_claims(updates.finalized_claimed_htlcs);
1548                 for failure in updates.failed_htlcs.drain(..) {
1549                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
1550                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
1551                 }
1552         } }
1553 }
1554
1555 macro_rules! handle_new_monitor_update {
1556         ($self: ident, $update_res: expr, $update_id: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, MANUALLY_REMOVING, $remove: expr) => { {
1557                 // update_maps_on_chan_removal needs to be able to take id_to_peer, so make sure we can in
1558                 // any case so that it won't deadlock.
1559                 debug_assert!($self.id_to_peer.try_lock().is_ok());
1560                 match $update_res {
1561                         ChannelMonitorUpdateStatus::InProgress => {
1562                                 log_debug!($self.logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
1563                                         log_bytes!($chan.channel_id()[..]));
1564                                 Ok(())
1565                         },
1566                         ChannelMonitorUpdateStatus::PermanentFailure => {
1567                                 log_error!($self.logger, "Closing channel {} due to monitor update ChannelMonitorUpdateStatus::PermanentFailure",
1568                                         log_bytes!($chan.channel_id()[..]));
1569                                 update_maps_on_chan_removal!($self, $chan);
1570                                 let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown(
1571                                         "ChannelMonitor storage failure".to_owned(), $chan.channel_id(),
1572                                         $chan.get_user_id(), $chan.force_shutdown(false),
1573                                         $self.get_channel_update_for_broadcast(&$chan).ok()));
1574                                 $remove;
1575                                 res
1576                         },
1577                         ChannelMonitorUpdateStatus::Completed => {
1578                                 if ($update_id == 0 || $chan.get_next_monitor_update()
1579                                         .expect("We can't be processing a monitor update if it isn't queued")
1580                                         .update_id == $update_id) &&
1581                                         $chan.get_latest_monitor_update_id() == $update_id
1582                                 {
1583                                         handle_monitor_update_completion!($self, $update_id, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
1584                                 }
1585                                 Ok(())
1586                         },
1587                 }
1588         } };
1589         ($self: ident, $update_res: expr, $update_id: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan_entry: expr) => {
1590                 handle_new_monitor_update!($self, $update_res, $update_id, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan_entry.get_mut(), MANUALLY_REMOVING, $chan_entry.remove_entry())
1591         }
1592 }
1593
1594 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> ChannelManager<M, T, ES, NS, SP, F, R, L>
1595 where
1596         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
1597         T::Target: BroadcasterInterface,
1598         ES::Target: EntropySource,
1599         NS::Target: NodeSigner,
1600         SP::Target: SignerProvider,
1601         F::Target: FeeEstimator,
1602         R::Target: Router,
1603         L::Target: Logger,
1604 {
1605         /// Constructs a new `ChannelManager` to hold several channels and route between them.
1606         ///
1607         /// This is the main "logic hub" for all channel-related actions, and implements
1608         /// [`ChannelMessageHandler`].
1609         ///
1610         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
1611         ///
1612         /// Users need to notify the new `ChannelManager` when a new block is connected or
1613         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
1614         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
1615         /// more details.
1616         ///
1617         /// [`block_connected`]: chain::Listen::block_connected
1618         /// [`block_disconnected`]: chain::Listen::block_disconnected
1619         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
1620         pub fn new(fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES, node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters) -> Self {
1621                 let mut secp_ctx = Secp256k1::new();
1622                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
1623                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
1624                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
1625                 ChannelManager {
1626                         default_configuration: config.clone(),
1627                         genesis_hash: genesis_block(params.network).header.block_hash(),
1628                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
1629                         chain_monitor,
1630                         tx_broadcaster,
1631                         router,
1632
1633                         best_block: RwLock::new(params.best_block),
1634
1635                         outbound_scid_aliases: Mutex::new(HashSet::new()),
1636                         pending_inbound_payments: Mutex::new(HashMap::new()),
1637                         pending_outbound_payments: OutboundPayments::new(),
1638                         forward_htlcs: Mutex::new(HashMap::new()),
1639                         claimable_payments: Mutex::new(ClaimablePayments { claimable_htlcs: HashMap::new(), pending_claiming_payments: HashMap::new() }),
1640                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
1641                         id_to_peer: Mutex::new(HashMap::new()),
1642                         short_to_chan_info: FairRwLock::new(HashMap::new()),
1643
1644                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
1645                         secp_ctx,
1646
1647                         inbound_payment_key: expanded_inbound_key,
1648                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
1649
1650                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
1651
1652                         highest_seen_timestamp: AtomicUsize::new(0),
1653
1654                         per_peer_state: FairRwLock::new(HashMap::new()),
1655
1656                         pending_events: Mutex::new(Vec::new()),
1657                         pending_background_events: Mutex::new(Vec::new()),
1658                         total_consistency_lock: RwLock::new(()),
1659                         persistence_notifier: Notifier::new(),
1660
1661                         entropy_source,
1662                         node_signer,
1663                         signer_provider,
1664
1665                         logger,
1666                 }
1667         }
1668
1669         /// Gets the current configuration applied to all new channels.
1670         pub fn get_current_default_configuration(&self) -> &UserConfig {
1671                 &self.default_configuration
1672         }
1673
1674         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
1675                 let height = self.best_block.read().unwrap().height();
1676                 let mut outbound_scid_alias = 0;
1677                 let mut i = 0;
1678                 loop {
1679                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
1680                                 outbound_scid_alias += 1;
1681                         } else {
1682                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
1683                         }
1684                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
1685                                 break;
1686                         }
1687                         i += 1;
1688                         if i > 1_000_000 { panic!("Your RNG is busted or we ran out of possible outbound SCID aliases (which should never happen before we run out of memory to store channels"); }
1689                 }
1690                 outbound_scid_alias
1691         }
1692
1693         /// Creates a new outbound channel to the given remote node and with the given value.
1694         ///
1695         /// `user_channel_id` will be provided back as in
1696         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
1697         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
1698         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
1699         /// is simply copied to events and otherwise ignored.
1700         ///
1701         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
1702         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
1703         ///
1704         /// Note that we do not check if you are currently connected to the given peer. If no
1705         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
1706         /// the channel eventually being silently forgotten (dropped on reload).
1707         ///
1708         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
1709         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
1710         /// [`ChannelDetails::channel_id`] until after
1711         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
1712         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
1713         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
1714         ///
1715         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
1716         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
1717         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
1718         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_channel_id: u128, override_config: Option<UserConfig>) -> Result<[u8; 32], APIError> {
1719                 if channel_value_satoshis < 1000 {
1720                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
1721                 }
1722
1723                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
1724                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
1725                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
1726
1727                 let per_peer_state = self.per_peer_state.read().unwrap();
1728
1729                 let peer_state_mutex = per_peer_state.get(&their_network_key)
1730                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
1731
1732                 let mut peer_state = peer_state_mutex.lock().unwrap();
1733                 let channel = {
1734                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
1735                         let their_features = &peer_state.latest_features;
1736                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
1737                         match Channel::new_outbound(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
1738                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
1739                                 self.best_block.read().unwrap().height(), outbound_scid_alias)
1740                         {
1741                                 Ok(res) => res,
1742                                 Err(e) => {
1743                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
1744                                         return Err(e);
1745                                 },
1746                         }
1747                 };
1748                 let res = channel.get_open_channel(self.genesis_hash.clone());
1749
1750                 let temporary_channel_id = channel.channel_id();
1751                 match peer_state.channel_by_id.entry(temporary_channel_id) {
1752                         hash_map::Entry::Occupied(_) => {
1753                                 if cfg!(fuzzing) {
1754                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
1755                                 } else {
1756                                         panic!("RNG is bad???");
1757                                 }
1758                         },
1759                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
1760                 }
1761
1762                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
1763                         node_id: their_network_key,
1764                         msg: res,
1765                 });
1766                 Ok(temporary_channel_id)
1767         }
1768
1769         fn list_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<<SP::Target as SignerProvider>::Signer>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
1770                 // Allocate our best estimate of the number of channels we have in the `res`
1771                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
1772                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
1773                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
1774                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
1775                 // the same channel.
1776                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
1777                 {
1778                         let best_block_height = self.best_block.read().unwrap().height();
1779                         let per_peer_state = self.per_peer_state.read().unwrap();
1780                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
1781                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
1782                                 let peer_state = &mut *peer_state_lock;
1783                                 for (_channel_id, channel) in peer_state.channel_by_id.iter().filter(f) {
1784                                         let details = ChannelDetails::from_channel(channel, best_block_height,
1785                                                 peer_state.latest_features.clone());
1786                                         res.push(details);
1787                                 }
1788                         }
1789                 }
1790                 res
1791         }
1792
1793         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
1794         /// more information.
1795         pub fn list_channels(&self) -> Vec<ChannelDetails> {
1796                 self.list_channels_with_filter(|_| true)
1797         }
1798
1799         /// Gets the list of usable channels, in random order. Useful as an argument to
1800         /// [`Router::find_route`] to ensure non-announced channels are used.
1801         ///
1802         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
1803         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
1804         /// are.
1805         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
1806                 // Note we use is_live here instead of usable which leads to somewhat confused
1807                 // internal/external nomenclature, but that's ok cause that's probably what the user
1808                 // really wanted anyway.
1809                 self.list_channels_with_filter(|&(_, ref channel)| channel.is_live())
1810         }
1811
1812         /// Gets the list of channels we have with a given counterparty, in random order.
1813         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
1814                 let best_block_height = self.best_block.read().unwrap().height();
1815                 let per_peer_state = self.per_peer_state.read().unwrap();
1816
1817                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
1818                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
1819                         let peer_state = &mut *peer_state_lock;
1820                         let features = &peer_state.latest_features;
1821                         return peer_state.channel_by_id
1822                                 .iter()
1823                                 .map(|(_, channel)|
1824                                         ChannelDetails::from_channel(channel, best_block_height, features.clone()))
1825                                 .collect();
1826                 }
1827                 vec![]
1828         }
1829
1830         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
1831         /// successful path, or have unresolved HTLCs.
1832         ///
1833         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
1834         /// result of a crash. If such a payment exists, is not listed here, and an
1835         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
1836         ///
1837         /// [`Event::PaymentSent`]: events::Event::PaymentSent
1838         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
1839                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
1840                         .filter_map(|(_, pending_outbound_payment)| match pending_outbound_payment {
1841                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
1842                                         Some(RecentPaymentDetails::Pending {
1843                                                 payment_hash: *payment_hash,
1844                                                 total_msat: *total_msat,
1845                                         })
1846                                 },
1847                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
1848                                         Some(RecentPaymentDetails::Abandoned { payment_hash: *payment_hash })
1849                                 },
1850                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
1851                                         Some(RecentPaymentDetails::Fulfilled { payment_hash: *payment_hash })
1852                                 },
1853                                 PendingOutboundPayment::Legacy { .. } => None
1854                         })
1855                         .collect()
1856         }
1857
1858         /// Helper function that issues the channel close events
1859         fn issue_channel_close_events(&self, channel: &Channel<<SP::Target as SignerProvider>::Signer>, closure_reason: ClosureReason) {
1860                 let mut pending_events_lock = self.pending_events.lock().unwrap();
1861                 match channel.unbroadcasted_funding() {
1862                         Some(transaction) => {
1863                                 pending_events_lock.push(events::Event::DiscardFunding { channel_id: channel.channel_id(), transaction })
1864                         },
1865                         None => {},
1866                 }
1867                 pending_events_lock.push(events::Event::ChannelClosed {
1868                         channel_id: channel.channel_id(),
1869                         user_channel_id: channel.get_user_id(),
1870                         reason: closure_reason
1871                 });
1872         }
1873
1874         fn close_channel_internal(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: Option<u32>) -> Result<(), APIError> {
1875                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
1876
1877                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)>;
1878                 let result: Result<(), _> = loop {
1879                         let per_peer_state = self.per_peer_state.read().unwrap();
1880
1881                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
1882                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
1883
1884                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
1885                         let peer_state = &mut *peer_state_lock;
1886                         match peer_state.channel_by_id.entry(channel_id.clone()) {
1887                                 hash_map::Entry::Occupied(mut chan_entry) => {
1888                                         let funding_txo_opt = chan_entry.get().get_funding_txo();
1889                                         let their_features = &peer_state.latest_features;
1890                                         let (shutdown_msg, mut monitor_update_opt, htlcs) = chan_entry.get_mut()
1891                                                 .get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight)?;
1892                                         failed_htlcs = htlcs;
1893
1894                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
1895                                         // here as we don't need the monitor update to complete until we send a
1896                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
1897                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1898                                                 node_id: *counterparty_node_id,
1899                                                 msg: shutdown_msg,
1900                                         });
1901
1902                                         // Update the monitor with the shutdown script if necessary.
1903                                         if let Some(monitor_update) = monitor_update_opt.take() {
1904                                                 let update_id = monitor_update.update_id;
1905                                                 let update_res = self.chain_monitor.update_channel(funding_txo_opt.unwrap(), monitor_update);
1906                                                 break handle_new_monitor_update!(self, update_res, update_id, peer_state_lock, peer_state, per_peer_state, chan_entry);
1907                                         }
1908
1909                                         if chan_entry.get().is_shutdown() {
1910                                                 let channel = remove_channel!(self, chan_entry);
1911                                                 if let Ok(channel_update) = self.get_channel_update_for_broadcast(&channel) {
1912                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1913                                                                 msg: channel_update
1914                                                         });
1915                                                 }
1916                                                 self.issue_channel_close_events(&channel, ClosureReason::HolderForceClosed);
1917                                         }
1918                                         break Ok(());
1919                                 },
1920                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(*channel_id), counterparty_node_id) })
1921                         }
1922                 };
1923
1924                 for htlc_source in failed_htlcs.drain(..) {
1925                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
1926                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
1927                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
1928                 }
1929
1930                 let _ = handle_error!(self, result, *counterparty_node_id);
1931                 Ok(())
1932         }
1933
1934         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
1935         /// will be accepted on the given channel, and after additional timeout/the closing of all
1936         /// pending HTLCs, the channel will be closed on chain.
1937         ///
1938         ///  * If we are the channel initiator, we will pay between our [`Background`] and
1939         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
1940         ///    estimate.
1941         ///  * If our counterparty is the channel initiator, we will require a channel closing
1942         ///    transaction feerate of at least our [`Background`] feerate or the feerate which
1943         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
1944         ///    counterparty to pay as much fee as they'd like, however.
1945         ///
1946         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
1947         ///
1948         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
1949         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
1950         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
1951         /// [`SendShutdown`]: crate::util::events::MessageSendEvent::SendShutdown
1952         pub fn close_channel(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey) -> Result<(), APIError> {
1953                 self.close_channel_internal(channel_id, counterparty_node_id, None)
1954         }
1955
1956         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
1957         /// will be accepted on the given channel, and after additional timeout/the closing of all
1958         /// pending HTLCs, the channel will be closed on chain.
1959         ///
1960         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
1961         /// the channel being closed or not:
1962         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
1963         ///    transaction. The upper-bound is set by
1964         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
1965         ///    estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
1966         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
1967         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
1968         ///    will appear on a force-closure transaction, whichever is lower).
1969         ///
1970         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
1971         ///
1972         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
1973         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
1974         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
1975         /// [`SendShutdown`]: crate::util::events::MessageSendEvent::SendShutdown
1976         pub fn close_channel_with_target_feerate(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: u32) -> Result<(), APIError> {
1977                 self.close_channel_internal(channel_id, counterparty_node_id, Some(target_feerate_sats_per_1000_weight))
1978         }
1979
1980         #[inline]
1981         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
1982                 let (monitor_update_option, mut failed_htlcs) = shutdown_res;
1983                 log_debug!(self.logger, "Finishing force-closure of channel with {} HTLCs to fail", failed_htlcs.len());
1984                 for htlc_source in failed_htlcs.drain(..) {
1985                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
1986                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
1987                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
1988                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
1989                 }
1990                 if let Some((funding_txo, monitor_update)) = monitor_update_option {
1991                         // There isn't anything we can do if we get an update failure - we're already
1992                         // force-closing. The monitor update on the required in-memory copy should broadcast
1993                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
1994                         // ignore the result here.
1995                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
1996                 }
1997         }
1998
1999         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2000         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2001         fn force_close_channel_with_peer(&self, channel_id: &[u8; 32], peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2002         -> Result<PublicKey, APIError> {
2003                 let per_peer_state = self.per_peer_state.read().unwrap();
2004                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2005                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2006                 let mut chan = {
2007                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2008                         let peer_state = &mut *peer_state_lock;
2009                         if let hash_map::Entry::Occupied(chan) = peer_state.channel_by_id.entry(channel_id.clone()) {
2010                                 if let Some(peer_msg) = peer_msg {
2011                                         self.issue_channel_close_events(chan.get(),ClosureReason::CounterpartyForceClosed { peer_msg: peer_msg.to_string() });
2012                                 } else {
2013                                         self.issue_channel_close_events(chan.get(),ClosureReason::HolderForceClosed);
2014                                 }
2015                                 remove_channel!(self, chan)
2016                         } else {
2017                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(*channel_id), peer_node_id) });
2018                         }
2019                 };
2020                 log_error!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
2021                 self.finish_force_close_channel(chan.force_shutdown(broadcast));
2022                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
2023                         let mut peer_state = peer_state_mutex.lock().unwrap();
2024                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2025                                 msg: update
2026                         });
2027                 }
2028
2029                 Ok(chan.get_counterparty_node_id())
2030         }
2031
2032         fn force_close_sending_error(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
2033                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2034                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
2035                         Ok(counterparty_node_id) => {
2036                                 let per_peer_state = self.per_peer_state.read().unwrap();
2037                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2038                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2039                                         peer_state.pending_msg_events.push(
2040                                                 events::MessageSendEvent::HandleError {
2041                                                         node_id: counterparty_node_id,
2042                                                         action: msgs::ErrorAction::SendErrorMessage {
2043                                                                 msg: msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() }
2044                                                         },
2045                                                 }
2046                                         );
2047                                 }
2048                                 Ok(())
2049                         },
2050                         Err(e) => Err(e)
2051                 }
2052         }
2053
2054         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2055         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2056         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
2057         /// channel.
2058         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey)
2059         -> Result<(), APIError> {
2060                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
2061         }
2062
2063         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
2064         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
2065         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
2066         ///
2067         /// You can always get the latest local transaction(s) to broadcast from
2068         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
2069         pub fn force_close_without_broadcasting_txn(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey)
2070         -> Result<(), APIError> {
2071                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
2072         }
2073
2074         /// Force close all channels, immediately broadcasting the latest local commitment transaction
2075         /// for each to the chain and rejecting new HTLCs on each.
2076         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
2077                 for chan in self.list_channels() {
2078                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
2079                 }
2080         }
2081
2082         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
2083         /// local transaction(s).
2084         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
2085                 for chan in self.list_channels() {
2086                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
2087                 }
2088         }
2089
2090         fn construct_recv_pending_htlc_info(&self, hop_data: msgs::OnionHopData, shared_secret: [u8; 32],
2091                 payment_hash: PaymentHash, amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>) -> Result<PendingHTLCInfo, ReceiveError>
2092         {
2093                 // final_incorrect_cltv_expiry
2094                 if hop_data.outgoing_cltv_value != cltv_expiry {
2095                         return Err(ReceiveError {
2096                                 msg: "Upstream node set CLTV to the wrong value",
2097                                 err_code: 18,
2098                                 err_data: cltv_expiry.to_be_bytes().to_vec()
2099                         })
2100                 }
2101                 // final_expiry_too_soon
2102                 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure
2103                 // we have at least HTLC_FAIL_BACK_BUFFER blocks to go.
2104                 //
2105                 // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
2106                 // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
2107                 // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
2108                 let current_height: u32 = self.best_block.read().unwrap().height();
2109                 if (hop_data.outgoing_cltv_value as u64) <= current_height as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1 {
2110                         let mut err_data = Vec::with_capacity(12);
2111                         err_data.extend_from_slice(&amt_msat.to_be_bytes());
2112                         err_data.extend_from_slice(&current_height.to_be_bytes());
2113                         return Err(ReceiveError {
2114                                 err_code: 0x4000 | 15, err_data,
2115                                 msg: "The final CLTV expiry is too soon to handle",
2116                         });
2117                 }
2118                 if hop_data.amt_to_forward > amt_msat {
2119                         return Err(ReceiveError {
2120                                 err_code: 19,
2121                                 err_data: amt_msat.to_be_bytes().to_vec(),
2122                                 msg: "Upstream node sent less than we were supposed to receive in payment",
2123                         });
2124                 }
2125
2126                 let routing = match hop_data.format {
2127                         msgs::OnionHopDataFormat::NonFinalNode { .. } => {
2128                                 return Err(ReceiveError {
2129                                         err_code: 0x4000|22,
2130                                         err_data: Vec::new(),
2131                                         msg: "Got non final data with an HMAC of 0",
2132                                 });
2133                         },
2134                         msgs::OnionHopDataFormat::FinalNode { payment_data, keysend_preimage } => {
2135                                 if payment_data.is_some() && keysend_preimage.is_some() {
2136                                         return Err(ReceiveError {
2137                                                 err_code: 0x4000|22,
2138                                                 err_data: Vec::new(),
2139                                                 msg: "We don't support MPP keysend payments",
2140                                         });
2141                                 } else if let Some(data) = payment_data {
2142                                         PendingHTLCRouting::Receive {
2143                                                 payment_data: data,
2144                                                 incoming_cltv_expiry: hop_data.outgoing_cltv_value,
2145                                                 phantom_shared_secret,
2146                                         }
2147                                 } else if let Some(payment_preimage) = keysend_preimage {
2148                                         // We need to check that the sender knows the keysend preimage before processing this
2149                                         // payment further. Otherwise, an intermediary routing hop forwarding non-keysend-HTLC X
2150                                         // could discover the final destination of X, by probing the adjacent nodes on the route
2151                                         // with a keysend payment of identical payment hash to X and observing the processing
2152                                         // time discrepancies due to a hash collision with X.
2153                                         let hashed_preimage = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
2154                                         if hashed_preimage != payment_hash {
2155                                                 return Err(ReceiveError {
2156                                                         err_code: 0x4000|22,
2157                                                         err_data: Vec::new(),
2158                                                         msg: "Payment preimage didn't match payment hash",
2159                                                 });
2160                                         }
2161
2162                                         PendingHTLCRouting::ReceiveKeysend {
2163                                                 payment_preimage,
2164                                                 incoming_cltv_expiry: hop_data.outgoing_cltv_value,
2165                                         }
2166                                 } else {
2167                                         return Err(ReceiveError {
2168                                                 err_code: 0x4000|0x2000|3,
2169                                                 err_data: Vec::new(),
2170                                                 msg: "We require payment_secrets",
2171                                         });
2172                                 }
2173                         },
2174                 };
2175                 Ok(PendingHTLCInfo {
2176                         routing,
2177                         payment_hash,
2178                         incoming_shared_secret: shared_secret,
2179                         incoming_amt_msat: Some(amt_msat),
2180                         outgoing_amt_msat: amt_msat,
2181                         outgoing_cltv_value: hop_data.outgoing_cltv_value,
2182                 })
2183         }
2184
2185         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> PendingHTLCStatus {
2186                 macro_rules! return_malformed_err {
2187                         ($msg: expr, $err_code: expr) => {
2188                                 {
2189                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2190                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
2191                                                 channel_id: msg.channel_id,
2192                                                 htlc_id: msg.htlc_id,
2193                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
2194                                                 failure_code: $err_code,
2195                                         }));
2196                                 }
2197                         }
2198                 }
2199
2200                 if let Err(_) = msg.onion_routing_packet.public_key {
2201                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
2202                 }
2203
2204                 let shared_secret = self.node_signer.ecdh(
2205                         Recipient::Node, &msg.onion_routing_packet.public_key.unwrap(), None
2206                 ).unwrap().secret_bytes();
2207
2208                 if msg.onion_routing_packet.version != 0 {
2209                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
2210                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
2211                         //the hash doesn't really serve any purpose - in the case of hashing all data, the
2212                         //receiving node would have to brute force to figure out which version was put in the
2213                         //packet by the node that send us the message, in the case of hashing the hop_data, the
2214                         //node knows the HMAC matched, so they already know what is there...
2215                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
2216                 }
2217                 macro_rules! return_err {
2218                         ($msg: expr, $err_code: expr, $data: expr) => {
2219                                 {
2220                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2221                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2222                                                 channel_id: msg.channel_id,
2223                                                 htlc_id: msg.htlc_id,
2224                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
2225                                                         .get_encrypted_failure_packet(&shared_secret, &None),
2226                                         }));
2227                                 }
2228                         }
2229                 }
2230
2231                 let next_hop = match onion_utils::decode_next_payment_hop(shared_secret, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac, msg.payment_hash) {
2232                         Ok(res) => res,
2233                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
2234                                 return_malformed_err!(err_msg, err_code);
2235                         },
2236                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
2237                                 return_err!(err_msg, err_code, &[0; 0]);
2238                         },
2239                 };
2240
2241                 let pending_forward_info = match next_hop {
2242                         onion_utils::Hop::Receive(next_hop_data) => {
2243                                 // OUR PAYMENT!
2244                                 match self.construct_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash, msg.amount_msat, msg.cltv_expiry, None) {
2245                                         Ok(info) => {
2246                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
2247                                                 // message, however that would leak that we are the recipient of this payment, so
2248                                                 // instead we stay symmetric with the forwarding case, only responding (after a
2249                                                 // delay) once they've send us a commitment_signed!
2250                                                 PendingHTLCStatus::Forward(info)
2251                                         },
2252                                         Err(ReceiveError { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
2253                                 }
2254                         },
2255                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
2256                                 let new_pubkey = msg.onion_routing_packet.public_key.unwrap();
2257                                 let outgoing_packet = msgs::OnionPacket {
2258                                         version: 0,
2259                                         public_key: onion_utils::next_hop_packet_pubkey(&self.secp_ctx, new_pubkey, &shared_secret),
2260                                         hop_data: new_packet_bytes,
2261                                         hmac: next_hop_hmac.clone(),
2262                                 };
2263
2264                                 let short_channel_id = match next_hop_data.format {
2265                                         msgs::OnionHopDataFormat::NonFinalNode { short_channel_id } => short_channel_id,
2266                                         msgs::OnionHopDataFormat::FinalNode { .. } => {
2267                                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0;0]);
2268                                         },
2269                                 };
2270
2271                                 PendingHTLCStatus::Forward(PendingHTLCInfo {
2272                                         routing: PendingHTLCRouting::Forward {
2273                                                 onion_packet: outgoing_packet,
2274                                                 short_channel_id,
2275                                         },
2276                                         payment_hash: msg.payment_hash.clone(),
2277                                         incoming_shared_secret: shared_secret,
2278                                         incoming_amt_msat: Some(msg.amount_msat),
2279                                         outgoing_amt_msat: next_hop_data.amt_to_forward,
2280                                         outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
2281                                 })
2282                         }
2283                 };
2284
2285                 if let &PendingHTLCStatus::Forward(PendingHTLCInfo { ref routing, ref outgoing_amt_msat, ref outgoing_cltv_value, .. }) = &pending_forward_info {
2286                         // If short_channel_id is 0 here, we'll reject the HTLC as there cannot be a channel
2287                         // with a short_channel_id of 0. This is important as various things later assume
2288                         // short_channel_id is non-0 in any ::Forward.
2289                         if let &PendingHTLCRouting::Forward { ref short_channel_id, .. } = routing {
2290                                 if let Some((err, mut code, chan_update)) = loop {
2291                                         let id_option = self.short_to_chan_info.read().unwrap().get(short_channel_id).cloned();
2292                                         let forwarding_chan_info_opt = match id_option {
2293                                                 None => { // unknown_next_peer
2294                                                         // Note that this is likely a timing oracle for detecting whether an scid is a
2295                                                         // phantom or an intercept.
2296                                                         if (self.default_configuration.accept_intercept_htlcs &&
2297                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, *short_channel_id, &self.genesis_hash)) ||
2298                                                            fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, *short_channel_id, &self.genesis_hash)
2299                                                         {
2300                                                                 None
2301                                                         } else {
2302                                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2303                                                         }
2304                                                 },
2305                                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
2306                                         };
2307                                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
2308                                                 let per_peer_state = self.per_peer_state.read().unwrap();
2309                                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
2310                                                 if peer_state_mutex_opt.is_none() {
2311                                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2312                                                 }
2313                                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
2314                                                 let peer_state = &mut *peer_state_lock;
2315                                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id) {
2316                                                         None => {
2317                                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
2318                                                                 // have no consistency guarantees.
2319                                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2320                                                         },
2321                                                         Some(chan) => chan
2322                                                 };
2323                                                 if !chan.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
2324                                                         // Note that the behavior here should be identical to the above block - we
2325                                                         // should NOT reveal the existence or non-existence of a private channel if
2326                                                         // we don't allow forwards outbound over them.
2327                                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
2328                                                 }
2329                                                 if chan.get_channel_type().supports_scid_privacy() && *short_channel_id != chan.outbound_scid_alias() {
2330                                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
2331                                                         // "refuse to forward unless the SCID alias was used", so we pretend
2332                                                         // we don't have the channel here.
2333                                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
2334                                                 }
2335                                                 let chan_update_opt = self.get_channel_update_for_onion(*short_channel_id, chan).ok();
2336
2337                                                 // Note that we could technically not return an error yet here and just hope
2338                                                 // that the connection is reestablished or monitor updated by the time we get
2339                                                 // around to doing the actual forward, but better to fail early if we can and
2340                                                 // hopefully an attacker trying to path-trace payments cannot make this occur
2341                                                 // on a small/per-node/per-channel scale.
2342                                                 if !chan.is_live() { // channel_disabled
2343                                                         break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, chan_update_opt));
2344                                                 }
2345                                                 if *outgoing_amt_msat < chan.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
2346                                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
2347                                                 }
2348                                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, *outgoing_amt_msat, *outgoing_cltv_value) {
2349                                                         break Some((err, code, chan_update_opt));
2350                                                 }
2351                                                 chan_update_opt
2352                                         } else {
2353                                                 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
2354                                                         // We really should set `incorrect_cltv_expiry` here but as we're not
2355                                                         // forwarding over a real channel we can't generate a channel_update
2356                                                         // for it. Instead we just return a generic temporary_node_failure.
2357                                                         break Some((
2358                                                                 "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
2359                                                                 0x2000 | 2, None,
2360                                                         ));
2361                                                 }
2362                                                 None
2363                                         };
2364
2365                                         let cur_height = self.best_block.read().unwrap().height() + 1;
2366                                         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now,
2367                                         // but we want to be robust wrt to counterparty packet sanitization (see
2368                                         // HTLC_FAIL_BACK_BUFFER rationale).
2369                                         if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
2370                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, chan_update_opt));
2371                                         }
2372                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
2373                                                 break Some(("CLTV expiry is too far in the future", 21, None));
2374                                         }
2375                                         // If the HTLC expires ~now, don't bother trying to forward it to our
2376                                         // counterparty. They should fail it anyway, but we don't want to bother with
2377                                         // the round-trips or risk them deciding they definitely want the HTLC and
2378                                         // force-closing to ensure they get it if we're offline.
2379                                         // We previously had a much more aggressive check here which tried to ensure
2380                                         // our counterparty receives an HTLC which has *our* risk threshold met on it,
2381                                         // but there is no need to do that, and since we're a bit conservative with our
2382                                         // risk threshold it just results in failing to forward payments.
2383                                         if (*outgoing_cltv_value) as u64 <= (cur_height + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
2384                                                 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, chan_update_opt));
2385                                         }
2386
2387                                         break None;
2388                                 }
2389                                 {
2390                                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
2391                                         if let Some(chan_update) = chan_update {
2392                                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
2393                                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
2394                                                 }
2395                                                 else if code == 0x1000 | 13 {
2396                                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
2397                                                 }
2398                                                 else if code == 0x1000 | 20 {
2399                                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
2400                                                         0u16.write(&mut res).expect("Writes cannot fail");
2401                                                 }
2402                                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
2403                                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
2404                                                 chan_update.write(&mut res).expect("Writes cannot fail");
2405                                         } else if code & 0x1000 == 0x1000 {
2406                                                 // If we're trying to return an error that requires a `channel_update` but
2407                                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
2408                                                 // generate an update), just use the generic "temporary_node_failure"
2409                                                 // instead.
2410                                                 code = 0x2000 | 2;
2411                                         }
2412                                         return_err!(err, code, &res.0[..]);
2413                                 }
2414                         }
2415                 }
2416
2417                 pending_forward_info
2418         }
2419
2420         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
2421         /// public, and thus should be called whenever the result is going to be passed out in a
2422         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
2423         ///
2424         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
2425         /// corresponding to the channel's counterparty locked, as the channel been removed from the
2426         /// storage and the `peer_state` lock has been dropped.
2427         ///
2428         /// [`channel_update`]: msgs::ChannelUpdate
2429         /// [`internal_closing_signed`]: Self::internal_closing_signed
2430         fn get_channel_update_for_broadcast(&self, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
2431                 if !chan.should_announce() {
2432                         return Err(LightningError {
2433                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
2434                                 action: msgs::ErrorAction::IgnoreError
2435                         });
2436                 }
2437                 if chan.get_short_channel_id().is_none() {
2438                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
2439                 }
2440                 log_trace!(self.logger, "Attempting to generate broadcast channel update for channel {}", log_bytes!(chan.channel_id()));
2441                 self.get_channel_update_for_unicast(chan)
2442         }
2443
2444         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
2445         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
2446         /// and thus MUST NOT be called unless the recipient of the resulting message has already
2447         /// provided evidence that they know about the existence of the channel.
2448         ///
2449         /// Note that through [`internal_closing_signed`], this function is called without the
2450         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
2451         /// removed from the storage and the `peer_state` lock has been dropped.
2452         ///
2453         /// [`channel_update`]: msgs::ChannelUpdate
2454         /// [`internal_closing_signed`]: Self::internal_closing_signed
2455         fn get_channel_update_for_unicast(&self, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
2456                 log_trace!(self.logger, "Attempting to generate channel update for channel {}", log_bytes!(chan.channel_id()));
2457                 let short_channel_id = match chan.get_short_channel_id().or(chan.latest_inbound_scid_alias()) {
2458                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
2459                         Some(id) => id,
2460                 };
2461
2462                 self.get_channel_update_for_onion(short_channel_id, chan)
2463         }
2464         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
2465                 log_trace!(self.logger, "Generating channel update for channel {}", log_bytes!(chan.channel_id()));
2466                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.get_counterparty_node_id().serialize()[..];
2467
2468                 let unsigned = msgs::UnsignedChannelUpdate {
2469                         chain_hash: self.genesis_hash,
2470                         short_channel_id,
2471                         timestamp: chan.get_update_time_counter(),
2472                         flags: (!were_node_one) as u8 | ((!chan.is_live() as u8) << 1),
2473                         cltv_expiry_delta: chan.get_cltv_expiry_delta(),
2474                         htlc_minimum_msat: chan.get_counterparty_htlc_minimum_msat(),
2475                         htlc_maximum_msat: chan.get_announced_htlc_max_msat(),
2476                         fee_base_msat: chan.get_outbound_forwarding_fee_base_msat(),
2477                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
2478                         excess_data: Vec::new(),
2479                 };
2480                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
2481                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
2482                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
2483                 // channel.
2484                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
2485
2486                 Ok(msgs::ChannelUpdate {
2487                         signature: sig,
2488                         contents: unsigned
2489                 })
2490         }
2491
2492         #[cfg(test)]
2493         pub(crate) fn test_send_payment_along_path(&self, path: &Vec<RouteHop>, payment_hash: &PaymentHash, payment_secret: &Option<PaymentSecret>, total_value: u64, cur_height: u32, payment_id: PaymentId, keysend_preimage: &Option<PaymentPreimage>, session_priv_bytes: [u8; 32]) -> Result<(), APIError> {
2494                 let _lck = self.total_consistency_lock.read().unwrap();
2495                 self.send_payment_along_path(path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv_bytes)
2496         }
2497
2498         fn send_payment_along_path(&self, path: &Vec<RouteHop>, payment_hash: &PaymentHash, payment_secret: &Option<PaymentSecret>, total_value: u64, cur_height: u32, payment_id: PaymentId, keysend_preimage: &Option<PaymentPreimage>, session_priv_bytes: [u8; 32]) -> Result<(), APIError> {
2499                 // The top-level caller should hold the total_consistency_lock read lock.
2500                 debug_assert!(self.total_consistency_lock.try_write().is_err());
2501
2502                 log_trace!(self.logger, "Attempting to send payment for path with next hop {}", path.first().unwrap().short_channel_id);
2503                 let prng_seed = self.entropy_source.get_secure_random_bytes();
2504                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
2505
2506                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
2507                         .map_err(|_| APIError::InvalidRoute{err: "Pubkey along hop was maliciously selected".to_owned()})?;
2508                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, payment_secret, cur_height, keysend_preimage)?;
2509                 if onion_utils::route_size_insane(&onion_payloads) {
2510                         return Err(APIError::InvalidRoute{err: "Route size too large considering onion data".to_owned()});
2511                 }
2512                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash);
2513
2514                 let err: Result<(), _> = loop {
2515                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.first().unwrap().short_channel_id) {
2516                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
2517                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
2518                         };
2519
2520                         let per_peer_state = self.per_peer_state.read().unwrap();
2521                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
2522                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
2523                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2524                         let peer_state = &mut *peer_state_lock;
2525                         if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(id) {
2526                                 if !chan.get().is_live() {
2527                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
2528                                 }
2529                                 let funding_txo = chan.get().get_funding_txo().unwrap();
2530                                 let send_res = chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(),
2531                                         htlc_cltv, HTLCSource::OutboundRoute {
2532                                                 path: path.clone(),
2533                                                 session_priv: session_priv.clone(),
2534                                                 first_hop_htlc_msat: htlc_msat,
2535                                                 payment_id,
2536                                                 payment_secret: payment_secret.clone(),
2537                                         }, onion_packet, &self.logger);
2538                                 match break_chan_entry!(self, send_res, chan) {
2539                                         Some(monitor_update) => {
2540                                                 let update_id = monitor_update.update_id;
2541                                                 let update_res = self.chain_monitor.update_channel(funding_txo, monitor_update);
2542                                                 if let Err(e) = handle_new_monitor_update!(self, update_res, update_id, peer_state_lock, peer_state, per_peer_state, chan) {
2543                                                         break Err(e);
2544                                                 }
2545                                                 if update_res == ChannelMonitorUpdateStatus::InProgress {
2546                                                         // Note that MonitorUpdateInProgress here indicates (per function
2547                                                         // docs) that we will resend the commitment update once monitor
2548                                                         // updating completes. Therefore, we must return an error
2549                                                         // indicating that it is unsafe to retry the payment wholesale,
2550                                                         // which we do in the send_payment check for
2551                                                         // MonitorUpdateInProgress, below.
2552                                                         return Err(APIError::MonitorUpdateInProgress);
2553                                                 }
2554                                         },
2555                                         None => { },
2556                                 }
2557                         } else {
2558                                 // The channel was likely removed after we fetched the id from the
2559                                 // `short_to_chan_info` map, but before we successfully locked the
2560                                 // `channel_by_id` map.
2561                                 // This can occur as no consistency guarantees exists between the two maps.
2562                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
2563                         }
2564                         return Ok(());
2565                 };
2566
2567                 match handle_error!(self, err, path.first().unwrap().pubkey) {
2568                         Ok(_) => unreachable!(),
2569                         Err(e) => {
2570                                 Err(APIError::ChannelUnavailable { err: e.err })
2571                         },
2572                 }
2573         }
2574
2575         /// Sends a payment along a given route.
2576         ///
2577         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
2578         /// fields for more info.
2579         ///
2580         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
2581         /// [`PeerManager::process_events`]).
2582         ///
2583         /// # Avoiding Duplicate Payments
2584         ///
2585         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
2586         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
2587         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
2588         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
2589         /// second payment with the same [`PaymentId`].
2590         ///
2591         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
2592         /// tracking of payments, including state to indicate once a payment has completed. Because you
2593         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
2594         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
2595         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
2596         ///
2597         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
2598         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
2599         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
2600         /// [`ChannelManager::list_recent_payments`] for more information.
2601         ///
2602         /// # Possible Error States on [`PaymentSendFailure`]
2603         ///
2604         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
2605         /// each entry matching the corresponding-index entry in the route paths, see
2606         /// [`PaymentSendFailure`] for more info.
2607         ///
2608         /// In general, a path may raise:
2609         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
2610         ///    node public key) is specified.
2611         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available for updates
2612         ///    (including due to previous monitor update failure or new permanent monitor update
2613         ///    failure).
2614         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
2615         ///    relevant updates.
2616         ///
2617         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
2618         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
2619         /// different route unless you intend to pay twice!
2620         ///
2621         /// # A caution on `payment_secret`
2622         ///
2623         /// `payment_secret` is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
2624         /// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
2625         /// attacks. For newer nodes, it will be provided to you in the invoice. If you do not have one,
2626         /// the [`Route`] must not contain multiple paths as multi-path payments require a
2627         /// recipient-provided `payment_secret`.
2628         ///
2629         /// If a `payment_secret` *is* provided, we assume that the invoice had the payment_secret
2630         /// feature bit set (either as required or as available). If multiple paths are present in the
2631         /// [`Route`], we assume the invoice had the basic_mpp feature set.
2632         ///
2633         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2634         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
2635         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
2636         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
2637         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
2638         pub fn send_payment(&self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
2639                 let best_block_height = self.best_block.read().unwrap().height();
2640                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2641                 self.pending_outbound_payments
2642                         .send_payment_with_route(route, payment_hash, payment_secret, payment_id, &self.entropy_source, &self.node_signer, best_block_height,
2643                                 |path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2644                                 self.send_payment_along_path(path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2645         }
2646
2647         /// Similar to [`ChannelManager::send_payment`], but will automatically find a route based on
2648         /// `route_params` and retry failed payment paths based on `retry_strategy`.
2649         pub fn send_payment_with_retry(&self, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
2650                 let best_block_height = self.best_block.read().unwrap().height();
2651                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2652                 self.pending_outbound_payments
2653                         .send_payment(payment_hash, payment_secret, payment_id, retry_strategy, route_params,
2654                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
2655                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
2656                                 &self.pending_events,
2657                                 |path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2658                                 self.send_payment_along_path(path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2659         }
2660
2661         #[cfg(test)]
2662         fn test_send_payment_internal(&self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>, keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>, onion_session_privs: Vec<[u8; 32]>) -> Result<(), PaymentSendFailure> {
2663                 let best_block_height = self.best_block.read().unwrap().height();
2664                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2665                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, payment_secret, keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer, best_block_height,
2666                         |path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2667                         self.send_payment_along_path(path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2668         }
2669
2670         #[cfg(test)]
2671         pub(crate) fn test_add_new_pending_payment(&self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId, route: &Route) -> Result<Vec<[u8; 32]>, PaymentSendFailure> {
2672                 let best_block_height = self.best_block.read().unwrap().height();
2673                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, payment_secret, payment_id, route, None, &self.entropy_source, best_block_height)
2674         }
2675
2676
2677         /// Signals that no further retries for the given payment should occur. Useful if you have a
2678         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
2679         /// retries are exhausted.
2680         ///
2681         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
2682         /// as there are no remaining pending HTLCs for this payment.
2683         ///
2684         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
2685         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
2686         /// determine the ultimate status of a payment.
2687         ///
2688         /// If an [`Event::PaymentFailed`] event is generated and we restart without this
2689         /// [`ChannelManager`] having been persisted, another [`Event::PaymentFailed`] may be generated.
2690         ///
2691         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
2692         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2693         pub fn abandon_payment(&self, payment_id: PaymentId) {
2694                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2695                 self.pending_outbound_payments.abandon_payment(payment_id, &self.pending_events);
2696         }
2697
2698         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
2699         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
2700         /// the preimage, it must be a cryptographically secure random value that no intermediate node
2701         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
2702         /// never reach the recipient.
2703         ///
2704         /// See [`send_payment`] documentation for more details on the return value of this function
2705         /// and idempotency guarantees provided by the [`PaymentId`] key.
2706         ///
2707         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
2708         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
2709         ///
2710         /// Note that `route` must have exactly one path.
2711         ///
2712         /// [`send_payment`]: Self::send_payment
2713         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
2714                 let best_block_height = self.best_block.read().unwrap().height();
2715                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2716                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
2717                         route, payment_preimage, payment_id, &self.entropy_source, &self.node_signer,
2718                         best_block_height,
2719                         |path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2720                         self.send_payment_along_path(path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2721         }
2722
2723         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
2724         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
2725         ///
2726         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
2727         /// payments.
2728         ///
2729         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
2730         pub fn send_spontaneous_payment_with_retry(&self, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<PaymentHash, RetryableSendFailure> {
2731                 let best_block_height = self.best_block.read().unwrap().height();
2732                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2733                 self.pending_outbound_payments.send_spontaneous_payment(payment_preimage, payment_id,
2734                         retry_strategy, route_params, &self.router, self.list_usable_channels(),
2735                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
2736                         &self.logger, &self.pending_events,
2737                         |path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2738                         self.send_payment_along_path(path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2739         }
2740
2741         /// Send a payment that is probing the given route for liquidity. We calculate the
2742         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
2743         /// us to easily discern them from real payments.
2744         pub fn send_probe(&self, hops: Vec<RouteHop>) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
2745                 let best_block_height = self.best_block.read().unwrap().height();
2746                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2747                 self.pending_outbound_payments.send_probe(hops, self.probing_cookie_secret, &self.entropy_source, &self.node_signer, best_block_height,
2748                         |path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2749                         self.send_payment_along_path(path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2750         }
2751
2752         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
2753         /// payment probe.
2754         #[cfg(test)]
2755         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
2756                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
2757         }
2758
2759         /// Handles the generation of a funding transaction, optionally (for tests) with a function
2760         /// which checks the correctness of the funding transaction given the associated channel.
2761         fn funding_transaction_generated_intern<FundingOutput: Fn(&Channel<<SP::Target as SignerProvider>::Signer>, &Transaction) -> Result<OutPoint, APIError>>(
2762                 &self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, funding_transaction: Transaction, find_funding_output: FundingOutput
2763         ) -> Result<(), APIError> {
2764                 let per_peer_state = self.per_peer_state.read().unwrap();
2765                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2766                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2767
2768                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2769                 let peer_state = &mut *peer_state_lock;
2770                 let (chan, msg) = {
2771                         let (res, chan) = {
2772                                 match peer_state.channel_by_id.remove(temporary_channel_id) {
2773                                         Some(mut chan) => {
2774                                                 let funding_txo = find_funding_output(&chan, &funding_transaction)?;
2775
2776                                                 (chan.get_outbound_funding_created(funding_transaction, funding_txo, &self.logger)
2777                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
2778                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.get_user_id(), chan.force_shutdown(true), None)
2779                                                         } else { unreachable!(); })
2780                                                 , chan)
2781                                         },
2782                                         None => { return Err(APIError::ChannelUnavailable { err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(*temporary_channel_id), counterparty_node_id) }) },
2783                                 }
2784                         };
2785                         match handle_error!(self, res, chan.get_counterparty_node_id()) {
2786                                 Ok(funding_msg) => {
2787                                         (chan, funding_msg)
2788                                 },
2789                                 Err(_) => { return Err(APIError::ChannelUnavailable {
2790                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
2791                                 }) },
2792                         }
2793                 };
2794
2795                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
2796                         node_id: chan.get_counterparty_node_id(),
2797                         msg,
2798                 });
2799                 match peer_state.channel_by_id.entry(chan.channel_id()) {
2800                         hash_map::Entry::Occupied(_) => {
2801                                 panic!("Generated duplicate funding txid?");
2802                         },
2803                         hash_map::Entry::Vacant(e) => {
2804                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
2805                                 if id_to_peer.insert(chan.channel_id(), chan.get_counterparty_node_id()).is_some() {
2806                                         panic!("id_to_peer map already contained funding txid, which shouldn't be possible");
2807                                 }
2808                                 e.insert(chan);
2809                         }
2810                 }
2811                 Ok(())
2812         }
2813
2814         #[cfg(test)]
2815         pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> {
2816                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, |_, tx| {
2817                         Ok(OutPoint { txid: tx.txid(), index: output_index })
2818                 })
2819         }
2820
2821         /// Call this upon creation of a funding transaction for the given channel.
2822         ///
2823         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
2824         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
2825         ///
2826         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
2827         /// across the p2p network.
2828         ///
2829         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
2830         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
2831         ///
2832         /// May panic if the output found in the funding transaction is duplicative with some other
2833         /// channel (note that this should be trivially prevented by using unique funding transaction
2834         /// keys per-channel).
2835         ///
2836         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
2837         /// counterparty's signature the funding transaction will automatically be broadcast via the
2838         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
2839         ///
2840         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
2841         /// not currently support replacing a funding transaction on an existing channel. Instead,
2842         /// create a new channel with a conflicting funding transaction.
2843         ///
2844         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
2845         /// the wallet software generating the funding transaction to apply anti-fee sniping as
2846         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
2847         /// for more details.
2848         ///
2849         /// [`Event::FundingGenerationReady`]: crate::util::events::Event::FundingGenerationReady
2850         /// [`Event::ChannelClosed`]: crate::util::events::Event::ChannelClosed
2851         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
2852                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2853
2854                 for inp in funding_transaction.input.iter() {
2855                         if inp.witness.is_empty() {
2856                                 return Err(APIError::APIMisuseError {
2857                                         err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
2858                                 });
2859                         }
2860                 }
2861                 {
2862                         let height = self.best_block.read().unwrap().height();
2863                         // Transactions are evaluated as final by network mempools at the next block. However, the modules
2864                         // constituting our Lightning node might not have perfect sync about their blockchain views. Thus, if
2865                         // the wallet module is in advance on the LDK view, allow one more block of headroom.
2866                         if !funding_transaction.input.iter().all(|input| input.sequence == Sequence::MAX) && LockTime::from(funding_transaction.lock_time).is_block_height() && funding_transaction.lock_time.0 > height + 2 {
2867                                 return Err(APIError::APIMisuseError {
2868                                         err: "Funding transaction absolute timelock is non-final".to_owned()
2869                                 });
2870                         }
2871                 }
2872                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, |chan, tx| {
2873                         let mut output_index = None;
2874                         let expected_spk = chan.get_funding_redeemscript().to_v0_p2wsh();
2875                         for (idx, outp) in tx.output.iter().enumerate() {
2876                                 if outp.script_pubkey == expected_spk && outp.value == chan.get_value_satoshis() {
2877                                         if output_index.is_some() {
2878                                                 return Err(APIError::APIMisuseError {
2879                                                         err: "Multiple outputs matched the expected script and value".to_owned()
2880                                                 });
2881                                         }
2882                                         if idx > u16::max_value() as usize {
2883                                                 return Err(APIError::APIMisuseError {
2884                                                         err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
2885                                                 });
2886                                         }
2887                                         output_index = Some(idx as u16);
2888                                 }
2889                         }
2890                         if output_index.is_none() {
2891                                 return Err(APIError::APIMisuseError {
2892                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
2893                                 });
2894                         }
2895                         Ok(OutPoint { txid: tx.txid(), index: output_index.unwrap() })
2896                 })
2897         }
2898
2899         /// Atomically updates the [`ChannelConfig`] for the given channels.
2900         ///
2901         /// Once the updates are applied, each eligible channel (advertised with a known short channel
2902         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
2903         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
2904         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
2905         ///
2906         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
2907         /// `counterparty_node_id` is provided.
2908         ///
2909         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
2910         /// below [`MIN_CLTV_EXPIRY_DELTA`].
2911         ///
2912         /// If an error is returned, none of the updates should be considered applied.
2913         ///
2914         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
2915         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
2916         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
2917         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
2918         /// [`ChannelUpdate`]: msgs::ChannelUpdate
2919         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
2920         /// [`APIMisuseError`]: APIError::APIMisuseError
2921         pub fn update_channel_config(
2922                 &self, counterparty_node_id: &PublicKey, channel_ids: &[[u8; 32]], config: &ChannelConfig,
2923         ) -> Result<(), APIError> {
2924                 if config.cltv_expiry_delta < MIN_CLTV_EXPIRY_DELTA {
2925                         return Err(APIError::APIMisuseError {
2926                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
2927                         });
2928                 }
2929
2930                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(
2931                         &self.total_consistency_lock, &self.persistence_notifier,
2932                 );
2933                 let per_peer_state = self.per_peer_state.read().unwrap();
2934                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2935                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2936                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2937                 let peer_state = &mut *peer_state_lock;
2938                 for channel_id in channel_ids {
2939                         if !peer_state.channel_by_id.contains_key(channel_id) {
2940                                 return Err(APIError::ChannelUnavailable {
2941                                         err: format!("Channel with ID {} was not found for the passed counterparty_node_id {}", log_bytes!(*channel_id), counterparty_node_id),
2942                                 });
2943                         }
2944                 }
2945                 for channel_id in channel_ids {
2946                         let channel = peer_state.channel_by_id.get_mut(channel_id).unwrap();
2947                         if !channel.update_config(config) {
2948                                 continue;
2949                         }
2950                         if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
2951                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
2952                         } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
2953                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
2954                                         node_id: channel.get_counterparty_node_id(),
2955                                         msg,
2956                                 });
2957                         }
2958                 }
2959                 Ok(())
2960         }
2961
2962         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
2963         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
2964         ///
2965         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
2966         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
2967         ///
2968         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
2969         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
2970         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
2971         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
2972         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
2973         ///
2974         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
2975         /// you from forwarding more than you received.
2976         ///
2977         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
2978         /// backwards.
2979         ///
2980         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
2981         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
2982         // TODO: when we move to deciding the best outbound channel at forward time, only take
2983         // `next_node_id` and not `next_hop_channel_id`
2984         pub fn forward_intercepted_htlc(&self, intercept_id: InterceptId, next_hop_channel_id: &[u8; 32], next_node_id: PublicKey, amt_to_forward_msat: u64) -> Result<(), APIError> {
2985                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2986
2987                 let next_hop_scid = {
2988                         let peer_state_lock = self.per_peer_state.read().unwrap();
2989                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
2990                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
2991                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2992                         let peer_state = &mut *peer_state_lock;
2993                         match peer_state.channel_by_id.get(next_hop_channel_id) {
2994                                 Some(chan) => {
2995                                         if !chan.is_usable() {
2996                                                 return Err(APIError::ChannelUnavailable {
2997                                                         err: format!("Channel with id {} not fully established", log_bytes!(*next_hop_channel_id))
2998                                                 })
2999                                         }
3000                                         chan.get_short_channel_id().unwrap_or(chan.outbound_scid_alias())
3001                                 },
3002                                 None => return Err(APIError::ChannelUnavailable {
3003                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(*next_hop_channel_id), next_node_id)
3004                                 })
3005                         }
3006                 };
3007
3008                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
3009                         .ok_or_else(|| APIError::APIMisuseError {
3010                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
3011                         })?;
3012
3013                 let routing = match payment.forward_info.routing {
3014                         PendingHTLCRouting::Forward { onion_packet, .. } => {
3015                                 PendingHTLCRouting::Forward { onion_packet, short_channel_id: next_hop_scid }
3016                         },
3017                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
3018                 };
3019                 let pending_htlc_info = PendingHTLCInfo {
3020                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
3021                 };
3022
3023                 let mut per_source_pending_forward = [(
3024                         payment.prev_short_channel_id,
3025                         payment.prev_funding_outpoint,
3026                         payment.prev_user_channel_id,
3027                         vec![(pending_htlc_info, payment.prev_htlc_id)]
3028                 )];
3029                 self.forward_htlcs(&mut per_source_pending_forward);
3030                 Ok(())
3031         }
3032
3033         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
3034         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
3035         ///
3036         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
3037         /// backwards.
3038         ///
3039         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
3040         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
3041                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3042
3043                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
3044                         .ok_or_else(|| APIError::APIMisuseError {
3045                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
3046                         })?;
3047
3048                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
3049                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3050                                 short_channel_id: payment.prev_short_channel_id,
3051                                 outpoint: payment.prev_funding_outpoint,
3052                                 htlc_id: payment.prev_htlc_id,
3053                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
3054                                 phantom_shared_secret: None,
3055                         });
3056
3057                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
3058                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
3059                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
3060                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
3061
3062                 Ok(())
3063         }
3064
3065         /// Processes HTLCs which are pending waiting on random forward delay.
3066         ///
3067         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
3068         /// Will likely generate further events.
3069         pub fn process_pending_htlc_forwards(&self) {
3070                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3071
3072                 let mut new_events = Vec::new();
3073                 let mut failed_forwards = Vec::new();
3074                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
3075                 {
3076                         let mut forward_htlcs = HashMap::new();
3077                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
3078
3079                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
3080                                 if short_chan_id != 0 {
3081                                         macro_rules! forwarding_channel_not_found {
3082                                                 () => {
3083                                                         for forward_info in pending_forwards.drain(..) {
3084                                                                 match forward_info {
3085                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
3086                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
3087                                                                                 forward_info: PendingHTLCInfo {
3088                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
3089                                                                                         outgoing_cltv_value, incoming_amt_msat: _
3090                                                                                 }
3091                                                                         }) => {
3092                                                                                 macro_rules! failure_handler {
3093                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
3094                                                                                                 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3095
3096                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3097                                                                                                         short_channel_id: prev_short_channel_id,
3098                                                                                                         outpoint: prev_funding_outpoint,
3099                                                                                                         htlc_id: prev_htlc_id,
3100                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
3101                                                                                                         phantom_shared_secret: $phantom_ss,
3102                                                                                                 });
3103
3104                                                                                                 let reason = if $next_hop_unknown {
3105                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
3106                                                                                                 } else {
3107                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
3108                                                                                                 };
3109
3110                                                                                                 failed_forwards.push((htlc_source, payment_hash,
3111                                                                                                         HTLCFailReason::reason($err_code, $err_data),
3112                                                                                                         reason
3113                                                                                                 ));
3114                                                                                                 continue;
3115                                                                                         }
3116                                                                                 }
3117                                                                                 macro_rules! fail_forward {
3118                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
3119                                                                                                 {
3120                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
3121                                                                                                 }
3122                                                                                         }
3123                                                                                 }
3124                                                                                 macro_rules! failed_payment {
3125                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
3126                                                                                                 {
3127                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
3128                                                                                                 }
3129                                                                                         }
3130                                                                                 }
3131                                                                                 if let PendingHTLCRouting::Forward { onion_packet, .. } = routing {
3132                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
3133                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.genesis_hash) {
3134                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
3135                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac, payment_hash) {
3136                                                                                                         Ok(res) => res,
3137                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
3138                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();
3139                                                                                                                 // In this scenario, the phantom would have sent us an
3140                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
3141                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
3142                                                                                                                 // of the onion.
3143                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
3144                                                                                                         },
3145                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
3146                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
3147                                                                                                         },
3148                                                                                                 };
3149                                                                                                 match next_hop {
3150                                                                                                         onion_utils::Hop::Receive(hop_data) => {
3151                                                                                                                 match self.construct_recv_pending_htlc_info(hop_data, incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value, Some(phantom_shared_secret)) {
3152                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
3153                                                                                                                         Err(ReceiveError { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
3154                                                                                                                 }
3155                                                                                                         },
3156                                                                                                         _ => panic!(),
3157                                                                                                 }
3158                                                                                         } else {
3159                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
3160                                                                                         }
3161                                                                                 } else {
3162                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
3163                                                                                 }
3164                                                                         },
3165                                                                         HTLCForwardInfo::FailHTLC { .. } => {
3166                                                                                 // Channel went away before we could fail it. This implies
3167                                                                                 // the channel is now on chain and our counterparty is
3168                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
3169                                                                                 // problem, not ours.
3170                                                                         }
3171                                                                 }
3172                                                         }
3173                                                 }
3174                                         }
3175                                         let (counterparty_node_id, forward_chan_id) = match self.short_to_chan_info.read().unwrap().get(&short_chan_id) {
3176                                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3177                                                 None => {
3178                                                         forwarding_channel_not_found!();
3179                                                         continue;
3180                                                 }
3181                                         };
3182                                         let per_peer_state = self.per_peer_state.read().unwrap();
3183                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
3184                                         if peer_state_mutex_opt.is_none() {
3185                                                 forwarding_channel_not_found!();
3186                                                 continue;
3187                                         }
3188                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3189                                         let peer_state = &mut *peer_state_lock;
3190                                         match peer_state.channel_by_id.entry(forward_chan_id) {
3191                                                 hash_map::Entry::Vacant(_) => {
3192                                                         forwarding_channel_not_found!();
3193                                                         continue;
3194                                                 },
3195                                                 hash_map::Entry::Occupied(mut chan) => {
3196                                                         for forward_info in pending_forwards.drain(..) {
3197                                                                 match forward_info {
3198                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
3199                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id: _,
3200                                                                                 forward_info: PendingHTLCInfo {
3201                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
3202                                                                                         routing: PendingHTLCRouting::Forward { onion_packet, .. }, incoming_amt_msat: _,
3203                                                                                 },
3204                                                                         }) => {
3205                                                                                 log_trace!(self.logger, "Adding HTLC from short id {} with payment_hash {} to channel with short id {} after delay", prev_short_channel_id, log_bytes!(payment_hash.0), short_chan_id);
3206                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3207                                                                                         short_channel_id: prev_short_channel_id,
3208                                                                                         outpoint: prev_funding_outpoint,
3209                                                                                         htlc_id: prev_htlc_id,
3210                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
3211                                                                                         // Phantom payments are only PendingHTLCRouting::Receive.
3212                                                                                         phantom_shared_secret: None,
3213                                                                                 });
3214                                                                                 if let Err(e) = chan.get_mut().queue_add_htlc(outgoing_amt_msat,
3215                                                                                         payment_hash, outgoing_cltv_value, htlc_source.clone(),
3216                                                                                         onion_packet, &self.logger)
3217                                                                                 {
3218                                                                                         if let ChannelError::Ignore(msg) = e {
3219                                                                                                 log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
3220                                                                                         } else {
3221                                                                                                 panic!("Stated return value requirements in send_htlc() were not met");
3222                                                                                         }
3223                                                                                         let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan.get());
3224                                                                                         failed_forwards.push((htlc_source, payment_hash,
3225                                                                                                 HTLCFailReason::reason(failure_code, data),
3226                                                                                                 HTLCDestination::NextHopChannel { node_id: Some(chan.get().get_counterparty_node_id()), channel_id: forward_chan_id }
3227                                                                                         ));
3228                                                                                         continue;
3229                                                                                 }
3230                                                                         },
3231                                                                         HTLCForwardInfo::AddHTLC { .. } => {
3232                                                                                 panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
3233                                                                         },
3234                                                                         HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
3235                                                                                 log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
3236                                                                                 if let Err(e) = chan.get_mut().queue_fail_htlc(
3237                                                                                         htlc_id, err_packet, &self.logger
3238                                                                                 ) {
3239                                                                                         if let ChannelError::Ignore(msg) = e {
3240                                                                                                 log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
3241                                                                                         } else {
3242                                                                                                 panic!("Stated return value requirements in queue_fail_htlc() were not met");
3243                                                                                         }
3244                                                                                         // fail-backs are best-effort, we probably already have one
3245                                                                                         // pending, and if not that's OK, if not, the channel is on
3246                                                                                         // the chain and sending the HTLC-Timeout is their problem.
3247                                                                                         continue;
3248                                                                                 }
3249                                                                         },
3250                                                                 }
3251                                                         }
3252                                                 }
3253                                         }
3254                                 } else {
3255                                         for forward_info in pending_forwards.drain(..) {
3256                                                 match forward_info {
3257                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
3258                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
3259                                                                 forward_info: PendingHTLCInfo {
3260                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat, ..
3261                                                                 }
3262                                                         }) => {
3263                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret) = match routing {
3264                                                                         PendingHTLCRouting::Receive { payment_data, incoming_cltv_expiry, phantom_shared_secret } => {
3265                                                                                 let _legacy_hop_data = Some(payment_data.clone());
3266                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data }, Some(payment_data), phantom_shared_secret)
3267                                                                         },
3268                                                                         PendingHTLCRouting::ReceiveKeysend { payment_preimage, incoming_cltv_expiry } =>
3269                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage), None, None),
3270                                                                         _ => {
3271                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
3272                                                                         }
3273                                                                 };
3274                                                                 let claimable_htlc = ClaimableHTLC {
3275                                                                         prev_hop: HTLCPreviousHopData {
3276                                                                                 short_channel_id: prev_short_channel_id,
3277                                                                                 outpoint: prev_funding_outpoint,
3278                                                                                 htlc_id: prev_htlc_id,
3279                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
3280                                                                                 phantom_shared_secret,
3281                                                                         },
3282                                                                         value: outgoing_amt_msat,
3283                                                                         timer_ticks: 0,
3284                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
3285                                                                         cltv_expiry,
3286                                                                         onion_payload,
3287                                                                 };
3288
3289                                                                 macro_rules! fail_htlc {
3290                                                                         ($htlc: expr, $payment_hash: expr) => {
3291                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
3292                                                                                 htlc_msat_height_data.extend_from_slice(
3293                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
3294                                                                                 );
3295                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
3296                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
3297                                                                                                 outpoint: prev_funding_outpoint,
3298                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
3299                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
3300                                                                                                 phantom_shared_secret,
3301                                                                                         }), payment_hash,
3302                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
3303                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
3304                                                                                 ));
3305                                                                         }
3306                                                                 }
3307                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
3308                                                                 let mut receiver_node_id = self.our_network_pubkey;
3309                                                                 if phantom_shared_secret.is_some() {
3310                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
3311                                                                                 .expect("Failed to get node_id for phantom node recipient");
3312                                                                 }
3313
3314                                                                 macro_rules! check_total_value {
3315                                                                         ($payment_data: expr, $payment_preimage: expr) => {{
3316                                                                                 let mut payment_claimable_generated = false;
3317                                                                                 let purpose = || {
3318                                                                                         events::PaymentPurpose::InvoicePayment {
3319                                                                                                 payment_preimage: $payment_preimage,
3320                                                                                                 payment_secret: $payment_data.payment_secret,
3321                                                                                         }
3322                                                                                 };
3323                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
3324                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
3325                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3326                                                                                         continue
3327                                                                                 }
3328                                                                                 let (_, htlcs) = claimable_payments.claimable_htlcs.entry(payment_hash)
3329                                                                                         .or_insert_with(|| (purpose(), Vec::new()));
3330                                                                                 if htlcs.len() == 1 {
3331                                                                                         if let OnionPayload::Spontaneous(_) = htlcs[0].onion_payload {
3332                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as we already had an existing keysend HTLC with the same payment hash", log_bytes!(payment_hash.0));
3333                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
3334                                                                                                 continue
3335                                                                                         }
3336                                                                                 }
3337                                                                                 let mut total_value = claimable_htlc.value;
3338                                                                                 for htlc in htlcs.iter() {
3339                                                                                         total_value += htlc.value;
3340                                                                                         match &htlc.onion_payload {
3341                                                                                                 OnionPayload::Invoice { .. } => {
3342                                                                                                         if htlc.total_msat != $payment_data.total_msat {
3343                                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
3344                                                                                                                         log_bytes!(payment_hash.0), $payment_data.total_msat, htlc.total_msat);
3345                                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
3346                                                                                                         }
3347                                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
3348                                                                                                 },
3349                                                                                                 _ => unreachable!(),
3350                                                                                         }
3351                                                                                 }
3352                                                                                 if total_value >= msgs::MAX_VALUE_MSAT || total_value > $payment_data.total_msat {
3353                                                                                         log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the total value {} ran over expected value {} (or HTLCs were inconsistent)",
3354                                                                                                 log_bytes!(payment_hash.0), total_value, $payment_data.total_msat);
3355                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3356                                                                                 } else if total_value == $payment_data.total_msat {
3357                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
3358                                                                                         htlcs.push(claimable_htlc);
3359                                                                                         new_events.push(events::Event::PaymentClaimable {
3360                                                                                                 receiver_node_id: Some(receiver_node_id),
3361                                                                                                 payment_hash,
3362                                                                                                 purpose: purpose(),
3363                                                                                                 amount_msat: total_value,
3364                                                                                                 via_channel_id: Some(prev_channel_id),
3365                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
3366                                                                                         });
3367                                                                                         payment_claimable_generated = true;
3368                                                                                 } else {
3369                                                                                         // Nothing to do - we haven't reached the total
3370                                                                                         // payment value yet, wait until we receive more
3371                                                                                         // MPP parts.
3372                                                                                         htlcs.push(claimable_htlc);
3373                                                                                 }
3374                                                                                 payment_claimable_generated
3375                                                                         }}
3376                                                                 }
3377
3378                                                                 // Check that the payment hash and secret are known. Note that we
3379                                                                 // MUST take care to handle the "unknown payment hash" and
3380                                                                 // "incorrect payment secret" cases here identically or we'd expose
3381                                                                 // that we are the ultimate recipient of the given payment hash.
3382                                                                 // Further, we must not expose whether we have any other HTLCs
3383                                                                 // associated with the same payment_hash pending or not.
3384                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
3385                                                                 match payment_secrets.entry(payment_hash) {
3386                                                                         hash_map::Entry::Vacant(_) => {
3387                                                                                 match claimable_htlc.onion_payload {
3388                                                                                         OnionPayload::Invoice { .. } => {
3389                                                                                                 let payment_data = payment_data.unwrap();
3390                                                                                                 let (payment_preimage, min_final_cltv_expiry_delta) = match inbound_payment::verify(payment_hash, &payment_data, self.highest_seen_timestamp.load(Ordering::Acquire) as u64, &self.inbound_payment_key, &self.logger) {
3391                                                                                                         Ok(result) => result,
3392                                                                                                         Err(()) => {
3393                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", log_bytes!(payment_hash.0));
3394                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
3395                                                                                                                 continue
3396                                                                                                         }
3397                                                                                                 };
3398                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
3399                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
3400                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
3401                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
3402                                                                                                                         log_bytes!(payment_hash.0), cltv_expiry, expected_min_expiry_height);
3403                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
3404                                                                                                                 continue;
3405                                                                                                         }
3406                                                                                                 }
3407                                                                                                 check_total_value!(payment_data, payment_preimage);
3408                                                                                         },
3409                                                                                         OnionPayload::Spontaneous(preimage) => {
3410                                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
3411                                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
3412                                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3413                                                                                                         continue
3414                                                                                                 }
3415                                                                                                 match claimable_payments.claimable_htlcs.entry(payment_hash) {
3416                                                                                                         hash_map::Entry::Vacant(e) => {
3417                                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
3418                                                                                                                 e.insert((purpose.clone(), vec![claimable_htlc]));
3419                                                                                                                 let prev_channel_id = prev_funding_outpoint.to_channel_id();
3420                                                                                                                 new_events.push(events::Event::PaymentClaimable {
3421                                                                                                                         receiver_node_id: Some(receiver_node_id),
3422                                                                                                                         payment_hash,
3423                                                                                                                         amount_msat: outgoing_amt_msat,
3424                                                                                                                         purpose,
3425                                                                                                                         via_channel_id: Some(prev_channel_id),
3426                                                                                                                         via_user_channel_id: Some(prev_user_channel_id),
3427                                                                                                                 });
3428                                                                                                         },
3429                                                                                                         hash_map::Entry::Occupied(_) => {
3430                                                                                                                 log_trace!(self.logger, "Failing new keysend HTLC with payment_hash {} for a duplicative payment hash", log_bytes!(payment_hash.0));
3431                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
3432                                                                                                         }
3433                                                                                                 }
3434                                                                                         }
3435                                                                                 }
3436                                                                         },
3437                                                                         hash_map::Entry::Occupied(inbound_payment) => {
3438                                                                                 if payment_data.is_none() {
3439                                                                                         log_trace!(self.logger, "Failing new keysend HTLC with payment_hash {} because we already have an inbound payment with the same payment hash", log_bytes!(payment_hash.0));
3440                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3441                                                                                         continue
3442                                                                                 };
3443                                                                                 let payment_data = payment_data.unwrap();
3444                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
3445                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", log_bytes!(payment_hash.0));
3446                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3447                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
3448                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
3449                                                                                                 log_bytes!(payment_hash.0), payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
3450                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3451                                                                                 } else {
3452                                                                                         let payment_claimable_generated = check_total_value!(payment_data, inbound_payment.get().payment_preimage);
3453                                                                                         if payment_claimable_generated {
3454                                                                                                 inbound_payment.remove_entry();
3455                                                                                         }
3456                                                                                 }
3457                                                                         },
3458                                                                 };
3459                                                         },
3460                                                         HTLCForwardInfo::FailHTLC { .. } => {
3461                                                                 panic!("Got pending fail of our own HTLC");
3462                                                         }
3463                                                 }
3464                                         }
3465                                 }
3466                         }
3467                 }
3468
3469                 let best_block_height = self.best_block.read().unwrap().height();
3470                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
3471                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
3472                         &self.pending_events, &self.logger,
3473                         |path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
3474                         self.send_payment_along_path(path, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv));
3475
3476                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
3477                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
3478                 }
3479                 self.forward_htlcs(&mut phantom_receives);
3480
3481                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
3482                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
3483                 // nice to do the work now if we can rather than while we're trying to get messages in the
3484                 // network stack.
3485                 self.check_free_holding_cells();
3486
3487                 if new_events.is_empty() { return }
3488                 let mut events = self.pending_events.lock().unwrap();
3489                 events.append(&mut new_events);
3490         }
3491
3492         /// Free the background events, generally called from timer_tick_occurred.
3493         ///
3494         /// Exposed for testing to allow us to process events quickly without generating accidental
3495         /// BroadcastChannelUpdate events in timer_tick_occurred.
3496         ///
3497         /// Expects the caller to have a total_consistency_lock read lock.
3498         fn process_background_events(&self) -> bool {
3499                 let mut background_events = Vec::new();
3500                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
3501                 if background_events.is_empty() {
3502                         return false;
3503                 }
3504
3505                 for event in background_events.drain(..) {
3506                         match event {
3507                                 BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)) => {
3508                                         // The channel has already been closed, so no use bothering to care about the
3509                                         // monitor updating completing.
3510                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
3511                                 },
3512                         }
3513                 }
3514                 true
3515         }
3516
3517         #[cfg(any(test, feature = "_test_utils"))]
3518         /// Process background events, for functional testing
3519         pub fn test_process_background_events(&self) {
3520                 self.process_background_events();
3521         }
3522
3523         fn update_channel_fee(&self, chan_id: &[u8; 32], chan: &mut Channel<<SP::Target as SignerProvider>::Signer>, new_feerate: u32) -> NotifyOption {
3524                 if !chan.is_outbound() { return NotifyOption::SkipPersist; }
3525                 // If the feerate has decreased by less than half, don't bother
3526                 if new_feerate <= chan.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.get_feerate_sat_per_1000_weight() {
3527                         log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {}.",
3528                                 log_bytes!(chan_id[..]), chan.get_feerate_sat_per_1000_weight(), new_feerate);
3529                         return NotifyOption::SkipPersist;
3530                 }
3531                 if !chan.is_live() {
3532                         log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {} as it cannot currently be updated (probably the peer is disconnected).",
3533                                 log_bytes!(chan_id[..]), chan.get_feerate_sat_per_1000_weight(), new_feerate);
3534                         return NotifyOption::SkipPersist;
3535                 }
3536                 log_trace!(self.logger, "Channel {} qualifies for a feerate change from {} to {}.",
3537                         log_bytes!(chan_id[..]), chan.get_feerate_sat_per_1000_weight(), new_feerate);
3538
3539                 chan.queue_update_fee(new_feerate, &self.logger);
3540                 NotifyOption::DoPersist
3541         }
3542
3543         #[cfg(fuzzing)]
3544         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
3545         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
3546         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
3547         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
3548         pub fn maybe_update_chan_fees(&self) {
3549                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
3550                         let mut should_persist = NotifyOption::SkipPersist;
3551
3552                         let new_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
3553
3554                         let per_peer_state = self.per_peer_state.read().unwrap();
3555                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
3556                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3557                                 let peer_state = &mut *peer_state_lock;
3558                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut() {
3559                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
3560                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
3561                                 }
3562                         }
3563
3564                         should_persist
3565                 });
3566         }
3567
3568         /// Performs actions which should happen on startup and roughly once per minute thereafter.
3569         ///
3570         /// This currently includes:
3571         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
3572         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
3573         ///    than a minute, informing the network that they should no longer attempt to route over
3574         ///    the channel.
3575         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
3576         ///    with the current [`ChannelConfig`].
3577         ///  * Removing peers which have disconnected but and no longer have any channels.
3578         ///
3579         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
3580         /// estimate fetches.
3581         ///
3582         /// [`ChannelUpdate`]: msgs::ChannelUpdate
3583         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
3584         pub fn timer_tick_occurred(&self) {
3585                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
3586                         let mut should_persist = NotifyOption::SkipPersist;
3587                         if self.process_background_events() { should_persist = NotifyOption::DoPersist; }
3588
3589                         let new_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
3590
3591                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
3592                         let mut timed_out_mpp_htlcs = Vec::new();
3593                         let mut pending_peers_awaiting_removal = Vec::new();
3594                         {
3595                                 let per_peer_state = self.per_peer_state.read().unwrap();
3596                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
3597                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3598                                         let peer_state = &mut *peer_state_lock;
3599                                         let pending_msg_events = &mut peer_state.pending_msg_events;
3600                                         let counterparty_node_id = *counterparty_node_id;
3601                                         peer_state.channel_by_id.retain(|chan_id, chan| {
3602                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
3603                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
3604
3605                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
3606                                                         let (needs_close, err) = convert_chan_err!(self, e, chan, chan_id);
3607                                                         handle_errors.push((Err(err), counterparty_node_id));
3608                                                         if needs_close { return false; }
3609                                                 }
3610
3611                                                 match chan.channel_update_status() {
3612                                                         ChannelUpdateStatus::Enabled if !chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged),
3613                                                         ChannelUpdateStatus::Disabled if chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged),
3614                                                         ChannelUpdateStatus::DisabledStaged if chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
3615                                                         ChannelUpdateStatus::EnabledStaged if !chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
3616                                                         ChannelUpdateStatus::DisabledStaged if !chan.is_live() => {
3617                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
3618                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3619                                                                                 msg: update
3620                                                                         });
3621                                                                 }
3622                                                                 should_persist = NotifyOption::DoPersist;
3623                                                                 chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
3624                                                         },
3625                                                         ChannelUpdateStatus::EnabledStaged if chan.is_live() => {
3626                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
3627                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3628                                                                                 msg: update
3629                                                                         });
3630                                                                 }
3631                                                                 should_persist = NotifyOption::DoPersist;
3632                                                                 chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
3633                                                         },
3634                                                         _ => {},
3635                                                 }
3636
3637                                                 chan.maybe_expire_prev_config();
3638
3639                                                 true
3640                                         });
3641                                         if peer_state.ok_to_remove(true) {
3642                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
3643                                         }
3644                                 }
3645                         }
3646
3647                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
3648                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
3649                         // of to that peer is later closed while still being disconnected (i.e. force closed),
3650                         // we therefore need to remove the peer from `peer_state` separately.
3651                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
3652                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
3653                         // negative effects on parallelism as much as possible.
3654                         if pending_peers_awaiting_removal.len() > 0 {
3655                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
3656                                 for counterparty_node_id in pending_peers_awaiting_removal {
3657                                         match per_peer_state.entry(counterparty_node_id) {
3658                                                 hash_map::Entry::Occupied(entry) => {
3659                                                         // Remove the entry if the peer is still disconnected and we still
3660                                                         // have no channels to the peer.
3661                                                         let remove_entry = {
3662                                                                 let peer_state = entry.get().lock().unwrap();
3663                                                                 peer_state.ok_to_remove(true)
3664                                                         };
3665                                                         if remove_entry {
3666                                                                 entry.remove_entry();
3667                                                         }
3668                                                 },
3669                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
3670                                         }
3671                                 }
3672                         }
3673
3674                         self.claimable_payments.lock().unwrap().claimable_htlcs.retain(|payment_hash, (_, htlcs)| {
3675                                 if htlcs.is_empty() {
3676                                         // This should be unreachable
3677                                         debug_assert!(false);
3678                                         return false;
3679                                 }
3680                                 if let OnionPayload::Invoice { .. } = htlcs[0].onion_payload {
3681                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
3682                                         // In this case we're not going to handle any timeouts of the parts here.
3683                                         if htlcs[0].total_msat == htlcs.iter().fold(0, |total, htlc| total + htlc.value) {
3684                                                 return true;
3685                                         } else if htlcs.into_iter().any(|htlc| {
3686                                                 htlc.timer_ticks += 1;
3687                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
3688                                         }) {
3689                                                 timed_out_mpp_htlcs.extend(htlcs.drain(..).map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
3690                                                 return false;
3691                                         }
3692                                 }
3693                                 true
3694                         });
3695
3696                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
3697                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
3698                                 let reason = HTLCFailReason::from_failure_code(23);
3699                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
3700                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
3701                         }
3702
3703                         for (err, counterparty_node_id) in handle_errors.drain(..) {
3704                                 let _ = handle_error!(self, err, counterparty_node_id);
3705                         }
3706
3707                         self.pending_outbound_payments.remove_stale_resolved_payments(&self.pending_events);
3708
3709                         // Technically we don't need to do this here, but if we have holding cell entries in a
3710                         // channel that need freeing, it's better to do that here and block a background task
3711                         // than block the message queueing pipeline.
3712                         if self.check_free_holding_cells() {
3713                                 should_persist = NotifyOption::DoPersist;
3714                         }
3715
3716                         should_persist
3717                 });
3718         }
3719
3720         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
3721         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
3722         /// along the path (including in our own channel on which we received it).
3723         ///
3724         /// Note that in some cases around unclean shutdown, it is possible the payment may have
3725         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
3726         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
3727         /// may have already been failed automatically by LDK if it was nearing its expiration time.
3728         ///
3729         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
3730         /// [`ChannelManager::claim_funds`]), you should still monitor for
3731         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
3732         /// startup during which time claims that were in-progress at shutdown may be replayed.
3733         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
3734                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
3735         }
3736
3737         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
3738         /// reason for the failure.
3739         ///
3740         /// See [`FailureCode`] for valid failure codes.
3741         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
3742                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3743
3744                 let removed_source = self.claimable_payments.lock().unwrap().claimable_htlcs.remove(payment_hash);
3745                 if let Some((_, mut sources)) = removed_source {
3746                         for htlc in sources.drain(..) {
3747                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
3748                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
3749                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
3750                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
3751                         }
3752                 }
3753         }
3754
3755         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
3756         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
3757                 match failure_code {
3758                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code as u16),
3759                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code as u16),
3760                         FailureCode::IncorrectOrUnknownPaymentDetails => {
3761                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
3762                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
3763                                 HTLCFailReason::reason(failure_code as u16, htlc_msat_height_data)
3764                         }
3765                 }
3766         }
3767
3768         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
3769         /// that we want to return and a channel.
3770         ///
3771         /// This is for failures on the channel on which the HTLC was *received*, not failures
3772         /// forwarding
3773         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> (u16, Vec<u8>) {
3774                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
3775                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
3776                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
3777                 // an inbound SCID alias before the real SCID.
3778                 let scid_pref = if chan.should_announce() {
3779                         chan.get_short_channel_id().or(chan.latest_inbound_scid_alias())
3780                 } else {
3781                         chan.latest_inbound_scid_alias().or(chan.get_short_channel_id())
3782                 };
3783                 if let Some(scid) = scid_pref {
3784                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
3785                 } else {
3786                         (0x4000|10, Vec::new())
3787                 }
3788         }
3789
3790
3791         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
3792         /// that we want to return and a channel.
3793         fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> (u16, Vec<u8>) {
3794                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
3795                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
3796                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
3797                         if desired_err_code == 0x1000 | 20 {
3798                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
3799                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
3800                                 0u16.write(&mut enc).expect("Writes cannot fail");
3801                         }
3802                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
3803                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
3804                         upd.write(&mut enc).expect("Writes cannot fail");
3805                         (desired_err_code, enc.0)
3806                 } else {
3807                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
3808                         // which means we really shouldn't have gotten a payment to be forwarded over this
3809                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
3810                         // PERM|no_such_channel should be fine.
3811                         (0x4000|10, Vec::new())
3812                 }
3813         }
3814
3815         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
3816         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
3817         // be surfaced to the user.
3818         fn fail_holding_cell_htlcs(
3819                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: [u8; 32],
3820                 counterparty_node_id: &PublicKey
3821         ) {
3822                 let (failure_code, onion_failure_data) = {
3823                         let per_peer_state = self.per_peer_state.read().unwrap();
3824                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
3825                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3826                                 let peer_state = &mut *peer_state_lock;
3827                                 match peer_state.channel_by_id.entry(channel_id) {
3828                                         hash_map::Entry::Occupied(chan_entry) => {
3829                                                 self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan_entry.get())
3830                                         },
3831                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
3832                                 }
3833                         } else { (0x4000|10, Vec::new()) }
3834                 };
3835
3836                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
3837                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
3838                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
3839                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
3840                 }
3841         }
3842
3843         /// Fails an HTLC backwards to the sender of it to us.
3844         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
3845         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
3846                 // Ensure that no peer state channel storage lock is held when calling this function.
3847                 // This ensures that future code doesn't introduce a lock-order requirement for
3848                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
3849                 // this function with any `per_peer_state` peer lock acquired would.
3850                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
3851                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
3852                 }
3853
3854                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
3855                 //identify whether we sent it or not based on the (I presume) very different runtime
3856                 //between the branches here. We should make this async and move it into the forward HTLCs
3857                 //timer handling.
3858
3859                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3860                 // from block_connected which may run during initialization prior to the chain_monitor
3861                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
3862                 match source {
3863                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
3864                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
3865                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
3866                                         &self.pending_events, &self.logger)
3867                                 { self.push_pending_forwards_ev(); }
3868                         },
3869                         HTLCSource::PreviousHopData(HTLCPreviousHopData { ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret, ref phantom_shared_secret, ref outpoint }) => {
3870                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with {:?}", log_bytes!(payment_hash.0), onion_error);
3871                                 let err_packet = onion_error.get_encrypted_failure_packet(incoming_packet_shared_secret, phantom_shared_secret);
3872
3873                                 let mut push_forward_ev = false;
3874                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
3875                                 if forward_htlcs.is_empty() {
3876                                         push_forward_ev = true;
3877                                 }
3878                                 match forward_htlcs.entry(*short_channel_id) {
3879                                         hash_map::Entry::Occupied(mut entry) => {
3880                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet });
3881                                         },
3882                                         hash_map::Entry::Vacant(entry) => {
3883                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }));
3884                                         }
3885                                 }
3886                                 mem::drop(forward_htlcs);
3887                                 if push_forward_ev { self.push_pending_forwards_ev(); }
3888                                 let mut pending_events = self.pending_events.lock().unwrap();
3889                                 pending_events.push(events::Event::HTLCHandlingFailed {
3890                                         prev_channel_id: outpoint.to_channel_id(),
3891                                         failed_next_destination: destination,
3892                                 });
3893                         },
3894                 }
3895         }
3896
3897         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
3898         /// [`MessageSendEvent`]s needed to claim the payment.
3899         ///
3900         /// Note that calling this method does *not* guarantee that the payment has been claimed. You
3901         /// *must* wait for an [`Event::PaymentClaimed`] event which upon a successful claim will be
3902         /// provided to your [`EventHandler`] when [`process_pending_events`] is next called.
3903         ///
3904         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
3905         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
3906         /// event matches your expectation. If you fail to do so and call this method, you may provide
3907         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
3908         ///
3909         /// [`Event::PaymentClaimable`]: crate::util::events::Event::PaymentClaimable
3910         /// [`Event::PaymentClaimed`]: crate::util::events::Event::PaymentClaimed
3911         /// [`process_pending_events`]: EventsProvider::process_pending_events
3912         /// [`create_inbound_payment`]: Self::create_inbound_payment
3913         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
3914         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
3915                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
3916
3917                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3918
3919                 let mut sources = {
3920                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
3921                         if let Some((payment_purpose, sources)) = claimable_payments.claimable_htlcs.remove(&payment_hash) {
3922                                 let mut receiver_node_id = self.our_network_pubkey;
3923                                 for htlc in sources.iter() {
3924                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
3925                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
3926                                                         .expect("Failed to get node_id for phantom node recipient");
3927                                                 receiver_node_id = phantom_pubkey;
3928                                                 break;
3929                                         }
3930                                 }
3931
3932                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
3933                                         ClaimingPayment { amount_msat: sources.iter().map(|source| source.value).sum(),
3934                                         payment_purpose, receiver_node_id,
3935                                 });
3936                                 if dup_purpose.is_some() {
3937                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
3938                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
3939                                                 log_bytes!(payment_hash.0));
3940                                 }
3941                                 sources
3942                         } else { return; }
3943                 };
3944                 debug_assert!(!sources.is_empty());
3945
3946                 // If we are claiming an MPP payment, we check that all channels which contain a claimable
3947                 // HTLC still exist. While this isn't guaranteed to remain true if a channel closes while
3948                 // we're claiming (or even after we claim, before the commitment update dance completes),
3949                 // it should be a relatively rare race, and we'd rather not claim HTLCs that require us to
3950                 // go on-chain (and lose the on-chain fee to do so) than just reject the payment.
3951                 //
3952                 // Note that we'll still always get our funds - as long as the generated
3953                 // `ChannelMonitorUpdate` makes it out to the relevant monitor we can claim on-chain.
3954                 //
3955                 // If we find an HTLC which we would need to claim but for which we do not have a
3956                 // channel, we will fail all parts of the MPP payment. While we could wait and see if
3957                 // the sender retries the already-failed path(s), it should be a pretty rare case where
3958                 // we got all the HTLCs and then a channel closed while we were waiting for the user to
3959                 // provide the preimage, so worrying too much about the optimal handling isn't worth
3960                 // it.
3961                 let mut claimable_amt_msat = 0;
3962                 let mut expected_amt_msat = None;
3963                 let mut valid_mpp = true;
3964                 let mut errs = Vec::new();
3965                 let per_peer_state = self.per_peer_state.read().unwrap();
3966                 for htlc in sources.iter() {
3967                         let (counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&htlc.prev_hop.short_channel_id) {
3968                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3969                                 None => {
3970                                         valid_mpp = false;
3971                                         break;
3972                                 }
3973                         };
3974
3975                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
3976                         if peer_state_mutex_opt.is_none() {
3977                                 valid_mpp = false;
3978                                 break;
3979                         }
3980
3981                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3982                         let peer_state = &mut *peer_state_lock;
3983
3984                         if peer_state.channel_by_id.get(&chan_id).is_none() {
3985                                 valid_mpp = false;
3986                                 break;
3987                         }
3988
3989                         if expected_amt_msat.is_some() && expected_amt_msat != Some(htlc.total_msat) {
3990                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different total amounts - this should not be reachable!");
3991                                 debug_assert!(false);
3992                                 valid_mpp = false;
3993                                 break;
3994                         }
3995
3996                         expected_amt_msat = Some(htlc.total_msat);
3997                         if let OnionPayload::Spontaneous(_) = &htlc.onion_payload {
3998                                 // We don't currently support MPP for spontaneous payments, so just check
3999                                 // that there's one payment here and move on.
4000                                 if sources.len() != 1 {
4001                                         log_error!(self.logger, "Somehow ended up with an MPP spontaneous payment - this should not be reachable!");
4002                                         debug_assert!(false);
4003                                         valid_mpp = false;
4004                                         break;
4005                                 }
4006                         }
4007
4008                         claimable_amt_msat += htlc.value;
4009                 }
4010                 mem::drop(per_peer_state);
4011                 if sources.is_empty() || expected_amt_msat.is_none() {
4012                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4013                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
4014                         return;
4015                 }
4016                 if claimable_amt_msat != expected_amt_msat.unwrap() {
4017                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4018                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
4019                                 expected_amt_msat.unwrap(), claimable_amt_msat);
4020                         return;
4021                 }
4022                 if valid_mpp {
4023                         for htlc in sources.drain(..) {
4024                                 if let Err((pk, err)) = self.claim_funds_from_hop(
4025                                         htlc.prev_hop, payment_preimage,
4026                                         |_| Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash }))
4027                                 {
4028                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
4029                                                 // We got a temporary failure updating monitor, but will claim the
4030                                                 // HTLC when the monitor updating is restored (or on chain).
4031                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
4032                                         } else { errs.push((pk, err)); }
4033                                 }
4034                         }
4035                 }
4036                 if !valid_mpp {
4037                         for htlc in sources.drain(..) {
4038                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
4039                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
4040                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
4041                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
4042                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
4043                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
4044                         }
4045                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4046                 }
4047
4048                 // Now we can handle any errors which were generated.
4049                 for (counterparty_node_id, err) in errs.drain(..) {
4050                         let res: Result<(), _> = Err(err);
4051                         let _ = handle_error!(self, res, counterparty_node_id);
4052                 }
4053         }
4054
4055         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>) -> Option<MonitorUpdateCompletionAction>>(&self,
4056                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
4057         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
4058                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
4059
4060                 let per_peer_state = self.per_peer_state.read().unwrap();
4061                 let chan_id = prev_hop.outpoint.to_channel_id();
4062                 let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
4063                         Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
4064                         None => None
4065                 };
4066
4067                 let peer_state_opt = counterparty_node_id_opt.as_ref().map(
4068                         |counterparty_node_id| per_peer_state.get(counterparty_node_id).map(
4069                                 |peer_mutex| peer_mutex.lock().unwrap()
4070                         )
4071                 ).unwrap_or(None);
4072
4073                 if peer_state_opt.is_some() {
4074                         let mut peer_state_lock = peer_state_opt.unwrap();
4075                         let peer_state = &mut *peer_state_lock;
4076                         if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(chan_id) {
4077                                 let counterparty_node_id = chan.get().get_counterparty_node_id();
4078                                 let fulfill_res = chan.get_mut().get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger);
4079
4080                                 if let UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } = fulfill_res {
4081                                         if let Some(action) = completion_action(Some(htlc_value_msat)) {
4082                                                 log_trace!(self.logger, "Tracking monitor update completion action for channel {}: {:?}",
4083                                                         log_bytes!(chan_id), action);
4084                                                 peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
4085                                         }
4086                                         let update_id = monitor_update.update_id;
4087                                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, monitor_update);
4088                                         let res = handle_new_monitor_update!(self, update_res, update_id, peer_state_lock,
4089                                                 peer_state, per_peer_state, chan);
4090                                         if let Err(e) = res {
4091                                                 // TODO: This is a *critical* error - we probably updated the outbound edge
4092                                                 // of the HTLC's monitor with a preimage. We should retry this monitor
4093                                                 // update over and over again until morale improves.
4094                                                 log_error!(self.logger, "Failed to update channel monitor with preimage {:?}", payment_preimage);
4095                                                 return Err((counterparty_node_id, e));
4096                                         }
4097                                 }
4098                                 return Ok(());
4099                         }
4100                 }
4101                 let preimage_update = ChannelMonitorUpdate {
4102                         update_id: CLOSED_CHANNEL_UPDATE_ID,
4103                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
4104                                 payment_preimage,
4105                         }],
4106                 };
4107                 // We update the ChannelMonitor on the backward link, after
4108                 // receiving an `update_fulfill_htlc` from the forward link.
4109                 let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
4110                 if update_res != ChannelMonitorUpdateStatus::Completed {
4111                         // TODO: This needs to be handled somehow - if we receive a monitor update
4112                         // with a preimage we *must* somehow manage to propagate it to the upstream
4113                         // channel, or we must have an ability to receive the same event and try
4114                         // again on restart.
4115                         log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
4116                                 payment_preimage, update_res);
4117                 }
4118                 // Note that we do process the completion action here. This totally could be a
4119                 // duplicate claim, but we have no way of knowing without interrogating the
4120                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
4121                 // generally always allowed to be duplicative (and it's specifically noted in
4122                 // `PaymentForwarded`).
4123                 self.handle_monitor_update_completion_actions(completion_action(None));
4124                 Ok(())
4125         }
4126
4127         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
4128                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
4129         }
4130
4131         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage, forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, next_channel_id: [u8; 32]) {
4132                 match source {
4133                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
4134                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage, session_priv, path, from_onchain, &self.pending_events, &self.logger);
4135                         },
4136                         HTLCSource::PreviousHopData(hop_data) => {
4137                                 let prev_outpoint = hop_data.outpoint;
4138                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
4139                                         |htlc_claim_value_msat| {
4140                                                 if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
4141                                                         let fee_earned_msat = if let Some(claimed_htlc_value) = htlc_claim_value_msat {
4142                                                                 Some(claimed_htlc_value - forwarded_htlc_value)
4143                                                         } else { None };
4144
4145                                                         let prev_channel_id = Some(prev_outpoint.to_channel_id());
4146                                                         let next_channel_id = Some(next_channel_id);
4147
4148                                                         Some(MonitorUpdateCompletionAction::EmitEvent { event: events::Event::PaymentForwarded {
4149                                                                 fee_earned_msat,
4150                                                                 claim_from_onchain_tx: from_onchain,
4151                                                                 prev_channel_id,
4152                                                                 next_channel_id,
4153                                                         }})
4154                                                 } else { None }
4155                                         });
4156                                 if let Err((pk, err)) = res {
4157                                         let result: Result<(), _> = Err(err);
4158                                         let _ = handle_error!(self, result, pk);
4159                                 }
4160                         },
4161                 }
4162         }
4163
4164         /// Gets the node_id held by this ChannelManager
4165         pub fn get_our_node_id(&self) -> PublicKey {
4166                 self.our_network_pubkey.clone()
4167         }
4168
4169         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
4170                 for action in actions.into_iter() {
4171                         match action {
4172                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
4173                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4174                                         if let Some(ClaimingPayment { amount_msat, payment_purpose: purpose, receiver_node_id }) = payment {
4175                                                 self.pending_events.lock().unwrap().push(events::Event::PaymentClaimed {
4176                                                         payment_hash, purpose, amount_msat, receiver_node_id: Some(receiver_node_id),
4177                                                 });
4178                                         }
4179                                 },
4180                                 MonitorUpdateCompletionAction::EmitEvent { event } => {
4181                                         self.pending_events.lock().unwrap().push(event);
4182                                 },
4183                         }
4184                 }
4185         }
4186
4187         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
4188         /// update completion.
4189         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
4190                 channel: &mut Channel<<SP::Target as SignerProvider>::Signer>, raa: Option<msgs::RevokeAndACK>,
4191                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
4192                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
4193                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
4194         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
4195                 log_trace!(self.logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
4196                         log_bytes!(channel.channel_id()),
4197                         if raa.is_some() { "an" } else { "no" },
4198                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
4199                         if funding_broadcastable.is_some() { "" } else { "not " },
4200                         if channel_ready.is_some() { "sending" } else { "without" },
4201                         if announcement_sigs.is_some() { "sending" } else { "without" });
4202
4203                 let mut htlc_forwards = None;
4204
4205                 let counterparty_node_id = channel.get_counterparty_node_id();
4206                 if !pending_forwards.is_empty() {
4207                         htlc_forwards = Some((channel.get_short_channel_id().unwrap_or(channel.outbound_scid_alias()),
4208                                 channel.get_funding_txo().unwrap(), channel.get_user_id(), pending_forwards));
4209                 }
4210
4211                 if let Some(msg) = channel_ready {
4212                         send_channel_ready!(self, pending_msg_events, channel, msg);
4213                 }
4214                 if let Some(msg) = announcement_sigs {
4215                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
4216                                 node_id: counterparty_node_id,
4217                                 msg,
4218                         });
4219                 }
4220
4221                 emit_channel_ready_event!(self, channel);
4222
4223                 macro_rules! handle_cs { () => {
4224                         if let Some(update) = commitment_update {
4225                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
4226                                         node_id: counterparty_node_id,
4227                                         updates: update,
4228                                 });
4229                         }
4230                 } }
4231                 macro_rules! handle_raa { () => {
4232                         if let Some(revoke_and_ack) = raa {
4233                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
4234                                         node_id: counterparty_node_id,
4235                                         msg: revoke_and_ack,
4236                                 });
4237                         }
4238                 } }
4239                 match order {
4240                         RAACommitmentOrder::CommitmentFirst => {
4241                                 handle_cs!();
4242                                 handle_raa!();
4243                         },
4244                         RAACommitmentOrder::RevokeAndACKFirst => {
4245                                 handle_raa!();
4246                                 handle_cs!();
4247                         },
4248                 }
4249
4250                 if let Some(tx) = funding_broadcastable {
4251                         log_info!(self.logger, "Broadcasting funding transaction with txid {}", tx.txid());
4252                         self.tx_broadcaster.broadcast_transaction(&tx);
4253                 }
4254
4255                 htlc_forwards
4256         }
4257
4258         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
4259                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
4260
4261                 let counterparty_node_id = match counterparty_node_id {
4262                         Some(cp_id) => cp_id.clone(),
4263                         None => {
4264                                 // TODO: Once we can rely on the counterparty_node_id from the
4265                                 // monitor event, this and the id_to_peer map should be removed.
4266                                 let id_to_peer = self.id_to_peer.lock().unwrap();
4267                                 match id_to_peer.get(&funding_txo.to_channel_id()) {
4268                                         Some(cp_id) => cp_id.clone(),
4269                                         None => return,
4270                                 }
4271                         }
4272                 };
4273                 let per_peer_state = self.per_peer_state.read().unwrap();
4274                 let mut peer_state_lock;
4275                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
4276                 if peer_state_mutex_opt.is_none() { return }
4277                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4278                 let peer_state = &mut *peer_state_lock;
4279                 let mut channel = {
4280                         match peer_state.channel_by_id.entry(funding_txo.to_channel_id()){
4281                                 hash_map::Entry::Occupied(chan) => chan,
4282                                 hash_map::Entry::Vacant(_) => return,
4283                         }
4284                 };
4285                 log_trace!(self.logger, "ChannelMonitor updated to {}. Current highest is {}",
4286                         highest_applied_update_id, channel.get().get_latest_monitor_update_id());
4287                 if !channel.get().is_awaiting_monitor_update() || channel.get().get_latest_monitor_update_id() != highest_applied_update_id {
4288                         return;
4289                 }
4290                 handle_monitor_update_completion!(self, highest_applied_update_id, peer_state_lock, peer_state, per_peer_state, channel.get_mut());
4291         }
4292
4293         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
4294         ///
4295         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
4296         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
4297         /// the channel.
4298         ///
4299         /// The `user_channel_id` parameter will be provided back in
4300         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
4301         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
4302         ///
4303         /// Note that this method will return an error and reject the channel, if it requires support
4304         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
4305         /// used to accept such channels.
4306         ///
4307         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
4308         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
4309         pub fn accept_inbound_channel(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
4310                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
4311         }
4312
4313         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
4314         /// it as confirmed immediately.
4315         ///
4316         /// The `user_channel_id` parameter will be provided back in
4317         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
4318         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
4319         ///
4320         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
4321         /// and (if the counterparty agrees), enables forwarding of payments immediately.
4322         ///
4323         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
4324         /// transaction and blindly assumes that it will eventually confirm.
4325         ///
4326         /// If it does not confirm before we decide to close the channel, or if the funding transaction
4327         /// does not pay to the correct script the correct amount, *you will lose funds*.
4328         ///
4329         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
4330         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
4331         pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
4332                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
4333         }
4334
4335         fn do_accept_inbound_channel(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
4336                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4337
4338                 let peers_without_funded_channels = self.peers_without_funded_channels(|peer| !peer.channel_by_id.is_empty());
4339                 let per_peer_state = self.per_peer_state.read().unwrap();
4340                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4341                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
4342                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4343                 let peer_state = &mut *peer_state_lock;
4344                 let is_only_peer_channel = peer_state.channel_by_id.len() == 1;
4345                 match peer_state.channel_by_id.entry(temporary_channel_id.clone()) {
4346                         hash_map::Entry::Occupied(mut channel) => {
4347                                 if !channel.get().inbound_is_awaiting_accept() {
4348                                         return Err(APIError::APIMisuseError { err: "The channel isn't currently awaiting to be accepted.".to_owned() });
4349                                 }
4350                                 if accept_0conf {
4351                                         channel.get_mut().set_0conf();
4352                                 } else if channel.get().get_channel_type().requires_zero_conf() {
4353                                         let send_msg_err_event = events::MessageSendEvent::HandleError {
4354                                                 node_id: channel.get().get_counterparty_node_id(),
4355                                                 action: msgs::ErrorAction::SendErrorMessage{
4356                                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
4357                                                 }
4358                                         };
4359                                         peer_state.pending_msg_events.push(send_msg_err_event);
4360                                         let _ = remove_channel!(self, channel);
4361                                         return Err(APIError::APIMisuseError { err: "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned() });
4362                                 } else {
4363                                         // If this peer already has some channels, a new channel won't increase our number of peers
4364                                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
4365                                         // channels per-peer we can accept channels from a peer with existing ones.
4366                                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
4367                                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
4368                                                         node_id: channel.get().get_counterparty_node_id(),
4369                                                         action: msgs::ErrorAction::SendErrorMessage{
4370                                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
4371                                                         }
4372                                                 };
4373                                                 peer_state.pending_msg_events.push(send_msg_err_event);
4374                                                 let _ = remove_channel!(self, channel);
4375                                                 return Err(APIError::APIMisuseError { err: "Too many peers with unfunded channels, refusing to accept new ones".to_owned() });
4376                                         }
4377                                 }
4378
4379                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
4380                                         node_id: channel.get().get_counterparty_node_id(),
4381                                         msg: channel.get_mut().accept_inbound_channel(user_channel_id),
4382                                 });
4383                         }
4384                         hash_map::Entry::Vacant(_) => {
4385                                 return Err(APIError::ChannelUnavailable { err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(*temporary_channel_id), counterparty_node_id) });
4386                         }
4387                 }
4388                 Ok(())
4389         }
4390
4391         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
4392         /// or 0-conf channels.
4393         ///
4394         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
4395         /// non-0-conf channels we have with the peer.
4396         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
4397         where Filter: Fn(&PeerState<<SP::Target as SignerProvider>::Signer>) -> bool {
4398                 let mut peers_without_funded_channels = 0;
4399                 let best_block_height = self.best_block.read().unwrap().height();
4400                 {
4401                         let peer_state_lock = self.per_peer_state.read().unwrap();
4402                         for (_, peer_mtx) in peer_state_lock.iter() {
4403                                 let peer = peer_mtx.lock().unwrap();
4404                                 if !maybe_count_peer(&*peer) { continue; }
4405                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
4406                                 if num_unfunded_channels == peer.channel_by_id.len() {
4407                                         peers_without_funded_channels += 1;
4408                                 }
4409                         }
4410                 }
4411                 return peers_without_funded_channels;
4412         }
4413
4414         fn unfunded_channel_count(
4415                 peer: &PeerState<<SP::Target as SignerProvider>::Signer>, best_block_height: u32
4416         ) -> usize {
4417                 let mut num_unfunded_channels = 0;
4418                 for (_, chan) in peer.channel_by_id.iter() {
4419                         if !chan.is_outbound() && chan.minimum_depth().unwrap_or(1) != 0 &&
4420                                 chan.get_funding_tx_confirmations(best_block_height) == 0
4421                         {
4422                                 num_unfunded_channels += 1;
4423                         }
4424                 }
4425                 num_unfunded_channels
4426         }
4427
4428         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
4429                 if msg.chain_hash != self.genesis_hash {
4430                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
4431                 }
4432
4433                 if !self.default_configuration.accept_inbound_channels {
4434                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
4435                 }
4436
4437                 let mut random_bytes = [0u8; 16];
4438                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
4439                 let user_channel_id = u128::from_be_bytes(random_bytes);
4440                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
4441
4442                 // Get the number of peers with channels, but without funded ones. We don't care too much
4443                 // about peers that never open a channel, so we filter by peers that have at least one
4444                 // channel, and then limit the number of those with unfunded channels.
4445                 let channeled_peers_without_funding = self.peers_without_funded_channels(|node| !node.channel_by_id.is_empty());
4446
4447                 let per_peer_state = self.per_peer_state.read().unwrap();
4448                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4449                     .ok_or_else(|| {
4450                                 debug_assert!(false);
4451                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.temporary_channel_id.clone())
4452                         })?;
4453                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4454                 let peer_state = &mut *peer_state_lock;
4455
4456                 // If this peer already has some channels, a new channel won't increase our number of peers
4457                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
4458                 // channels per-peer we can accept channels from a peer with existing ones.
4459                 if peer_state.channel_by_id.is_empty() &&
4460                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
4461                         !self.default_configuration.manually_accept_inbound_channels
4462                 {
4463                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
4464                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
4465                                 msg.temporary_channel_id.clone()));
4466                 }
4467
4468                 let best_block_height = self.best_block.read().unwrap().height();
4469                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
4470                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
4471                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
4472                                 msg.temporary_channel_id.clone()));
4473                 }
4474
4475                 let mut channel = match Channel::new_from_req(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
4476                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
4477                         &self.default_configuration, best_block_height, &self.logger, outbound_scid_alias)
4478                 {
4479                         Err(e) => {
4480                                 self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
4481                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
4482                         },
4483                         Ok(res) => res
4484                 };
4485                 match peer_state.channel_by_id.entry(channel.channel_id()) {
4486                         hash_map::Entry::Occupied(_) => {
4487                                 self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
4488                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()))
4489                         },
4490                         hash_map::Entry::Vacant(entry) => {
4491                                 if !self.default_configuration.manually_accept_inbound_channels {
4492                                         if channel.get_channel_type().requires_zero_conf() {
4493                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
4494                                         }
4495                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
4496                                                 node_id: counterparty_node_id.clone(),
4497                                                 msg: channel.accept_inbound_channel(user_channel_id),
4498                                         });
4499                                 } else {
4500                                         let mut pending_events = self.pending_events.lock().unwrap();
4501                                         pending_events.push(
4502                                                 events::Event::OpenChannelRequest {
4503                                                         temporary_channel_id: msg.temporary_channel_id.clone(),
4504                                                         counterparty_node_id: counterparty_node_id.clone(),
4505                                                         funding_satoshis: msg.funding_satoshis,
4506                                                         push_msat: msg.push_msat,
4507                                                         channel_type: channel.get_channel_type().clone(),
4508                                                 }
4509                                         );
4510                                 }
4511
4512                                 entry.insert(channel);
4513                         }
4514                 }
4515                 Ok(())
4516         }
4517
4518         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
4519                 let (value, output_script, user_id) = {
4520                         let per_peer_state = self.per_peer_state.read().unwrap();
4521                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4522                                 .ok_or_else(|| {
4523                                         debug_assert!(false);
4524                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.temporary_channel_id)
4525                                 })?;
4526                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4527                         let peer_state = &mut *peer_state_lock;
4528                         match peer_state.channel_by_id.entry(msg.temporary_channel_id) {
4529                                 hash_map::Entry::Occupied(mut chan) => {
4530                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), chan);
4531                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
4532                                 },
4533                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.temporary_channel_id))
4534                         }
4535                 };
4536                 let mut pending_events = self.pending_events.lock().unwrap();
4537                 pending_events.push(events::Event::FundingGenerationReady {
4538                         temporary_channel_id: msg.temporary_channel_id,
4539                         counterparty_node_id: *counterparty_node_id,
4540                         channel_value_satoshis: value,
4541                         output_script,
4542                         user_channel_id: user_id,
4543                 });
4544                 Ok(())
4545         }
4546
4547         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
4548                 let best_block = *self.best_block.read().unwrap();
4549
4550                 let per_peer_state = self.per_peer_state.read().unwrap();
4551                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4552                         .ok_or_else(|| {
4553                                 debug_assert!(false);
4554                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.temporary_channel_id)
4555                         })?;
4556
4557                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4558                 let peer_state = &mut *peer_state_lock;
4559                 let ((funding_msg, monitor), chan) =
4560                         match peer_state.channel_by_id.entry(msg.temporary_channel_id) {
4561                                 hash_map::Entry::Occupied(mut chan) => {
4562                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg, best_block, &self.signer_provider, &self.logger), chan), chan.remove())
4563                                 },
4564                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.temporary_channel_id))
4565                         };
4566
4567                 match peer_state.channel_by_id.entry(funding_msg.channel_id) {
4568                         hash_map::Entry::Occupied(_) => {
4569                                 Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
4570                         },
4571                         hash_map::Entry::Vacant(e) => {
4572                                 match self.id_to_peer.lock().unwrap().entry(chan.channel_id()) {
4573                                         hash_map::Entry::Occupied(_) => {
4574                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(
4575                                                         "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
4576                                                         funding_msg.channel_id))
4577                                         },
4578                                         hash_map::Entry::Vacant(i_e) => {
4579                                                 i_e.insert(chan.get_counterparty_node_id());
4580                                         }
4581                                 }
4582
4583                                 // There's no problem signing a counterparty's funding transaction if our monitor
4584                                 // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
4585                                 // accepted payment from yet. We do, however, need to wait to send our channel_ready
4586                                 // until we have persisted our monitor.
4587                                 let new_channel_id = funding_msg.channel_id;
4588                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
4589                                         node_id: counterparty_node_id.clone(),
4590                                         msg: funding_msg,
4591                                 });
4592
4593                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
4594
4595                                 let chan = e.insert(chan);
4596                                 let mut res = handle_new_monitor_update!(self, monitor_res, 0, peer_state_lock, peer_state,
4597                                         per_peer_state, chan, MANUALLY_REMOVING, { peer_state.channel_by_id.remove(&new_channel_id) });
4598
4599                                 // Note that we reply with the new channel_id in error messages if we gave up on the
4600                                 // channel, not the temporary_channel_id. This is compatible with ourselves, but the
4601                                 // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
4602                                 // any messages referencing a previously-closed channel anyway.
4603                                 // We do not propagate the monitor update to the user as it would be for a monitor
4604                                 // that we didn't manage to store (and that we don't care about - we don't respond
4605                                 // with the funding_signed so the channel can never go on chain).
4606                                 if let Err(MsgHandleErrInternal { shutdown_finish: Some((res, _)), .. }) = &mut res {
4607                                         res.0 = None;
4608                                 }
4609                                 res
4610                         }
4611                 }
4612         }
4613
4614         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
4615                 let best_block = *self.best_block.read().unwrap();
4616                 let per_peer_state = self.per_peer_state.read().unwrap();
4617                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4618                         .ok_or_else(|| {
4619                                 debug_assert!(false);
4620                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
4621                         })?;
4622
4623                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4624                 let peer_state = &mut *peer_state_lock;
4625                 match peer_state.channel_by_id.entry(msg.channel_id) {
4626                         hash_map::Entry::Occupied(mut chan) => {
4627                                 let monitor = try_chan_entry!(self,
4628                                         chan.get_mut().funding_signed(&msg, best_block, &self.signer_provider, &self.logger), chan);
4629                                 let update_res = self.chain_monitor.watch_channel(chan.get().get_funding_txo().unwrap(), monitor);
4630                                 let mut res = handle_new_monitor_update!(self, update_res, 0, peer_state_lock, peer_state, per_peer_state, chan);
4631                                 if let Err(MsgHandleErrInternal { ref mut shutdown_finish, .. }) = res {
4632                                         // We weren't able to watch the channel to begin with, so no updates should be made on
4633                                         // it. Previously, full_stack_target found an (unreachable) panic when the
4634                                         // monitor update contained within `shutdown_finish` was applied.
4635                                         if let Some((ref mut shutdown_finish, _)) = shutdown_finish {
4636                                                 shutdown_finish.0.take();
4637                                         }
4638                                 }
4639                                 res
4640                         },
4641                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
4642                 }
4643         }
4644
4645         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
4646                 let per_peer_state = self.per_peer_state.read().unwrap();
4647                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4648                         .ok_or_else(|| {
4649                                 debug_assert!(false);
4650                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
4651                         })?;
4652                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4653                 let peer_state = &mut *peer_state_lock;
4654                 match peer_state.channel_by_id.entry(msg.channel_id) {
4655                         hash_map::Entry::Occupied(mut chan) => {
4656                                 let announcement_sigs_opt = try_chan_entry!(self, chan.get_mut().channel_ready(&msg, &self.node_signer,
4657                                         self.genesis_hash.clone(), &self.default_configuration, &self.best_block.read().unwrap(), &self.logger), chan);
4658                                 if let Some(announcement_sigs) = announcement_sigs_opt {
4659                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", log_bytes!(chan.get().channel_id()));
4660                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
4661                                                 node_id: counterparty_node_id.clone(),
4662                                                 msg: announcement_sigs,
4663                                         });
4664                                 } else if chan.get().is_usable() {
4665                                         // If we're sending an announcement_signatures, we'll send the (public)
4666                                         // channel_update after sending a channel_announcement when we receive our
4667                                         // counterparty's announcement_signatures. Thus, we only bother to send a
4668                                         // channel_update here if the channel is not public, i.e. we're not sending an
4669                                         // announcement_signatures.
4670                                         log_trace!(self.logger, "Sending private initial channel_update for our counterparty on channel {}", log_bytes!(chan.get().channel_id()));
4671                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan.get()) {
4672                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
4673                                                         node_id: counterparty_node_id.clone(),
4674                                                         msg,
4675                                                 });
4676                                         }
4677                                 }
4678
4679                                 emit_channel_ready_event!(self, chan.get_mut());
4680
4681                                 Ok(())
4682                         },
4683                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
4684                 }
4685         }
4686
4687         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
4688                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)>;
4689                 let result: Result<(), _> = loop {
4690                         let per_peer_state = self.per_peer_state.read().unwrap();
4691                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4692                                 .ok_or_else(|| {
4693                                         debug_assert!(false);
4694                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
4695                                 })?;
4696                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4697                         let peer_state = &mut *peer_state_lock;
4698                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
4699                                 hash_map::Entry::Occupied(mut chan_entry) => {
4700
4701                                         if !chan_entry.get().received_shutdown() {
4702                                                 log_info!(self.logger, "Received a shutdown message from our counterparty for channel {}{}.",
4703                                                         log_bytes!(msg.channel_id),
4704                                                         if chan_entry.get().sent_shutdown() { " after we initiated shutdown" } else { "" });
4705                                         }
4706
4707                                         let funding_txo_opt = chan_entry.get().get_funding_txo();
4708                                         let (shutdown, monitor_update_opt, htlcs) = try_chan_entry!(self,
4709                                                 chan_entry.get_mut().shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_entry);
4710                                         dropped_htlcs = htlcs;
4711
4712                                         if let Some(msg) = shutdown {
4713                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
4714                                                 // here as we don't need the monitor update to complete until we send a
4715                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
4716                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
4717                                                         node_id: *counterparty_node_id,
4718                                                         msg,
4719                                                 });
4720                                         }
4721
4722                                         // Update the monitor with the shutdown script if necessary.
4723                                         if let Some(monitor_update) = monitor_update_opt {
4724                                                 let update_id = monitor_update.update_id;
4725                                                 let update_res = self.chain_monitor.update_channel(funding_txo_opt.unwrap(), monitor_update);
4726                                                 break handle_new_monitor_update!(self, update_res, update_id, peer_state_lock, peer_state, per_peer_state, chan_entry);
4727                                         }
4728                                         break Ok(());
4729                                 },
4730                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
4731                         }
4732                 };
4733                 for htlc_source in dropped_htlcs.drain(..) {
4734                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
4735                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
4736                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
4737                 }
4738
4739                 result
4740         }
4741
4742         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
4743                 let per_peer_state = self.per_peer_state.read().unwrap();
4744                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4745                         .ok_or_else(|| {
4746                                 debug_assert!(false);
4747                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
4748                         })?;
4749                 let (tx, chan_option) = {
4750                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4751                         let peer_state = &mut *peer_state_lock;
4752                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
4753                                 hash_map::Entry::Occupied(mut chan_entry) => {
4754                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&self.fee_estimator, &msg), chan_entry);
4755                                         if let Some(msg) = closing_signed {
4756                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
4757                                                         node_id: counterparty_node_id.clone(),
4758                                                         msg,
4759                                                 });
4760                                         }
4761                                         if tx.is_some() {
4762                                                 // We're done with this channel, we've got a signed closing transaction and
4763                                                 // will send the closing_signed back to the remote peer upon return. This
4764                                                 // also implies there are no pending HTLCs left on the channel, so we can
4765                                                 // fully delete it from tracking (the channel monitor is still around to
4766                                                 // watch for old state broadcasts)!
4767                                                 (tx, Some(remove_channel!(self, chan_entry)))
4768                                         } else { (tx, None) }
4769                                 },
4770                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
4771                         }
4772                 };
4773                 if let Some(broadcast_tx) = tx {
4774                         log_info!(self.logger, "Broadcasting {}", log_tx!(broadcast_tx));
4775                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
4776                 }
4777                 if let Some(chan) = chan_option {
4778                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4779                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4780                                 let peer_state = &mut *peer_state_lock;
4781                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4782                                         msg: update
4783                                 });
4784                         }
4785                         self.issue_channel_close_events(&chan, ClosureReason::CooperativeClosure);
4786                 }
4787                 Ok(())
4788         }
4789
4790         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
4791                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
4792                 //determine the state of the payment based on our response/if we forward anything/the time
4793                 //we take to respond. We should take care to avoid allowing such an attack.
4794                 //
4795                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
4796                 //us repeatedly garbled in different ways, and compare our error messages, which are
4797                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
4798                 //but we should prevent it anyway.
4799
4800                 let pending_forward_info = self.decode_update_add_htlc_onion(msg);
4801                 let per_peer_state = self.per_peer_state.read().unwrap();
4802                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4803                         .ok_or_else(|| {
4804                                 debug_assert!(false);
4805                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
4806                         })?;
4807                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4808                 let peer_state = &mut *peer_state_lock;
4809                 match peer_state.channel_by_id.entry(msg.channel_id) {
4810                         hash_map::Entry::Occupied(mut chan) => {
4811
4812                                 let create_pending_htlc_status = |chan: &Channel<<SP::Target as SignerProvider>::Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
4813                                         // If the update_add is completely bogus, the call will Err and we will close,
4814                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
4815                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
4816                                         match pending_forward_info {
4817                                                 PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
4818                                                         let reason = if (error_code & 0x1000) != 0 {
4819                                                                 let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
4820                                                                 HTLCFailReason::reason(real_code, error_data)
4821                                                         } else {
4822                                                                 HTLCFailReason::from_failure_code(error_code)
4823                                                         }.get_encrypted_failure_packet(incoming_shared_secret, &None);
4824                                                         let msg = msgs::UpdateFailHTLC {
4825                                                                 channel_id: msg.channel_id,
4826                                                                 htlc_id: msg.htlc_id,
4827                                                                 reason
4828                                                         };
4829                                                         PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
4830                                                 },
4831                                                 _ => pending_forward_info
4832                                         }
4833                                 };
4834                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.logger), chan);
4835                         },
4836                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
4837                 }
4838                 Ok(())
4839         }
4840
4841         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
4842                 let (htlc_source, forwarded_htlc_value) = {
4843                         let per_peer_state = self.per_peer_state.read().unwrap();
4844                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4845                                 .ok_or_else(|| {
4846                                         debug_assert!(false);
4847                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
4848                                 })?;
4849                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4850                         let peer_state = &mut *peer_state_lock;
4851                         match peer_state.channel_by_id.entry(msg.channel_id) {
4852                                 hash_map::Entry::Occupied(mut chan) => {
4853                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), chan)
4854                                 },
4855                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
4856                         }
4857                 };
4858                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, msg.channel_id);
4859                 Ok(())
4860         }
4861
4862         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
4863                 let per_peer_state = self.per_peer_state.read().unwrap();
4864                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4865                         .ok_or_else(|| {
4866                                 debug_assert!(false);
4867                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
4868                         })?;
4869                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4870                 let peer_state = &mut *peer_state_lock;
4871                 match peer_state.channel_by_id.entry(msg.channel_id) {
4872                         hash_map::Entry::Occupied(mut chan) => {
4873                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan);
4874                         },
4875                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
4876                 }
4877                 Ok(())
4878         }
4879
4880         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
4881                 let per_peer_state = self.per_peer_state.read().unwrap();
4882                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4883                         .ok_or_else(|| {
4884                                 debug_assert!(false);
4885                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
4886                         })?;
4887                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4888                 let peer_state = &mut *peer_state_lock;
4889                 match peer_state.channel_by_id.entry(msg.channel_id) {
4890                         hash_map::Entry::Occupied(mut chan) => {
4891                                 if (msg.failure_code & 0x8000) == 0 {
4892                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
4893                                         try_chan_entry!(self, Err(chan_err), chan);
4894                                 }
4895                                 try_chan_entry!(self, chan.get_mut().update_fail_malformed_htlc(&msg, HTLCFailReason::reason(msg.failure_code, msg.sha256_of_onion.to_vec())), chan);
4896                                 Ok(())
4897                         },
4898                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
4899                 }
4900         }
4901
4902         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
4903                 let per_peer_state = self.per_peer_state.read().unwrap();
4904                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4905                         .ok_or_else(|| {
4906                                 debug_assert!(false);
4907                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
4908                         })?;
4909                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4910                 let peer_state = &mut *peer_state_lock;
4911                 match peer_state.channel_by_id.entry(msg.channel_id) {
4912                         hash_map::Entry::Occupied(mut chan) => {
4913                                 let funding_txo = chan.get().get_funding_txo();
4914                                 let monitor_update = try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &self.logger), chan);
4915                                 let update_res = self.chain_monitor.update_channel(funding_txo.unwrap(), monitor_update);
4916                                 let update_id = monitor_update.update_id;
4917                                 handle_new_monitor_update!(self, update_res, update_id, peer_state_lock,
4918                                         peer_state, per_peer_state, chan)
4919                         },
4920                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
4921                 }
4922         }
4923
4924         #[inline]
4925         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
4926                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
4927                         let mut push_forward_event = false;
4928                         let mut new_intercept_events = Vec::new();
4929                         let mut failed_intercept_forwards = Vec::new();
4930                         if !pending_forwards.is_empty() {
4931                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
4932                                         let scid = match forward_info.routing {
4933                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
4934                                                 PendingHTLCRouting::Receive { .. } => 0,
4935                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
4936                                         };
4937                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
4938                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
4939
4940                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
4941                                         let forward_htlcs_empty = forward_htlcs.is_empty();
4942                                         match forward_htlcs.entry(scid) {
4943                                                 hash_map::Entry::Occupied(mut entry) => {
4944                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4945                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
4946                                                 },
4947                                                 hash_map::Entry::Vacant(entry) => {
4948                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
4949                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.genesis_hash)
4950                                                         {
4951                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).into_inner());
4952                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
4953                                                                 match pending_intercepts.entry(intercept_id) {
4954                                                                         hash_map::Entry::Vacant(entry) => {
4955                                                                                 new_intercept_events.push(events::Event::HTLCIntercepted {
4956                                                                                         requested_next_hop_scid: scid,
4957                                                                                         payment_hash: forward_info.payment_hash,
4958                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
4959                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
4960                                                                                         intercept_id
4961                                                                                 });
4962                                                                                 entry.insert(PendingAddHTLCInfo {
4963                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
4964                                                                         },
4965                                                                         hash_map::Entry::Occupied(_) => {
4966                                                                                 log_info!(self.logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
4967                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4968                                                                                         short_channel_id: prev_short_channel_id,
4969                                                                                         outpoint: prev_funding_outpoint,
4970                                                                                         htlc_id: prev_htlc_id,
4971                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
4972                                                                                         phantom_shared_secret: None,
4973                                                                                 });
4974
4975                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
4976                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
4977                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
4978                                                                                 ));
4979                                                                         }
4980                                                                 }
4981                                                         } else {
4982                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
4983                                                                 // payments are being processed.
4984                                                                 if forward_htlcs_empty {
4985                                                                         push_forward_event = true;
4986                                                                 }
4987                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4988                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
4989                                                         }
4990                                                 }
4991                                         }
4992                                 }
4993                         }
4994
4995                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
4996                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4997                         }
4998
4999                         if !new_intercept_events.is_empty() {
5000                                 let mut events = self.pending_events.lock().unwrap();
5001                                 events.append(&mut new_intercept_events);
5002                         }
5003                         if push_forward_event { self.push_pending_forwards_ev() }
5004                 }
5005         }
5006
5007         // We only want to push a PendingHTLCsForwardable event if no others are queued.
5008         fn push_pending_forwards_ev(&self) {
5009                 let mut pending_events = self.pending_events.lock().unwrap();
5010                 let forward_ev_exists = pending_events.iter()
5011                         .find(|ev| if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false })
5012                         .is_some();
5013                 if !forward_ev_exists {
5014                         pending_events.push(events::Event::PendingHTLCsForwardable {
5015                                 time_forwardable:
5016                                         Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
5017                         });
5018                 }
5019         }
5020
5021         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
5022                 let (htlcs_to_fail, res) = {
5023                         let per_peer_state = self.per_peer_state.read().unwrap();
5024                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
5025                                 .ok_or_else(|| {
5026                                         debug_assert!(false);
5027                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5028                                 }).map(|mtx| mtx.lock().unwrap())?;
5029                         let peer_state = &mut *peer_state_lock;
5030                         match peer_state.channel_by_id.entry(msg.channel_id) {
5031                                 hash_map::Entry::Occupied(mut chan) => {
5032                                         let funding_txo = chan.get().get_funding_txo();
5033                                         let (htlcs_to_fail, monitor_update) = try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &self.logger), chan);
5034                                         let update_res = self.chain_monitor.update_channel(funding_txo.unwrap(), monitor_update);
5035                                         let update_id = monitor_update.update_id;
5036                                         let res = handle_new_monitor_update!(self, update_res, update_id,
5037                                                 peer_state_lock, peer_state, per_peer_state, chan);
5038                                         (htlcs_to_fail, res)
5039                                 },
5040                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
5041                         }
5042                 };
5043                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
5044                 res
5045         }
5046
5047         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
5048                 let per_peer_state = self.per_peer_state.read().unwrap();
5049                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5050                         .ok_or_else(|| {
5051                                 debug_assert!(false);
5052                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5053                         })?;
5054                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5055                 let peer_state = &mut *peer_state_lock;
5056                 match peer_state.channel_by_id.entry(msg.channel_id) {
5057                         hash_map::Entry::Occupied(mut chan) => {
5058                                 try_chan_entry!(self, chan.get_mut().update_fee(&self.fee_estimator, &msg, &self.logger), chan);
5059                         },
5060                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
5061                 }
5062                 Ok(())
5063         }
5064
5065         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
5066                 let per_peer_state = self.per_peer_state.read().unwrap();
5067                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5068                         .ok_or_else(|| {
5069                                 debug_assert!(false);
5070                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5071                         })?;
5072                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5073                 let peer_state = &mut *peer_state_lock;
5074                 match peer_state.channel_by_id.entry(msg.channel_id) {
5075                         hash_map::Entry::Occupied(mut chan) => {
5076                                 if !chan.get().is_usable() {
5077                                         return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
5078                                 }
5079
5080                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
5081                                         msg: try_chan_entry!(self, chan.get_mut().announcement_signatures(
5082                                                 &self.node_signer, self.genesis_hash.clone(), self.best_block.read().unwrap().height(),
5083                                                 msg, &self.default_configuration
5084                                         ), chan),
5085                                         // Note that announcement_signatures fails if the channel cannot be announced,
5086                                         // so get_channel_update_for_broadcast will never fail by the time we get here.
5087                                         update_msg: Some(self.get_channel_update_for_broadcast(chan.get()).unwrap()),
5088                                 });
5089                         },
5090                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
5091                 }
5092                 Ok(())
5093         }
5094
5095         /// Returns ShouldPersist if anything changed, otherwise either SkipPersist or an Err.
5096         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
5097                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
5098                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
5099                         None => {
5100                                 // It's not a local channel
5101                                 return Ok(NotifyOption::SkipPersist)
5102                         }
5103                 };
5104                 let per_peer_state = self.per_peer_state.read().unwrap();
5105                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
5106                 if peer_state_mutex_opt.is_none() {
5107                         return Ok(NotifyOption::SkipPersist)
5108                 }
5109                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
5110                 let peer_state = &mut *peer_state_lock;
5111                 match peer_state.channel_by_id.entry(chan_id) {
5112                         hash_map::Entry::Occupied(mut chan) => {
5113                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
5114                                         if chan.get().should_announce() {
5115                                                 // If the announcement is about a channel of ours which is public, some
5116                                                 // other peer may simply be forwarding all its gossip to us. Don't provide
5117                                                 // a scary-looking error message and return Ok instead.
5118                                                 return Ok(NotifyOption::SkipPersist);
5119                                         }
5120                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a channel_update for a channel from the wrong node - it shouldn't know about our private channels!".to_owned(), chan_id));
5121                                 }
5122                                 let were_node_one = self.get_our_node_id().serialize()[..] < chan.get().get_counterparty_node_id().serialize()[..];
5123                                 let msg_from_node_one = msg.contents.flags & 1 == 0;
5124                                 if were_node_one == msg_from_node_one {
5125                                         return Ok(NotifyOption::SkipPersist);
5126                                 } else {
5127                                         log_debug!(self.logger, "Received channel_update for channel {}.", log_bytes!(chan_id));
5128                                         try_chan_entry!(self, chan.get_mut().channel_update(&msg), chan);
5129                                 }
5130                         },
5131                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersist)
5132                 }
5133                 Ok(NotifyOption::DoPersist)
5134         }
5135
5136         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
5137                 let htlc_forwards;
5138                 let need_lnd_workaround = {
5139                         let per_peer_state = self.per_peer_state.read().unwrap();
5140
5141                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5142                                 .ok_or_else(|| {
5143                                         debug_assert!(false);
5144                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5145                                 })?;
5146                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5147                         let peer_state = &mut *peer_state_lock;
5148                         match peer_state.channel_by_id.entry(msg.channel_id) {
5149                                 hash_map::Entry::Occupied(mut chan) => {
5150                                         // Currently, we expect all holding cell update_adds to be dropped on peer
5151                                         // disconnect, so Channel's reestablish will never hand us any holding cell
5152                                         // freed HTLCs to fail backwards. If in the future we no longer drop pending
5153                                         // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
5154                                         let responses = try_chan_entry!(self, chan.get_mut().channel_reestablish(
5155                                                 msg, &self.logger, &self.node_signer, self.genesis_hash,
5156                                                 &self.default_configuration, &*self.best_block.read().unwrap()), chan);
5157                                         let mut channel_update = None;
5158                                         if let Some(msg) = responses.shutdown_msg {
5159                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
5160                                                         node_id: counterparty_node_id.clone(),
5161                                                         msg,
5162                                                 });
5163                                         } else if chan.get().is_usable() {
5164                                                 // If the channel is in a usable state (ie the channel is not being shut
5165                                                 // down), send a unicast channel_update to our counterparty to make sure
5166                                                 // they have the latest channel parameters.
5167                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan.get()) {
5168                                                         channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
5169                                                                 node_id: chan.get().get_counterparty_node_id(),
5170                                                                 msg,
5171                                                         });
5172                                                 }
5173                                         }
5174                                         let need_lnd_workaround = chan.get_mut().workaround_lnd_bug_4006.take();
5175                                         htlc_forwards = self.handle_channel_resumption(
5176                                                 &mut peer_state.pending_msg_events, chan.get_mut(), responses.raa, responses.commitment_update, responses.order,
5177                                                 Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
5178                                         if let Some(upd) = channel_update {
5179                                                 peer_state.pending_msg_events.push(upd);
5180                                         }
5181                                         need_lnd_workaround
5182                                 },
5183                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
5184                         }
5185                 };
5186
5187                 if let Some(forwards) = htlc_forwards {
5188                         self.forward_htlcs(&mut [forwards][..]);
5189                 }
5190
5191                 if let Some(channel_ready_msg) = need_lnd_workaround {
5192                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
5193                 }
5194                 Ok(())
5195         }
5196
5197         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
5198         fn process_pending_monitor_events(&self) -> bool {
5199                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5200
5201                 let mut failed_channels = Vec::new();
5202                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
5203                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
5204                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
5205                         for monitor_event in monitor_events.drain(..) {
5206                                 match monitor_event {
5207                                         MonitorEvent::HTLCEvent(htlc_update) => {
5208                                                 if let Some(preimage) = htlc_update.payment_preimage {
5209                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
5210                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, funding_outpoint.to_channel_id());
5211                                                 } else {
5212                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
5213                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
5214                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
5215                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
5216                                                 }
5217                                         },
5218                                         MonitorEvent::CommitmentTxConfirmed(funding_outpoint) |
5219                                         MonitorEvent::UpdateFailed(funding_outpoint) => {
5220                                                 let counterparty_node_id_opt = match counterparty_node_id {
5221                                                         Some(cp_id) => Some(cp_id),
5222                                                         None => {
5223                                                                 // TODO: Once we can rely on the counterparty_node_id from the
5224                                                                 // monitor event, this and the id_to_peer map should be removed.
5225                                                                 let id_to_peer = self.id_to_peer.lock().unwrap();
5226                                                                 id_to_peer.get(&funding_outpoint.to_channel_id()).cloned()
5227                                                         }
5228                                                 };
5229                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
5230                                                         let per_peer_state = self.per_peer_state.read().unwrap();
5231                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
5232                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5233                                                                 let peer_state = &mut *peer_state_lock;
5234                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
5235                                                                 if let hash_map::Entry::Occupied(chan_entry) = peer_state.channel_by_id.entry(funding_outpoint.to_channel_id()) {
5236                                                                         let mut chan = remove_channel!(self, chan_entry);
5237                                                                         failed_channels.push(chan.force_shutdown(false));
5238                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
5239                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
5240                                                                                         msg: update
5241                                                                                 });
5242                                                                         }
5243                                                                         let reason = if let MonitorEvent::UpdateFailed(_) = monitor_event {
5244                                                                                 ClosureReason::ProcessingError { err: "Failed to persist ChannelMonitor update during chain sync".to_string() }
5245                                                                         } else {
5246                                                                                 ClosureReason::CommitmentTxConfirmed
5247                                                                         };
5248                                                                         self.issue_channel_close_events(&chan, reason);
5249                                                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
5250                                                                                 node_id: chan.get_counterparty_node_id(),
5251                                                                                 action: msgs::ErrorAction::SendErrorMessage {
5252                                                                                         msg: msgs::ErrorMessage { channel_id: chan.channel_id(), data: "Channel force-closed".to_owned() }
5253                                                                                 },
5254                                                                         });
5255                                                                 }
5256                                                         }
5257                                                 }
5258                                         },
5259                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
5260                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id, counterparty_node_id.as_ref());
5261                                         },
5262                                 }
5263                         }
5264                 }
5265
5266                 for failure in failed_channels.drain(..) {
5267                         self.finish_force_close_channel(failure);
5268                 }
5269
5270                 has_pending_monitor_events
5271         }
5272
5273         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
5274         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
5275         /// update events as a separate process method here.
5276         #[cfg(fuzzing)]
5277         pub fn process_monitor_events(&self) {
5278                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
5279                         if self.process_pending_monitor_events() {
5280                                 NotifyOption::DoPersist
5281                         } else {
5282                                 NotifyOption::SkipPersist
5283                         }
5284                 });
5285         }
5286
5287         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
5288         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
5289         /// update was applied.
5290         fn check_free_holding_cells(&self) -> bool {
5291                 let mut has_monitor_update = false;
5292                 let mut failed_htlcs = Vec::new();
5293                 let mut handle_errors = Vec::new();
5294
5295                 // Walk our list of channels and find any that need to update. Note that when we do find an
5296                 // update, if it includes actions that must be taken afterwards, we have to drop the
5297                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
5298                 // manage to go through all our peers without finding a single channel to update.
5299                 'peer_loop: loop {
5300                         let per_peer_state = self.per_peer_state.read().unwrap();
5301                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
5302                                 'chan_loop: loop {
5303                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5304                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
5305                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut() {
5306                                                 let counterparty_node_id = chan.get_counterparty_node_id();
5307                                                 let funding_txo = chan.get_funding_txo();
5308                                                 let (monitor_opt, holding_cell_failed_htlcs) =
5309                                                         chan.maybe_free_holding_cell_htlcs(&self.logger);
5310                                                 if !holding_cell_failed_htlcs.is_empty() {
5311                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
5312                                                 }
5313                                                 if let Some(monitor_update) = monitor_opt {
5314                                                         has_monitor_update = true;
5315
5316                                                         let update_res = self.chain_monitor.update_channel(
5317                                                                 funding_txo.expect("channel is live"), monitor_update);
5318                                                         let update_id = monitor_update.update_id;
5319                                                         let channel_id: [u8; 32] = *channel_id;
5320                                                         let res = handle_new_monitor_update!(self, update_res, update_id,
5321                                                                 peer_state_lock, peer_state, per_peer_state, chan, MANUALLY_REMOVING,
5322                                                                 peer_state.channel_by_id.remove(&channel_id));
5323                                                         if res.is_err() {
5324                                                                 handle_errors.push((counterparty_node_id, res));
5325                                                         }
5326                                                         continue 'peer_loop;
5327                                                 }
5328                                         }
5329                                         break 'chan_loop;
5330                                 }
5331                         }
5332                         break 'peer_loop;
5333                 }
5334
5335                 let has_update = has_monitor_update || !failed_htlcs.is_empty() || !handle_errors.is_empty();
5336                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
5337                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
5338                 }
5339
5340                 for (counterparty_node_id, err) in handle_errors.drain(..) {
5341                         let _ = handle_error!(self, err, counterparty_node_id);
5342                 }
5343
5344                 has_update
5345         }
5346
5347         /// Check whether any channels have finished removing all pending updates after a shutdown
5348         /// exchange and can now send a closing_signed.
5349         /// Returns whether any closing_signed messages were generated.
5350         fn maybe_generate_initial_closing_signed(&self) -> bool {
5351                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
5352                 let mut has_update = false;
5353                 {
5354                         let per_peer_state = self.per_peer_state.read().unwrap();
5355
5356                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
5357                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5358                                 let peer_state = &mut *peer_state_lock;
5359                                 let pending_msg_events = &mut peer_state.pending_msg_events;
5360                                 peer_state.channel_by_id.retain(|channel_id, chan| {
5361                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &self.logger) {
5362                                                 Ok((msg_opt, tx_opt)) => {
5363                                                         if let Some(msg) = msg_opt {
5364                                                                 has_update = true;
5365                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
5366                                                                         node_id: chan.get_counterparty_node_id(), msg,
5367                                                                 });
5368                                                         }
5369                                                         if let Some(tx) = tx_opt {
5370                                                                 // We're done with this channel. We got a closing_signed and sent back
5371                                                                 // a closing_signed with a closing transaction to broadcast.
5372                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
5373                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
5374                                                                                 msg: update
5375                                                                         });
5376                                                                 }
5377
5378                                                                 self.issue_channel_close_events(chan, ClosureReason::CooperativeClosure);
5379
5380                                                                 log_info!(self.logger, "Broadcasting {}", log_tx!(tx));
5381                                                                 self.tx_broadcaster.broadcast_transaction(&tx);
5382                                                                 update_maps_on_chan_removal!(self, chan);
5383                                                                 false
5384                                                         } else { true }
5385                                                 },
5386                                                 Err(e) => {
5387                                                         has_update = true;
5388                                                         let (close_channel, res) = convert_chan_err!(self, e, chan, channel_id);
5389                                                         handle_errors.push((chan.get_counterparty_node_id(), Err(res)));
5390                                                         !close_channel
5391                                                 }
5392                                         }
5393                                 });
5394                         }
5395                 }
5396
5397                 for (counterparty_node_id, err) in handle_errors.drain(..) {
5398                         let _ = handle_error!(self, err, counterparty_node_id);
5399                 }
5400
5401                 has_update
5402         }
5403
5404         /// Handle a list of channel failures during a block_connected or block_disconnected call,
5405         /// pushing the channel monitor update (if any) to the background events queue and removing the
5406         /// Channel object.
5407         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
5408                 for mut failure in failed_channels.drain(..) {
5409                         // Either a commitment transactions has been confirmed on-chain or
5410                         // Channel::block_disconnected detected that the funding transaction has been
5411                         // reorganized out of the main chain.
5412                         // We cannot broadcast our latest local state via monitor update (as
5413                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
5414                         // so we track the update internally and handle it when the user next calls
5415                         // timer_tick_occurred, guaranteeing we're running normally.
5416                         if let Some((funding_txo, update)) = failure.0.take() {
5417                                 assert_eq!(update.updates.len(), 1);
5418                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
5419                                         assert!(should_broadcast);
5420                                 } else { unreachable!(); }
5421                                 self.pending_background_events.lock().unwrap().push(BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)));
5422                         }
5423                         self.finish_force_close_channel(failure);
5424                 }
5425         }
5426
5427         fn set_payment_hash_secret_map(&self, payment_hash: PaymentHash, payment_preimage: Option<PaymentPreimage>, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32) -> Result<PaymentSecret, APIError> {
5428                 assert!(invoice_expiry_delta_secs <= 60*60*24*365); // Sadly bitcoin timestamps are u32s, so panic before 2106
5429
5430                 if min_value_msat.is_some() && min_value_msat.unwrap() > MAX_VALUE_MSAT {
5431                         return Err(APIError::APIMisuseError { err: format!("min_value_msat of {} greater than total 21 million bitcoin supply", min_value_msat.unwrap()) });
5432                 }
5433
5434                 let payment_secret = PaymentSecret(self.entropy_source.get_secure_random_bytes());
5435
5436                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5437                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
5438                 match payment_secrets.entry(payment_hash) {
5439                         hash_map::Entry::Vacant(e) => {
5440                                 e.insert(PendingInboundPayment {
5441                                         payment_secret, min_value_msat, payment_preimage,
5442                                         user_payment_id: 0, // For compatibility with version 0.0.103 and earlier
5443                                         // We assume that highest_seen_timestamp is pretty close to the current time -
5444                                         // it's updated when we receive a new block with the maximum time we've seen in
5445                                         // a header. It should never be more than two hours in the future.
5446                                         // Thus, we add two hours here as a buffer to ensure we absolutely
5447                                         // never fail a payment too early.
5448                                         // Note that we assume that received blocks have reasonably up-to-date
5449                                         // timestamps.
5450                                         expiry_time: self.highest_seen_timestamp.load(Ordering::Acquire) as u64 + invoice_expiry_delta_secs as u64 + 7200,
5451                                 });
5452                         },
5453                         hash_map::Entry::Occupied(_) => return Err(APIError::APIMisuseError { err: "Duplicate payment hash".to_owned() }),
5454                 }
5455                 Ok(payment_secret)
5456         }
5457
5458         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
5459         /// to pay us.
5460         ///
5461         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
5462         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
5463         ///
5464         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
5465         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
5466         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
5467         /// passed directly to [`claim_funds`].
5468         ///
5469         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
5470         ///
5471         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
5472         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
5473         ///
5474         /// # Note
5475         ///
5476         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
5477         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
5478         ///
5479         /// Errors if `min_value_msat` is greater than total bitcoin supply.
5480         ///
5481         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
5482         /// on versions of LDK prior to 0.0.114.
5483         ///
5484         /// [`claim_funds`]: Self::claim_funds
5485         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
5486         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
5487         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
5488         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
5489         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5490         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
5491                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
5492                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
5493                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
5494                         min_final_cltv_expiry_delta)
5495         }
5496
5497         /// Legacy version of [`create_inbound_payment`]. Use this method if you wish to share
5498         /// serialized state with LDK node(s) running 0.0.103 and earlier.
5499         ///
5500         /// May panic if `invoice_expiry_delta_secs` is greater than one year.
5501         ///
5502         /// # Note
5503         /// This method is deprecated and will be removed soon.
5504         ///
5505         /// [`create_inbound_payment`]: Self::create_inbound_payment
5506         #[deprecated]
5507         pub fn create_inbound_payment_legacy(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32) -> Result<(PaymentHash, PaymentSecret), APIError> {
5508                 let payment_preimage = PaymentPreimage(self.entropy_source.get_secure_random_bytes());
5509                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
5510                 let payment_secret = self.set_payment_hash_secret_map(payment_hash, Some(payment_preimage), min_value_msat, invoice_expiry_delta_secs)?;
5511                 Ok((payment_hash, payment_secret))
5512         }
5513
5514         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
5515         /// stored external to LDK.
5516         ///
5517         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
5518         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
5519         /// the `min_value_msat` provided here, if one is provided.
5520         ///
5521         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
5522         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
5523         /// payments.
5524         ///
5525         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
5526         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
5527         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
5528         /// sender "proof-of-payment" unless they have paid the required amount.
5529         ///
5530         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
5531         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
5532         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
5533         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
5534         /// invoices when no timeout is set.
5535         ///
5536         /// Note that we use block header time to time-out pending inbound payments (with some margin
5537         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
5538         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
5539         /// If you need exact expiry semantics, you should enforce them upon receipt of
5540         /// [`PaymentClaimable`].
5541         ///
5542         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
5543         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
5544         ///
5545         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
5546         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
5547         ///
5548         /// # Note
5549         ///
5550         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
5551         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
5552         ///
5553         /// Errors if `min_value_msat` is greater than total bitcoin supply.
5554         ///
5555         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
5556         /// on versions of LDK prior to 0.0.114.
5557         ///
5558         /// [`create_inbound_payment`]: Self::create_inbound_payment
5559         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
5560         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
5561                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
5562                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
5563                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
5564                         min_final_cltv_expiry)
5565         }
5566
5567         /// Legacy version of [`create_inbound_payment_for_hash`]. Use this method if you wish to share
5568         /// serialized state with LDK node(s) running 0.0.103 and earlier.
5569         ///
5570         /// May panic if `invoice_expiry_delta_secs` is greater than one year.
5571         ///
5572         /// # Note
5573         /// This method is deprecated and will be removed soon.
5574         ///
5575         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5576         #[deprecated]
5577         pub fn create_inbound_payment_for_hash_legacy(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32) -> Result<PaymentSecret, APIError> {
5578                 self.set_payment_hash_secret_map(payment_hash, None, min_value_msat, invoice_expiry_delta_secs)
5579         }
5580
5581         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
5582         /// previously returned from [`create_inbound_payment`].
5583         ///
5584         /// [`create_inbound_payment`]: Self::create_inbound_payment
5585         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
5586                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
5587         }
5588
5589         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
5590         /// are used when constructing the phantom invoice's route hints.
5591         ///
5592         /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
5593         pub fn get_phantom_scid(&self) -> u64 {
5594                 let best_block_height = self.best_block.read().unwrap().height();
5595                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
5596                 loop {
5597                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
5598                         // Ensure the generated scid doesn't conflict with a real channel.
5599                         match short_to_chan_info.get(&scid_candidate) {
5600                                 Some(_) => continue,
5601                                 None => return scid_candidate
5602                         }
5603                 }
5604         }
5605
5606         /// Gets route hints for use in receiving [phantom node payments].
5607         ///
5608         /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
5609         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
5610                 PhantomRouteHints {
5611                         channels: self.list_usable_channels(),
5612                         phantom_scid: self.get_phantom_scid(),
5613                         real_node_pubkey: self.get_our_node_id(),
5614                 }
5615         }
5616
5617         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
5618         /// used when constructing the route hints for HTLCs intended to be intercepted. See
5619         /// [`ChannelManager::forward_intercepted_htlc`].
5620         ///
5621         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
5622         /// times to get a unique scid.
5623         pub fn get_intercept_scid(&self) -> u64 {
5624                 let best_block_height = self.best_block.read().unwrap().height();
5625                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
5626                 loop {
5627                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
5628                         // Ensure the generated scid doesn't conflict with a real channel.
5629                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
5630                         return scid_candidate
5631                 }
5632         }
5633
5634         /// Gets inflight HTLC information by processing pending outbound payments that are in
5635         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
5636         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
5637                 let mut inflight_htlcs = InFlightHtlcs::new();
5638
5639                 let per_peer_state = self.per_peer_state.read().unwrap();
5640                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
5641                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5642                         let peer_state = &mut *peer_state_lock;
5643                         for chan in peer_state.channel_by_id.values() {
5644                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
5645                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
5646                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
5647                                         }
5648                                 }
5649                         }
5650                 }
5651
5652                 inflight_htlcs
5653         }
5654
5655         #[cfg(any(test, fuzzing, feature = "_test_utils"))]
5656         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
5657                 let events = core::cell::RefCell::new(Vec::new());
5658                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
5659                 self.process_pending_events(&event_handler);
5660                 events.into_inner()
5661         }
5662
5663         #[cfg(feature = "_test_utils")]
5664         pub fn push_pending_event(&self, event: events::Event) {
5665                 let mut events = self.pending_events.lock().unwrap();
5666                 events.push(event);
5667         }
5668
5669         #[cfg(test)]
5670         pub fn pop_pending_event(&self) -> Option<events::Event> {
5671                 let mut events = self.pending_events.lock().unwrap();
5672                 if events.is_empty() { None } else { Some(events.remove(0)) }
5673         }
5674
5675         #[cfg(test)]
5676         pub fn has_pending_payments(&self) -> bool {
5677                 self.pending_outbound_payments.has_pending_payments()
5678         }
5679
5680         #[cfg(test)]
5681         pub fn clear_pending_payments(&self) {
5682                 self.pending_outbound_payments.clear_pending_payments()
5683         }
5684
5685         /// Processes any events asynchronously in the order they were generated since the last call
5686         /// using the given event handler.
5687         ///
5688         /// See the trait-level documentation of [`EventsProvider`] for requirements.
5689         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
5690                 &self, handler: H
5691         ) {
5692                 // We'll acquire our total consistency lock until the returned future completes so that
5693                 // we can be sure no other persists happen while processing events.
5694                 let _read_guard = self.total_consistency_lock.read().unwrap();
5695
5696                 let mut result = NotifyOption::SkipPersist;
5697
5698                 // TODO: This behavior should be documented. It's unintuitive that we query
5699                 // ChannelMonitors when clearing other events.
5700                 if self.process_pending_monitor_events() {
5701                         result = NotifyOption::DoPersist;
5702                 }
5703
5704                 let pending_events = mem::replace(&mut *self.pending_events.lock().unwrap(), vec![]);
5705                 if !pending_events.is_empty() {
5706                         result = NotifyOption::DoPersist;
5707                 }
5708
5709                 for event in pending_events {
5710                         handler(event).await;
5711                 }
5712
5713                 if result == NotifyOption::DoPersist {
5714                         self.persistence_notifier.notify();
5715                 }
5716         }
5717 }
5718
5719 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> MessageSendEventsProvider for ChannelManager<M, T, ES, NS, SP, F, R, L>
5720 where
5721         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
5722         T::Target: BroadcasterInterface,
5723         ES::Target: EntropySource,
5724         NS::Target: NodeSigner,
5725         SP::Target: SignerProvider,
5726         F::Target: FeeEstimator,
5727         R::Target: Router,
5728         L::Target: Logger,
5729 {
5730         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
5731         /// The returned array will contain `MessageSendEvent`s for different peers if
5732         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
5733         /// is always placed next to each other.
5734         ///
5735         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
5736         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
5737         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
5738         /// will randomly be placed first or last in the returned array.
5739         ///
5740         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
5741         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
5742         /// the `MessageSendEvent`s to the specific peer they were generated under.
5743         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
5744                 let events = RefCell::new(Vec::new());
5745                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
5746                         let mut result = NotifyOption::SkipPersist;
5747
5748                         // TODO: This behavior should be documented. It's unintuitive that we query
5749                         // ChannelMonitors when clearing other events.
5750                         if self.process_pending_monitor_events() {
5751                                 result = NotifyOption::DoPersist;
5752                         }
5753
5754                         if self.check_free_holding_cells() {
5755                                 result = NotifyOption::DoPersist;
5756                         }
5757                         if self.maybe_generate_initial_closing_signed() {
5758                                 result = NotifyOption::DoPersist;
5759                         }
5760
5761                         let mut pending_events = Vec::new();
5762                         let per_peer_state = self.per_peer_state.read().unwrap();
5763                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
5764                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5765                                 let peer_state = &mut *peer_state_lock;
5766                                 if peer_state.pending_msg_events.len() > 0 {
5767                                         pending_events.append(&mut peer_state.pending_msg_events);
5768                                 }
5769                         }
5770
5771                         if !pending_events.is_empty() {
5772                                 events.replace(pending_events);
5773                         }
5774
5775                         result
5776                 });
5777                 events.into_inner()
5778         }
5779 }
5780
5781 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> EventsProvider for ChannelManager<M, T, ES, NS, SP, F, R, L>
5782 where
5783         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
5784         T::Target: BroadcasterInterface,
5785         ES::Target: EntropySource,
5786         NS::Target: NodeSigner,
5787         SP::Target: SignerProvider,
5788         F::Target: FeeEstimator,
5789         R::Target: Router,
5790         L::Target: Logger,
5791 {
5792         /// Processes events that must be periodically handled.
5793         ///
5794         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
5795         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
5796         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
5797                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
5798                         let mut result = NotifyOption::SkipPersist;
5799
5800                         // TODO: This behavior should be documented. It's unintuitive that we query
5801                         // ChannelMonitors when clearing other events.
5802                         if self.process_pending_monitor_events() {
5803                                 result = NotifyOption::DoPersist;
5804                         }
5805
5806                         let pending_events = mem::replace(&mut *self.pending_events.lock().unwrap(), vec![]);
5807                         if !pending_events.is_empty() {
5808                                 result = NotifyOption::DoPersist;
5809                         }
5810
5811                         for event in pending_events {
5812                                 handler.handle_event(event);
5813                         }
5814
5815                         result
5816                 });
5817         }
5818 }
5819
5820 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> chain::Listen for ChannelManager<M, T, ES, NS, SP, F, R, L>
5821 where
5822         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
5823         T::Target: BroadcasterInterface,
5824         ES::Target: EntropySource,
5825         NS::Target: NodeSigner,
5826         SP::Target: SignerProvider,
5827         F::Target: FeeEstimator,
5828         R::Target: Router,
5829         L::Target: Logger,
5830 {
5831         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
5832                 {
5833                         let best_block = self.best_block.read().unwrap();
5834                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
5835                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
5836                         assert_eq!(best_block.height(), height - 1,
5837                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
5838                 }
5839
5840                 self.transactions_confirmed(header, txdata, height);
5841                 self.best_block_updated(header, height);
5842         }
5843
5844         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
5845                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5846                 let new_height = height - 1;
5847                 {
5848                         let mut best_block = self.best_block.write().unwrap();
5849                         assert_eq!(best_block.block_hash(), header.block_hash(),
5850                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
5851                         assert_eq!(best_block.height(), height,
5852                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
5853                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
5854                 }
5855
5856                 self.do_chain_event(Some(new_height), |channel| channel.best_block_updated(new_height, header.time, self.genesis_hash.clone(), &self.node_signer, &self.default_configuration, &self.logger));
5857         }
5858 }
5859
5860 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> chain::Confirm for ChannelManager<M, T, ES, NS, SP, F, R, L>
5861 where
5862         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
5863         T::Target: BroadcasterInterface,
5864         ES::Target: EntropySource,
5865         NS::Target: NodeSigner,
5866         SP::Target: SignerProvider,
5867         F::Target: FeeEstimator,
5868         R::Target: Router,
5869         L::Target: Logger,
5870 {
5871         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
5872                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5873                 // during initialization prior to the chain_monitor being fully configured in some cases.
5874                 // See the docs for `ChannelManagerReadArgs` for more.
5875
5876                 let block_hash = header.block_hash();
5877                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
5878
5879                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5880                 self.do_chain_event(Some(height), |channel| channel.transactions_confirmed(&block_hash, height, txdata, self.genesis_hash.clone(), &self.node_signer, &self.default_configuration, &self.logger)
5881                         .map(|(a, b)| (a, Vec::new(), b)));
5882
5883                 let last_best_block_height = self.best_block.read().unwrap().height();
5884                 if height < last_best_block_height {
5885                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
5886                         self.do_chain_event(Some(last_best_block_height), |channel| channel.best_block_updated(last_best_block_height, timestamp as u32, self.genesis_hash.clone(), &self.node_signer, &self.default_configuration, &self.logger));
5887                 }
5888         }
5889
5890         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
5891                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5892                 // during initialization prior to the chain_monitor being fully configured in some cases.
5893                 // See the docs for `ChannelManagerReadArgs` for more.
5894
5895                 let block_hash = header.block_hash();
5896                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
5897
5898                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5899
5900                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
5901
5902                 self.do_chain_event(Some(height), |channel| channel.best_block_updated(height, header.time, self.genesis_hash.clone(), &self.node_signer, &self.default_configuration, &self.logger));
5903
5904                 macro_rules! max_time {
5905                         ($timestamp: expr) => {
5906                                 loop {
5907                                         // Update $timestamp to be the max of its current value and the block
5908                                         // timestamp. This should keep us close to the current time without relying on
5909                                         // having an explicit local time source.
5910                                         // Just in case we end up in a race, we loop until we either successfully
5911                                         // update $timestamp or decide we don't need to.
5912                                         let old_serial = $timestamp.load(Ordering::Acquire);
5913                                         if old_serial >= header.time as usize { break; }
5914                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
5915                                                 break;
5916                                         }
5917                                 }
5918                         }
5919                 }
5920                 max_time!(self.highest_seen_timestamp);
5921                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
5922                 payment_secrets.retain(|_, inbound_payment| {
5923                         inbound_payment.expiry_time > header.time as u64
5924                 });
5925         }
5926
5927         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
5928                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
5929                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
5930                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5931                         let peer_state = &mut *peer_state_lock;
5932                         for chan in peer_state.channel_by_id.values() {
5933                                 if let (Some(funding_txo), Some(block_hash)) = (chan.get_funding_txo(), chan.get_funding_tx_confirmed_in()) {
5934                                         res.push((funding_txo.txid, Some(block_hash)));
5935                                 }
5936                         }
5937                 }
5938                 res
5939         }
5940
5941         fn transaction_unconfirmed(&self, txid: &Txid) {
5942                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5943                 self.do_chain_event(None, |channel| {
5944                         if let Some(funding_txo) = channel.get_funding_txo() {
5945                                 if funding_txo.txid == *txid {
5946                                         channel.funding_transaction_unconfirmed(&self.logger).map(|()| (None, Vec::new(), None))
5947                                 } else { Ok((None, Vec::new(), None)) }
5948                         } else { Ok((None, Vec::new(), None)) }
5949                 });
5950         }
5951 }
5952
5953 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> ChannelManager<M, T, ES, NS, SP, F, R, L>
5954 where
5955         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
5956         T::Target: BroadcasterInterface,
5957         ES::Target: EntropySource,
5958         NS::Target: NodeSigner,
5959         SP::Target: SignerProvider,
5960         F::Target: FeeEstimator,
5961         R::Target: Router,
5962         L::Target: Logger,
5963 {
5964         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
5965         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
5966         /// the function.
5967         fn do_chain_event<FN: Fn(&mut Channel<<SP::Target as SignerProvider>::Signer>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
5968                         (&self, height_opt: Option<u32>, f: FN) {
5969                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5970                 // during initialization prior to the chain_monitor being fully configured in some cases.
5971                 // See the docs for `ChannelManagerReadArgs` for more.
5972
5973                 let mut failed_channels = Vec::new();
5974                 let mut timed_out_htlcs = Vec::new();
5975                 {
5976                         let per_peer_state = self.per_peer_state.read().unwrap();
5977                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
5978                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5979                                 let peer_state = &mut *peer_state_lock;
5980                                 let pending_msg_events = &mut peer_state.pending_msg_events;
5981                                 peer_state.channel_by_id.retain(|_, channel| {
5982                                         let res = f(channel);
5983                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
5984                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
5985                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
5986                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
5987                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.get_counterparty_node_id()), channel_id: channel.channel_id() }));
5988                                                 }
5989                                                 if let Some(channel_ready) = channel_ready_opt {
5990                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
5991                                                         if channel.is_usable() {
5992                                                                 log_trace!(self.logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", log_bytes!(channel.channel_id()));
5993                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
5994                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
5995                                                                                 node_id: channel.get_counterparty_node_id(),
5996                                                                                 msg,
5997                                                                         });
5998                                                                 }
5999                                                         } else {
6000                                                                 log_trace!(self.logger, "Sending channel_ready WITHOUT channel_update for {}", log_bytes!(channel.channel_id()));
6001                                                         }
6002                                                 }
6003
6004                                                 emit_channel_ready_event!(self, channel);
6005
6006                                                 if let Some(announcement_sigs) = announcement_sigs {
6007                                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", log_bytes!(channel.channel_id()));
6008                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
6009                                                                 node_id: channel.get_counterparty_node_id(),
6010                                                                 msg: announcement_sigs,
6011                                                         });
6012                                                         if let Some(height) = height_opt {
6013                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.genesis_hash, height, &self.default_configuration) {
6014                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
6015                                                                                 msg: announcement,
6016                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
6017                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
6018                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
6019                                                                         });
6020                                                                 }
6021                                                         }
6022                                                 }
6023                                                 if channel.is_our_channel_ready() {
6024                                                         if let Some(real_scid) = channel.get_short_channel_id() {
6025                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
6026                                                                 // to the short_to_chan_info map here. Note that we check whether we
6027                                                                 // can relay using the real SCID at relay-time (i.e.
6028                                                                 // enforce option_scid_alias then), and if the funding tx is ever
6029                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
6030                                                                 // is always consistent.
6031                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
6032                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.get_counterparty_node_id(), channel.channel_id()));
6033                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.get_counterparty_node_id(), channel.channel_id()),
6034                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
6035                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
6036                                                         }
6037                                                 }
6038                                         } else if let Err(reason) = res {
6039                                                 update_maps_on_chan_removal!(self, channel);
6040                                                 // It looks like our counterparty went on-chain or funding transaction was
6041                                                 // reorged out of the main chain. Close the channel.
6042                                                 failed_channels.push(channel.force_shutdown(true));
6043                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
6044                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6045                                                                 msg: update
6046                                                         });
6047                                                 }
6048                                                 let reason_message = format!("{}", reason);
6049                                                 self.issue_channel_close_events(channel, reason);
6050                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
6051                                                         node_id: channel.get_counterparty_node_id(),
6052                                                         action: msgs::ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage {
6053                                                                 channel_id: channel.channel_id(),
6054                                                                 data: reason_message,
6055                                                         } },
6056                                                 });
6057                                                 return false;
6058                                         }
6059                                         true
6060                                 });
6061                         }
6062                 }
6063
6064                 if let Some(height) = height_opt {
6065                         self.claimable_payments.lock().unwrap().claimable_htlcs.retain(|payment_hash, (_, htlcs)| {
6066                                 htlcs.retain(|htlc| {
6067                                         // If height is approaching the number of blocks we think it takes us to get
6068                                         // our commitment transaction confirmed before the HTLC expires, plus the
6069                                         // number of blocks we generally consider it to take to do a commitment update,
6070                                         // just give up on it and fail the HTLC.
6071                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
6072                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
6073                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
6074
6075                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
6076                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
6077                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
6078                                                 false
6079                                         } else { true }
6080                                 });
6081                                 !htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
6082                         });
6083
6084                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
6085                         intercepted_htlcs.retain(|_, htlc| {
6086                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
6087                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6088                                                 short_channel_id: htlc.prev_short_channel_id,
6089                                                 htlc_id: htlc.prev_htlc_id,
6090                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
6091                                                 phantom_shared_secret: None,
6092                                                 outpoint: htlc.prev_funding_outpoint,
6093                                         });
6094
6095                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
6096                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6097                                                 _ => unreachable!(),
6098                                         };
6099                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
6100                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
6101                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
6102                                         log_trace!(self.logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
6103                                         false
6104                                 } else { true }
6105                         });
6106                 }
6107
6108                 self.handle_init_event_channel_failures(failed_channels);
6109
6110                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
6111                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
6112                 }
6113         }
6114
6115         /// Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool
6116         /// indicating whether persistence is necessary. Only one listener on
6117         /// [`await_persistable_update`], [`await_persistable_update_timeout`], or a future returned by
6118         /// [`get_persistable_update_future`] is guaranteed to be woken up.
6119         ///
6120         /// Note that this method is not available with the `no-std` feature.
6121         ///
6122         /// [`await_persistable_update`]: Self::await_persistable_update
6123         /// [`await_persistable_update_timeout`]: Self::await_persistable_update_timeout
6124         /// [`get_persistable_update_future`]: Self::get_persistable_update_future
6125         #[cfg(any(test, feature = "std"))]
6126         pub fn await_persistable_update_timeout(&self, max_wait: Duration) -> bool {
6127                 self.persistence_notifier.wait_timeout(max_wait)
6128         }
6129
6130         /// Blocks until ChannelManager needs to be persisted. Only one listener on
6131         /// [`await_persistable_update`], `await_persistable_update_timeout`, or a future returned by
6132         /// [`get_persistable_update_future`] is guaranteed to be woken up.
6133         ///
6134         /// [`await_persistable_update`]: Self::await_persistable_update
6135         /// [`get_persistable_update_future`]: Self::get_persistable_update_future
6136         pub fn await_persistable_update(&self) {
6137                 self.persistence_notifier.wait()
6138         }
6139
6140         /// Gets a [`Future`] that completes when a persistable update is available. Note that
6141         /// callbacks registered on the [`Future`] MUST NOT call back into this [`ChannelManager`] and
6142         /// should instead register actions to be taken later.
6143         pub fn get_persistable_update_future(&self) -> Future {
6144                 self.persistence_notifier.get_future()
6145         }
6146
6147         #[cfg(any(test, feature = "_test_utils"))]
6148         pub fn get_persistence_condvar_value(&self) -> bool {
6149                 self.persistence_notifier.notify_pending()
6150         }
6151
6152         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
6153         /// [`chain::Confirm`] interfaces.
6154         pub fn current_best_block(&self) -> BestBlock {
6155                 self.best_block.read().unwrap().clone()
6156         }
6157
6158         /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
6159         /// [`ChannelManager`].
6160         pub fn node_features(&self) -> NodeFeatures {
6161                 provided_node_features(&self.default_configuration)
6162         }
6163
6164         /// Fetches the set of [`InvoiceFeatures`] flags which are provided by or required by
6165         /// [`ChannelManager`].
6166         ///
6167         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
6168         /// or not. Thus, this method is not public.
6169         #[cfg(any(feature = "_test_utils", test))]
6170         pub fn invoice_features(&self) -> InvoiceFeatures {
6171                 provided_invoice_features(&self.default_configuration)
6172         }
6173
6174         /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
6175         /// [`ChannelManager`].
6176         pub fn channel_features(&self) -> ChannelFeatures {
6177                 provided_channel_features(&self.default_configuration)
6178         }
6179
6180         /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
6181         /// [`ChannelManager`].
6182         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
6183                 provided_channel_type_features(&self.default_configuration)
6184         }
6185
6186         /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
6187         /// [`ChannelManager`].
6188         pub fn init_features(&self) -> InitFeatures {
6189                 provided_init_features(&self.default_configuration)
6190         }
6191 }
6192
6193 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
6194         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
6195 where
6196         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6197         T::Target: BroadcasterInterface,
6198         ES::Target: EntropySource,
6199         NS::Target: NodeSigner,
6200         SP::Target: SignerProvider,
6201         F::Target: FeeEstimator,
6202         R::Target: Router,
6203         L::Target: Logger,
6204 {
6205         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
6206                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6207                 let _ = handle_error!(self, self.internal_open_channel(counterparty_node_id, msg), *counterparty_node_id);
6208         }
6209
6210         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
6211                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6212                 let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
6213         }
6214
6215         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
6216                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6217                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
6218         }
6219
6220         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
6221                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6222                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
6223         }
6224
6225         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
6226                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6227                 let _ = handle_error!(self, self.internal_channel_ready(counterparty_node_id, msg), *counterparty_node_id);
6228         }
6229
6230         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
6231                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6232                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
6233         }
6234
6235         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
6236                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6237                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
6238         }
6239
6240         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
6241                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6242                 let _ = handle_error!(self, self.internal_update_add_htlc(counterparty_node_id, msg), *counterparty_node_id);
6243         }
6244
6245         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
6246                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6247                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
6248         }
6249
6250         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
6251                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6252                 let _ = handle_error!(self, self.internal_update_fail_htlc(counterparty_node_id, msg), *counterparty_node_id);
6253         }
6254
6255         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
6256                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6257                 let _ = handle_error!(self, self.internal_update_fail_malformed_htlc(counterparty_node_id, msg), *counterparty_node_id);
6258         }
6259
6260         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
6261                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6262                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
6263         }
6264
6265         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
6266                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6267                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
6268         }
6269
6270         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
6271                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6272                 let _ = handle_error!(self, self.internal_update_fee(counterparty_node_id, msg), *counterparty_node_id);
6273         }
6274
6275         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
6276                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6277                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
6278         }
6279
6280         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
6281                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
6282                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
6283                                 persist
6284                         } else {
6285                                 NotifyOption::SkipPersist
6286                         }
6287                 });
6288         }
6289
6290         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
6291                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6292                 let _ = handle_error!(self, self.internal_channel_reestablish(counterparty_node_id, msg), *counterparty_node_id);
6293         }
6294
6295         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
6296                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6297                 let mut failed_channels = Vec::new();
6298                 let mut per_peer_state = self.per_peer_state.write().unwrap();
6299                 let remove_peer = {
6300                         log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates.",
6301                                 log_pubkey!(counterparty_node_id));
6302                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
6303                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6304                                 let peer_state = &mut *peer_state_lock;
6305                                 let pending_msg_events = &mut peer_state.pending_msg_events;
6306                                 peer_state.channel_by_id.retain(|_, chan| {
6307                                         chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger);
6308                                         if chan.is_shutdown() {
6309                                                 update_maps_on_chan_removal!(self, chan);
6310                                                 self.issue_channel_close_events(chan, ClosureReason::DisconnectedPeer);
6311                                                 return false;
6312                                         }
6313                                         true
6314                                 });
6315                                 pending_msg_events.retain(|msg| {
6316                                         match msg {
6317                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
6318                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
6319                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
6320                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
6321                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
6322                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
6323                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
6324                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
6325                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
6326                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
6327                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
6328                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
6329                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
6330                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
6331                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
6332                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
6333                                                 &events::MessageSendEvent::HandleError { .. } => false,
6334                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
6335                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
6336                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
6337                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
6338                                         }
6339                                 });
6340                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
6341                                 peer_state.is_connected = false;
6342                                 peer_state.ok_to_remove(true)
6343                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
6344                 };
6345                 if remove_peer {
6346                         per_peer_state.remove(counterparty_node_id);
6347                 }
6348                 mem::drop(per_peer_state);
6349
6350                 for failure in failed_channels.drain(..) {
6351                         self.finish_force_close_channel(failure);
6352                 }
6353         }
6354
6355         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
6356                 if !init_msg.features.supports_static_remote_key() {
6357                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
6358                         return Err(());
6359                 }
6360
6361                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6362
6363                 // If we have too many peers connected which don't have funded channels, disconnect the
6364                 // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
6365                 // unfunded channels taking up space in memory for disconnected peers, we still let new
6366                 // peers connect, but we'll reject new channels from them.
6367                 let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
6368                 let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
6369
6370                 {
6371                         let mut peer_state_lock = self.per_peer_state.write().unwrap();
6372                         match peer_state_lock.entry(counterparty_node_id.clone()) {
6373                                 hash_map::Entry::Vacant(e) => {
6374                                         if inbound_peer_limited {
6375                                                 return Err(());
6376                                         }
6377                                         e.insert(Mutex::new(PeerState {
6378                                                 channel_by_id: HashMap::new(),
6379                                                 latest_features: init_msg.features.clone(),
6380                                                 pending_msg_events: Vec::new(),
6381                                                 monitor_update_blocked_actions: BTreeMap::new(),
6382                                                 is_connected: true,
6383                                         }));
6384                                 },
6385                                 hash_map::Entry::Occupied(e) => {
6386                                         let mut peer_state = e.get().lock().unwrap();
6387                                         peer_state.latest_features = init_msg.features.clone();
6388
6389                                         let best_block_height = self.best_block.read().unwrap().height();
6390                                         if inbound_peer_limited &&
6391                                                 Self::unfunded_channel_count(&*peer_state, best_block_height) ==
6392                                                 peer_state.channel_by_id.len()
6393                                         {
6394                                                 return Err(());
6395                                         }
6396
6397                                         debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
6398                                         peer_state.is_connected = true;
6399                                 },
6400                         }
6401                 }
6402
6403                 log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
6404
6405                 let per_peer_state = self.per_peer_state.read().unwrap();
6406                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6407                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6408                         let peer_state = &mut *peer_state_lock;
6409                         let pending_msg_events = &mut peer_state.pending_msg_events;
6410                         peer_state.channel_by_id.retain(|_, chan| {
6411                                 let retain = if chan.get_counterparty_node_id() == *counterparty_node_id {
6412                                         if !chan.have_received_message() {
6413                                                 // If we created this (outbound) channel while we were disconnected from the
6414                                                 // peer we probably failed to send the open_channel message, which is now
6415                                                 // lost. We can't have had anything pending related to this channel, so we just
6416                                                 // drop it.
6417                                                 false
6418                                         } else {
6419                                                 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
6420                                                         node_id: chan.get_counterparty_node_id(),
6421                                                         msg: chan.get_channel_reestablish(&self.logger),
6422                                                 });
6423                                                 true
6424                                         }
6425                                 } else { true };
6426                                 if retain && chan.get_counterparty_node_id() != *counterparty_node_id {
6427                                         if let Some(msg) = chan.get_signed_channel_announcement(&self.node_signer, self.genesis_hash.clone(), self.best_block.read().unwrap().height(), &self.default_configuration) {
6428                                                 if let Ok(update_msg) = self.get_channel_update_for_broadcast(chan) {
6429                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelAnnouncement {
6430                                                                 node_id: *counterparty_node_id,
6431                                                                 msg, update_msg,
6432                                                         });
6433                                                 }
6434                                         }
6435                                 }
6436                                 retain
6437                         });
6438                 }
6439                 //TODO: Also re-broadcast announcement_signatures
6440                 Ok(())
6441         }
6442
6443         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
6444                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6445
6446                 if msg.channel_id == [0; 32] {
6447                         let channel_ids: Vec<[u8; 32]> = {
6448                                 let per_peer_state = self.per_peer_state.read().unwrap();
6449                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
6450                                 if peer_state_mutex_opt.is_none() { return; }
6451                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
6452                                 let peer_state = &mut *peer_state_lock;
6453                                 peer_state.channel_by_id.keys().cloned().collect()
6454                         };
6455                         for channel_id in channel_ids {
6456                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
6457                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
6458                         }
6459                 } else {
6460                         {
6461                                 // First check if we can advance the channel type and try again.
6462                                 let per_peer_state = self.per_peer_state.read().unwrap();
6463                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
6464                                 if peer_state_mutex_opt.is_none() { return; }
6465                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
6466                                 let peer_state = &mut *peer_state_lock;
6467                                 if let Some(chan) = peer_state.channel_by_id.get_mut(&msg.channel_id) {
6468                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.genesis_hash) {
6469                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
6470                                                         node_id: *counterparty_node_id,
6471                                                         msg,
6472                                                 });
6473                                                 return;
6474                                         }
6475                                 }
6476                         }
6477
6478                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
6479                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
6480                 }
6481         }
6482
6483         fn provided_node_features(&self) -> NodeFeatures {
6484                 provided_node_features(&self.default_configuration)
6485         }
6486
6487         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
6488                 provided_init_features(&self.default_configuration)
6489         }
6490 }
6491
6492 /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
6493 /// [`ChannelManager`].
6494 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
6495         provided_init_features(config).to_context()
6496 }
6497
6498 /// Fetches the set of [`InvoiceFeatures`] flags which are provided by or required by
6499 /// [`ChannelManager`].
6500 ///
6501 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
6502 /// or not. Thus, this method is not public.
6503 #[cfg(any(feature = "_test_utils", test))]
6504 pub(crate) fn provided_invoice_features(config: &UserConfig) -> InvoiceFeatures {
6505         provided_init_features(config).to_context()
6506 }
6507
6508 /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
6509 /// [`ChannelManager`].
6510 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
6511         provided_init_features(config).to_context()
6512 }
6513
6514 /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
6515 /// [`ChannelManager`].
6516 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
6517         ChannelTypeFeatures::from_init(&provided_init_features(config))
6518 }
6519
6520 /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
6521 /// [`ChannelManager`].
6522 pub fn provided_init_features(_config: &UserConfig) -> InitFeatures {
6523         // Note that if new features are added here which other peers may (eventually) require, we
6524         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
6525         // [`ErroringMessageHandler`].
6526         let mut features = InitFeatures::empty();
6527         features.set_data_loss_protect_optional();
6528         features.set_upfront_shutdown_script_optional();
6529         features.set_variable_length_onion_required();
6530         features.set_static_remote_key_required();
6531         features.set_payment_secret_required();
6532         features.set_basic_mpp_optional();
6533         features.set_wumbo_optional();
6534         features.set_shutdown_any_segwit_optional();
6535         features.set_channel_type_optional();
6536         features.set_scid_privacy_optional();
6537         features.set_zero_conf_optional();
6538         #[cfg(anchors)]
6539         { // Attributes are not allowed on if expressions on our current MSRV of 1.41.
6540                 if _config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
6541                         features.set_anchors_zero_fee_htlc_tx_optional();
6542                 }
6543         }
6544         features
6545 }
6546
6547 const SERIALIZATION_VERSION: u8 = 1;
6548 const MIN_SERIALIZATION_VERSION: u8 = 1;
6549
6550 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
6551         (2, fee_base_msat, required),
6552         (4, fee_proportional_millionths, required),
6553         (6, cltv_expiry_delta, required),
6554 });
6555
6556 impl_writeable_tlv_based!(ChannelCounterparty, {
6557         (2, node_id, required),
6558         (4, features, required),
6559         (6, unspendable_punishment_reserve, required),
6560         (8, forwarding_info, option),
6561         (9, outbound_htlc_minimum_msat, option),
6562         (11, outbound_htlc_maximum_msat, option),
6563 });
6564
6565 impl Writeable for ChannelDetails {
6566         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
6567                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
6568                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
6569                 let user_channel_id_low = self.user_channel_id as u64;
6570                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
6571                 write_tlv_fields!(writer, {
6572                         (1, self.inbound_scid_alias, option),
6573                         (2, self.channel_id, required),
6574                         (3, self.channel_type, option),
6575                         (4, self.counterparty, required),
6576                         (5, self.outbound_scid_alias, option),
6577                         (6, self.funding_txo, option),
6578                         (7, self.config, option),
6579                         (8, self.short_channel_id, option),
6580                         (9, self.confirmations, option),
6581                         (10, self.channel_value_satoshis, required),
6582                         (12, self.unspendable_punishment_reserve, option),
6583                         (14, user_channel_id_low, required),
6584                         (16, self.balance_msat, required),
6585                         (18, self.outbound_capacity_msat, required),
6586                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
6587                         // filled in, so we can safely unwrap it here.
6588                         (19, self.next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
6589                         (20, self.inbound_capacity_msat, required),
6590                         (22, self.confirmations_required, option),
6591                         (24, self.force_close_spend_delay, option),
6592                         (26, self.is_outbound, required),
6593                         (28, self.is_channel_ready, required),
6594                         (30, self.is_usable, required),
6595                         (32, self.is_public, required),
6596                         (33, self.inbound_htlc_minimum_msat, option),
6597                         (35, self.inbound_htlc_maximum_msat, option),
6598                         (37, user_channel_id_high_opt, option),
6599                         (39, self.feerate_sat_per_1000_weight, option),
6600                 });
6601                 Ok(())
6602         }
6603 }
6604
6605 impl Readable for ChannelDetails {
6606         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
6607                 _init_and_read_tlv_fields!(reader, {
6608                         (1, inbound_scid_alias, option),
6609                         (2, channel_id, required),
6610                         (3, channel_type, option),
6611                         (4, counterparty, required),
6612                         (5, outbound_scid_alias, option),
6613                         (6, funding_txo, option),
6614                         (7, config, option),
6615                         (8, short_channel_id, option),
6616                         (9, confirmations, option),
6617                         (10, channel_value_satoshis, required),
6618                         (12, unspendable_punishment_reserve, option),
6619                         (14, user_channel_id_low, required),
6620                         (16, balance_msat, required),
6621                         (18, outbound_capacity_msat, required),
6622                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
6623                         // filled in, so we can safely unwrap it here.
6624                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
6625                         (20, inbound_capacity_msat, required),
6626                         (22, confirmations_required, option),
6627                         (24, force_close_spend_delay, option),
6628                         (26, is_outbound, required),
6629                         (28, is_channel_ready, required),
6630                         (30, is_usable, required),
6631                         (32, is_public, required),
6632                         (33, inbound_htlc_minimum_msat, option),
6633                         (35, inbound_htlc_maximum_msat, option),
6634                         (37, user_channel_id_high_opt, option),
6635                         (39, feerate_sat_per_1000_weight, option),
6636                 });
6637
6638                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
6639                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
6640                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
6641                 let user_channel_id = user_channel_id_low as u128 +
6642                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
6643
6644                 Ok(Self {
6645                         inbound_scid_alias,
6646                         channel_id: channel_id.0.unwrap(),
6647                         channel_type,
6648                         counterparty: counterparty.0.unwrap(),
6649                         outbound_scid_alias,
6650                         funding_txo,
6651                         config,
6652                         short_channel_id,
6653                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
6654                         unspendable_punishment_reserve,
6655                         user_channel_id,
6656                         balance_msat: balance_msat.0.unwrap(),
6657                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
6658                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
6659                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
6660                         confirmations_required,
6661                         confirmations,
6662                         force_close_spend_delay,
6663                         is_outbound: is_outbound.0.unwrap(),
6664                         is_channel_ready: is_channel_ready.0.unwrap(),
6665                         is_usable: is_usable.0.unwrap(),
6666                         is_public: is_public.0.unwrap(),
6667                         inbound_htlc_minimum_msat,
6668                         inbound_htlc_maximum_msat,
6669                         feerate_sat_per_1000_weight,
6670                 })
6671         }
6672 }
6673
6674 impl_writeable_tlv_based!(PhantomRouteHints, {
6675         (2, channels, vec_type),
6676         (4, phantom_scid, required),
6677         (6, real_node_pubkey, required),
6678 });
6679
6680 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
6681         (0, Forward) => {
6682                 (0, onion_packet, required),
6683                 (2, short_channel_id, required),
6684         },
6685         (1, Receive) => {
6686                 (0, payment_data, required),
6687                 (1, phantom_shared_secret, option),
6688                 (2, incoming_cltv_expiry, required),
6689         },
6690         (2, ReceiveKeysend) => {
6691                 (0, payment_preimage, required),
6692                 (2, incoming_cltv_expiry, required),
6693         },
6694 ;);
6695
6696 impl_writeable_tlv_based!(PendingHTLCInfo, {
6697         (0, routing, required),
6698         (2, incoming_shared_secret, required),
6699         (4, payment_hash, required),
6700         (6, outgoing_amt_msat, required),
6701         (8, outgoing_cltv_value, required),
6702         (9, incoming_amt_msat, option),
6703 });
6704
6705
6706 impl Writeable for HTLCFailureMsg {
6707         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
6708                 match self {
6709                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
6710                                 0u8.write(writer)?;
6711                                 channel_id.write(writer)?;
6712                                 htlc_id.write(writer)?;
6713                                 reason.write(writer)?;
6714                         },
6715                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
6716                                 channel_id, htlc_id, sha256_of_onion, failure_code
6717                         }) => {
6718                                 1u8.write(writer)?;
6719                                 channel_id.write(writer)?;
6720                                 htlc_id.write(writer)?;
6721                                 sha256_of_onion.write(writer)?;
6722                                 failure_code.write(writer)?;
6723                         },
6724                 }
6725                 Ok(())
6726         }
6727 }
6728
6729 impl Readable for HTLCFailureMsg {
6730         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
6731                 let id: u8 = Readable::read(reader)?;
6732                 match id {
6733                         0 => {
6734                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
6735                                         channel_id: Readable::read(reader)?,
6736                                         htlc_id: Readable::read(reader)?,
6737                                         reason: Readable::read(reader)?,
6738                                 }))
6739                         },
6740                         1 => {
6741                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
6742                                         channel_id: Readable::read(reader)?,
6743                                         htlc_id: Readable::read(reader)?,
6744                                         sha256_of_onion: Readable::read(reader)?,
6745                                         failure_code: Readable::read(reader)?,
6746                                 }))
6747                         },
6748                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
6749                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
6750                         // messages contained in the variants.
6751                         // In version 0.0.101, support for reading the variants with these types was added, and
6752                         // we should migrate to writing these variants when UpdateFailHTLC or
6753                         // UpdateFailMalformedHTLC get TLV fields.
6754                         2 => {
6755                                 let length: BigSize = Readable::read(reader)?;
6756                                 let mut s = FixedLengthReader::new(reader, length.0);
6757                                 let res = Readable::read(&mut s)?;
6758                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
6759                                 Ok(HTLCFailureMsg::Relay(res))
6760                         },
6761                         3 => {
6762                                 let length: BigSize = Readable::read(reader)?;
6763                                 let mut s = FixedLengthReader::new(reader, length.0);
6764                                 let res = Readable::read(&mut s)?;
6765                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
6766                                 Ok(HTLCFailureMsg::Malformed(res))
6767                         },
6768                         _ => Err(DecodeError::UnknownRequiredFeature),
6769                 }
6770         }
6771 }
6772
6773 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
6774         (0, Forward),
6775         (1, Fail),
6776 );
6777
6778 impl_writeable_tlv_based!(HTLCPreviousHopData, {
6779         (0, short_channel_id, required),
6780         (1, phantom_shared_secret, option),
6781         (2, outpoint, required),
6782         (4, htlc_id, required),
6783         (6, incoming_packet_shared_secret, required)
6784 });
6785
6786 impl Writeable for ClaimableHTLC {
6787         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
6788                 let (payment_data, keysend_preimage) = match &self.onion_payload {
6789                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
6790                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
6791                 };
6792                 write_tlv_fields!(writer, {
6793                         (0, self.prev_hop, required),
6794                         (1, self.total_msat, required),
6795                         (2, self.value, required),
6796                         (4, payment_data, option),
6797                         (6, self.cltv_expiry, required),
6798                         (8, keysend_preimage, option),
6799                 });
6800                 Ok(())
6801         }
6802 }
6803
6804 impl Readable for ClaimableHTLC {
6805         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
6806                 let mut prev_hop = crate::util::ser::RequiredWrapper(None);
6807                 let mut value = 0;
6808                 let mut payment_data: Option<msgs::FinalOnionHopData> = None;
6809                 let mut cltv_expiry = 0;
6810                 let mut total_msat = None;
6811                 let mut keysend_preimage: Option<PaymentPreimage> = None;
6812                 read_tlv_fields!(reader, {
6813                         (0, prev_hop, required),
6814                         (1, total_msat, option),
6815                         (2, value, required),
6816                         (4, payment_data, option),
6817                         (6, cltv_expiry, required),
6818                         (8, keysend_preimage, option)
6819                 });
6820                 let onion_payload = match keysend_preimage {
6821                         Some(p) => {
6822                                 if payment_data.is_some() {
6823                                         return Err(DecodeError::InvalidValue)
6824                                 }
6825                                 if total_msat.is_none() {
6826                                         total_msat = Some(value);
6827                                 }
6828                                 OnionPayload::Spontaneous(p)
6829                         },
6830                         None => {
6831                                 if total_msat.is_none() {
6832                                         if payment_data.is_none() {
6833                                                 return Err(DecodeError::InvalidValue)
6834                                         }
6835                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
6836                                 }
6837                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
6838                         },
6839                 };
6840                 Ok(Self {
6841                         prev_hop: prev_hop.0.unwrap(),
6842                         timer_ticks: 0,
6843                         value,
6844                         total_msat: total_msat.unwrap(),
6845                         onion_payload,
6846                         cltv_expiry,
6847                 })
6848         }
6849 }
6850
6851 impl Readable for HTLCSource {
6852         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
6853                 let id: u8 = Readable::read(reader)?;
6854                 match id {
6855                         0 => {
6856                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
6857                                 let mut first_hop_htlc_msat: u64 = 0;
6858                                 let mut path: Option<Vec<RouteHop>> = Some(Vec::new());
6859                                 let mut payment_id = None;
6860                                 let mut payment_secret = None;
6861                                 let mut payment_params: Option<PaymentParameters> = None;
6862                                 read_tlv_fields!(reader, {
6863                                         (0, session_priv, required),
6864                                         (1, payment_id, option),
6865                                         (2, first_hop_htlc_msat, required),
6866                                         (3, payment_secret, option),
6867                                         (4, path, vec_type),
6868                                         (5, payment_params, (option: ReadableArgs, 0)),
6869                                 });
6870                                 if payment_id.is_none() {
6871                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
6872                                         // instead.
6873                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
6874                                 }
6875                                 if path.is_none() || path.as_ref().unwrap().is_empty() {
6876                                         return Err(DecodeError::InvalidValue);
6877                                 }
6878                                 let path = path.unwrap();
6879                                 if let Some(params) = payment_params.as_mut() {
6880                                         if params.final_cltv_expiry_delta == 0 {
6881                                                 params.final_cltv_expiry_delta = path.last().unwrap().cltv_expiry_delta;
6882                                         }
6883                                 }
6884                                 Ok(HTLCSource::OutboundRoute {
6885                                         session_priv: session_priv.0.unwrap(),
6886                                         first_hop_htlc_msat,
6887                                         path,
6888                                         payment_id: payment_id.unwrap(),
6889                                         payment_secret,
6890                                 })
6891                         }
6892                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
6893                         _ => Err(DecodeError::UnknownRequiredFeature),
6894                 }
6895         }
6896 }
6897
6898 impl Writeable for HTLCSource {
6899         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
6900                 match self {
6901                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id, payment_secret } => {
6902                                 0u8.write(writer)?;
6903                                 let payment_id_opt = Some(payment_id);
6904                                 write_tlv_fields!(writer, {
6905                                         (0, session_priv, required),
6906                                         (1, payment_id_opt, option),
6907                                         (2, first_hop_htlc_msat, required),
6908                                         (3, payment_secret, option),
6909                                         (4, *path, vec_type),
6910                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
6911                                  });
6912                         }
6913                         HTLCSource::PreviousHopData(ref field) => {
6914                                 1u8.write(writer)?;
6915                                 field.write(writer)?;
6916                         }
6917                 }
6918                 Ok(())
6919         }
6920 }
6921
6922 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
6923         (0, forward_info, required),
6924         (1, prev_user_channel_id, (default_value, 0)),
6925         (2, prev_short_channel_id, required),
6926         (4, prev_htlc_id, required),
6927         (6, prev_funding_outpoint, required),
6928 });
6929
6930 impl_writeable_tlv_based_enum!(HTLCForwardInfo,
6931         (1, FailHTLC) => {
6932                 (0, htlc_id, required),
6933                 (2, err_packet, required),
6934         };
6935         (0, AddHTLC)
6936 );
6937
6938 impl_writeable_tlv_based!(PendingInboundPayment, {
6939         (0, payment_secret, required),
6940         (2, expiry_time, required),
6941         (4, user_payment_id, required),
6942         (6, payment_preimage, required),
6943         (8, min_value_msat, required),
6944 });
6945
6946 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> Writeable for ChannelManager<M, T, ES, NS, SP, F, R, L>
6947 where
6948         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6949         T::Target: BroadcasterInterface,
6950         ES::Target: EntropySource,
6951         NS::Target: NodeSigner,
6952         SP::Target: SignerProvider,
6953         F::Target: FeeEstimator,
6954         R::Target: Router,
6955         L::Target: Logger,
6956 {
6957         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
6958                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
6959
6960                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
6961
6962                 self.genesis_hash.write(writer)?;
6963                 {
6964                         let best_block = self.best_block.read().unwrap();
6965                         best_block.height().write(writer)?;
6966                         best_block.block_hash().write(writer)?;
6967                 }
6968
6969                 let mut serializable_peer_count: u64 = 0;
6970                 {
6971                         let per_peer_state = self.per_peer_state.read().unwrap();
6972                         let mut unfunded_channels = 0;
6973                         let mut number_of_channels = 0;
6974                         for (_, peer_state_mutex) in per_peer_state.iter() {
6975                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6976                                 let peer_state = &mut *peer_state_lock;
6977                                 if !peer_state.ok_to_remove(false) {
6978                                         serializable_peer_count += 1;
6979                                 }
6980                                 number_of_channels += peer_state.channel_by_id.len();
6981                                 for (_, channel) in peer_state.channel_by_id.iter() {
6982                                         if !channel.is_funding_initiated() {
6983                                                 unfunded_channels += 1;
6984                                         }
6985                                 }
6986                         }
6987
6988                         ((number_of_channels - unfunded_channels) as u64).write(writer)?;
6989
6990                         for (_, peer_state_mutex) in per_peer_state.iter() {
6991                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6992                                 let peer_state = &mut *peer_state_lock;
6993                                 for (_, channel) in peer_state.channel_by_id.iter() {
6994                                         if channel.is_funding_initiated() {
6995                                                 channel.write(writer)?;
6996                                         }
6997                                 }
6998                         }
6999                 }
7000
7001                 {
7002                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
7003                         (forward_htlcs.len() as u64).write(writer)?;
7004                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
7005                                 short_channel_id.write(writer)?;
7006                                 (pending_forwards.len() as u64).write(writer)?;
7007                                 for forward in pending_forwards {
7008                                         forward.write(writer)?;
7009                                 }
7010                         }
7011                 }
7012
7013                 let per_peer_state = self.per_peer_state.write().unwrap();
7014
7015                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
7016                 let claimable_payments = self.claimable_payments.lock().unwrap();
7017                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
7018
7019                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
7020                 (claimable_payments.claimable_htlcs.len() as u64).write(writer)?;
7021                 for (payment_hash, (purpose, previous_hops)) in claimable_payments.claimable_htlcs.iter() {
7022                         payment_hash.write(writer)?;
7023                         (previous_hops.len() as u64).write(writer)?;
7024                         for htlc in previous_hops.iter() {
7025                                 htlc.write(writer)?;
7026                         }
7027                         htlc_purposes.push(purpose);
7028                 }
7029
7030                 let mut monitor_update_blocked_actions_per_peer = None;
7031                 let mut peer_states = Vec::new();
7032                 for (_, peer_state_mutex) in per_peer_state.iter() {
7033                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
7034                         // of a lockorder violation deadlock - no other thread can be holding any
7035                         // per_peer_state lock at all.
7036                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
7037                 }
7038
7039                 (serializable_peer_count).write(writer)?;
7040                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
7041                         // Peers which we have no channels to should be dropped once disconnected. As we
7042                         // disconnect all peers when shutting down and serializing the ChannelManager, we
7043                         // consider all peers as disconnected here. There's therefore no need write peers with
7044                         // no channels.
7045                         if !peer_state.ok_to_remove(false) {
7046                                 peer_pubkey.write(writer)?;
7047                                 peer_state.latest_features.write(writer)?;
7048                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
7049                                         monitor_update_blocked_actions_per_peer
7050                                                 .get_or_insert_with(Vec::new)
7051                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
7052                                 }
7053                         }
7054                 }
7055
7056                 let events = self.pending_events.lock().unwrap();
7057                 (events.len() as u64).write(writer)?;
7058                 for event in events.iter() {
7059                         event.write(writer)?;
7060                 }
7061
7062                 let background_events = self.pending_background_events.lock().unwrap();
7063                 (background_events.len() as u64).write(writer)?;
7064                 for event in background_events.iter() {
7065                         match event {
7066                                 BackgroundEvent::ClosingMonitorUpdate((funding_txo, monitor_update)) => {
7067                                         0u8.write(writer)?;
7068                                         funding_txo.write(writer)?;
7069                                         monitor_update.write(writer)?;
7070                                 },
7071                         }
7072                 }
7073
7074                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
7075                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
7076                 // likely to be identical.
7077                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
7078                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
7079
7080                 (pending_inbound_payments.len() as u64).write(writer)?;
7081                 for (hash, pending_payment) in pending_inbound_payments.iter() {
7082                         hash.write(writer)?;
7083                         pending_payment.write(writer)?;
7084                 }
7085
7086                 // For backwards compat, write the session privs and their total length.
7087                 let mut num_pending_outbounds_compat: u64 = 0;
7088                 for (_, outbound) in pending_outbound_payments.iter() {
7089                         if !outbound.is_fulfilled() && !outbound.abandoned() {
7090                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
7091                         }
7092                 }
7093                 num_pending_outbounds_compat.write(writer)?;
7094                 for (_, outbound) in pending_outbound_payments.iter() {
7095                         match outbound {
7096                                 PendingOutboundPayment::Legacy { session_privs } |
7097                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
7098                                         for session_priv in session_privs.iter() {
7099                                                 session_priv.write(writer)?;
7100                                         }
7101                                 }
7102                                 PendingOutboundPayment::Fulfilled { .. } => {},
7103                                 PendingOutboundPayment::Abandoned { .. } => {},
7104                         }
7105                 }
7106
7107                 // Encode without retry info for 0.0.101 compatibility.
7108                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
7109                 for (id, outbound) in pending_outbound_payments.iter() {
7110                         match outbound {
7111                                 PendingOutboundPayment::Legacy { session_privs } |
7112                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
7113                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
7114                                 },
7115                                 _ => {},
7116                         }
7117                 }
7118
7119                 let mut pending_intercepted_htlcs = None;
7120                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
7121                 if our_pending_intercepts.len() != 0 {
7122                         pending_intercepted_htlcs = Some(our_pending_intercepts);
7123                 }
7124
7125                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
7126                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
7127                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
7128                         // map. Thus, if there are no entries we skip writing a TLV for it.
7129                         pending_claiming_payments = None;
7130                 }
7131
7132                 write_tlv_fields!(writer, {
7133                         (1, pending_outbound_payments_no_retry, required),
7134                         (2, pending_intercepted_htlcs, option),
7135                         (3, pending_outbound_payments, required),
7136                         (4, pending_claiming_payments, option),
7137                         (5, self.our_network_pubkey, required),
7138                         (6, monitor_update_blocked_actions_per_peer, option),
7139                         (7, self.fake_scid_rand_bytes, required),
7140                         (9, htlc_purposes, vec_type),
7141                         (11, self.probing_cookie_secret, required),
7142                 });
7143
7144                 Ok(())
7145         }
7146 }
7147
7148 /// Arguments for the creation of a ChannelManager that are not deserialized.
7149 ///
7150 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
7151 /// is:
7152 /// 1) Deserialize all stored [`ChannelMonitor`]s.
7153 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
7154 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
7155 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
7156 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
7157 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
7158 ///    same way you would handle a [`chain::Filter`] call using
7159 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
7160 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
7161 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
7162 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
7163 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
7164 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
7165 ///    the next step.
7166 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
7167 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
7168 ///
7169 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
7170 /// call any other methods on the newly-deserialized [`ChannelManager`].
7171 ///
7172 /// Note that because some channels may be closed during deserialization, it is critical that you
7173 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
7174 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
7175 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
7176 /// not force-close the same channels but consider them live), you may end up revoking a state for
7177 /// which you've already broadcasted the transaction.
7178 ///
7179 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
7180 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
7181 where
7182         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7183         T::Target: BroadcasterInterface,
7184         ES::Target: EntropySource,
7185         NS::Target: NodeSigner,
7186         SP::Target: SignerProvider,
7187         F::Target: FeeEstimator,
7188         R::Target: Router,
7189         L::Target: Logger,
7190 {
7191         /// A cryptographically secure source of entropy.
7192         pub entropy_source: ES,
7193
7194         /// A signer that is able to perform node-scoped cryptographic operations.
7195         pub node_signer: NS,
7196
7197         /// The keys provider which will give us relevant keys. Some keys will be loaded during
7198         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
7199         /// signing data.
7200         pub signer_provider: SP,
7201
7202         /// The fee_estimator for use in the ChannelManager in the future.
7203         ///
7204         /// No calls to the FeeEstimator will be made during deserialization.
7205         pub fee_estimator: F,
7206         /// The chain::Watch for use in the ChannelManager in the future.
7207         ///
7208         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
7209         /// you have deserialized ChannelMonitors separately and will add them to your
7210         /// chain::Watch after deserializing this ChannelManager.
7211         pub chain_monitor: M,
7212
7213         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
7214         /// used to broadcast the latest local commitment transactions of channels which must be
7215         /// force-closed during deserialization.
7216         pub tx_broadcaster: T,
7217         /// The router which will be used in the ChannelManager in the future for finding routes
7218         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
7219         ///
7220         /// No calls to the router will be made during deserialization.
7221         pub router: R,
7222         /// The Logger for use in the ChannelManager and which may be used to log information during
7223         /// deserialization.
7224         pub logger: L,
7225         /// Default settings used for new channels. Any existing channels will continue to use the
7226         /// runtime settings which were stored when the ChannelManager was serialized.
7227         pub default_config: UserConfig,
7228
7229         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
7230         /// value.get_funding_txo() should be the key).
7231         ///
7232         /// If a monitor is inconsistent with the channel state during deserialization the channel will
7233         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
7234         /// is true for missing channels as well. If there is a monitor missing for which we find
7235         /// channel data Err(DecodeError::InvalidValue) will be returned.
7236         ///
7237         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
7238         /// this struct.
7239         ///
7240         /// This is not exported to bindings users because we have no HashMap bindings
7241         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>,
7242 }
7243
7244 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
7245                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
7246 where
7247         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7248         T::Target: BroadcasterInterface,
7249         ES::Target: EntropySource,
7250         NS::Target: NodeSigner,
7251         SP::Target: SignerProvider,
7252         F::Target: FeeEstimator,
7253         R::Target: Router,
7254         L::Target: Logger,
7255 {
7256         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
7257         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
7258         /// populate a HashMap directly from C.
7259         pub fn new(entropy_source: ES, node_signer: NS, signer_provider: SP, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, default_config: UserConfig,
7260                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>) -> Self {
7261                 Self {
7262                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
7263                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
7264                 }
7265         }
7266 }
7267
7268 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
7269 // SipmleArcChannelManager type:
7270 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
7271         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
7272 where
7273         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7274         T::Target: BroadcasterInterface,
7275         ES::Target: EntropySource,
7276         NS::Target: NodeSigner,
7277         SP::Target: SignerProvider,
7278         F::Target: FeeEstimator,
7279         R::Target: Router,
7280         L::Target: Logger,
7281 {
7282         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
7283                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
7284                 Ok((blockhash, Arc::new(chan_manager)))
7285         }
7286 }
7287
7288 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
7289         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
7290 where
7291         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7292         T::Target: BroadcasterInterface,
7293         ES::Target: EntropySource,
7294         NS::Target: NodeSigner,
7295         SP::Target: SignerProvider,
7296         F::Target: FeeEstimator,
7297         R::Target: Router,
7298         L::Target: Logger,
7299 {
7300         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
7301                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
7302
7303                 let genesis_hash: BlockHash = Readable::read(reader)?;
7304                 let best_block_height: u32 = Readable::read(reader)?;
7305                 let best_block_hash: BlockHash = Readable::read(reader)?;
7306
7307                 let mut failed_htlcs = Vec::new();
7308
7309                 let channel_count: u64 = Readable::read(reader)?;
7310                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
7311                 let mut peer_channels: HashMap<PublicKey, HashMap<[u8; 32], Channel<<SP::Target as SignerProvider>::Signer>>> = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
7312                 let mut id_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
7313                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
7314                 let mut channel_closures = Vec::new();
7315                 for _ in 0..channel_count {
7316                         let mut channel: Channel<<SP::Target as SignerProvider>::Signer> = Channel::read(reader, (
7317                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
7318                         ))?;
7319                         let funding_txo = channel.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
7320                         funding_txo_set.insert(funding_txo.clone());
7321                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
7322                                 if channel.get_cur_holder_commitment_transaction_number() < monitor.get_cur_holder_commitment_number() ||
7323                                                 channel.get_revoked_counterparty_commitment_transaction_number() < monitor.get_min_seen_secret() ||
7324                                                 channel.get_cur_counterparty_commitment_transaction_number() < monitor.get_cur_counterparty_commitment_number() ||
7325                                                 channel.get_latest_monitor_update_id() > monitor.get_latest_update_id() {
7326                                         // If the channel is ahead of the monitor, return InvalidValue:
7327                                         log_error!(args.logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
7328                                         log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
7329                                                 log_bytes!(channel.channel_id()), monitor.get_latest_update_id(), channel.get_latest_monitor_update_id());
7330                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
7331                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
7332                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
7333                                         log_error!(args.logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
7334                                         return Err(DecodeError::InvalidValue);
7335                                 } else if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
7336                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
7337                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
7338                                                 channel.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
7339                                         // But if the channel is behind of the monitor, close the channel:
7340                                         log_error!(args.logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
7341                                         log_error!(args.logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
7342                                         log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
7343                                                 log_bytes!(channel.channel_id()), monitor.get_latest_update_id(), channel.get_latest_monitor_update_id());
7344                                         let (_, mut new_failed_htlcs) = channel.force_shutdown(true);
7345                                         failed_htlcs.append(&mut new_failed_htlcs);
7346                                         monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
7347                                         channel_closures.push(events::Event::ChannelClosed {
7348                                                 channel_id: channel.channel_id(),
7349                                                 user_channel_id: channel.get_user_id(),
7350                                                 reason: ClosureReason::OutdatedChannelManager
7351                                         });
7352                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
7353                                                 let mut found_htlc = false;
7354                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
7355                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
7356                                                 }
7357                                                 if !found_htlc {
7358                                                         // If we have some HTLCs in the channel which are not present in the newer
7359                                                         // ChannelMonitor, they have been removed and should be failed back to
7360                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
7361                                                         // were actually claimed we'd have generated and ensured the previous-hop
7362                                                         // claim update ChannelMonitor updates were persisted prior to persising
7363                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
7364                                                         // backwards leg of the HTLC will simply be rejected.
7365                                                         log_info!(args.logger,
7366                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
7367                                                                 log_bytes!(channel.channel_id()), log_bytes!(payment_hash.0));
7368                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.get_counterparty_node_id(), channel.channel_id()));
7369                                                 }
7370                                         }
7371                                 } else {
7372                                         log_info!(args.logger, "Successfully loaded channel {}", log_bytes!(channel.channel_id()));
7373                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
7374                                                 short_to_chan_info.insert(short_channel_id, (channel.get_counterparty_node_id(), channel.channel_id()));
7375                                         }
7376                                         if channel.is_funding_initiated() {
7377                                                 id_to_peer.insert(channel.channel_id(), channel.get_counterparty_node_id());
7378                                         }
7379                                         match peer_channels.entry(channel.get_counterparty_node_id()) {
7380                                                 hash_map::Entry::Occupied(mut entry) => {
7381                                                         let by_id_map = entry.get_mut();
7382                                                         by_id_map.insert(channel.channel_id(), channel);
7383                                                 },
7384                                                 hash_map::Entry::Vacant(entry) => {
7385                                                         let mut by_id_map = HashMap::new();
7386                                                         by_id_map.insert(channel.channel_id(), channel);
7387                                                         entry.insert(by_id_map);
7388                                                 }
7389                                         }
7390                                 }
7391                         } else if channel.is_awaiting_initial_mon_persist() {
7392                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
7393                                 // was in-progress, we never broadcasted the funding transaction and can still
7394                                 // safely discard the channel.
7395                                 let _ = channel.force_shutdown(false);
7396                                 channel_closures.push(events::Event::ChannelClosed {
7397                                         channel_id: channel.channel_id(),
7398                                         user_channel_id: channel.get_user_id(),
7399                                         reason: ClosureReason::DisconnectedPeer,
7400                                 });
7401                         } else {
7402                                 log_error!(args.logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", log_bytes!(channel.channel_id()));
7403                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
7404                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
7405                                 log_error!(args.logger, " Without the ChannelMonitor we cannot continue without risking funds.");
7406                                 log_error!(args.logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
7407                                 return Err(DecodeError::InvalidValue);
7408                         }
7409                 }
7410
7411                 for (funding_txo, monitor) in args.channel_monitors.iter_mut() {
7412                         if !funding_txo_set.contains(funding_txo) {
7413                                 log_info!(args.logger, "Broadcasting latest holder commitment transaction for closed channel {}", log_bytes!(funding_txo.to_channel_id()));
7414                                 monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
7415                         }
7416                 }
7417
7418                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
7419                 let forward_htlcs_count: u64 = Readable::read(reader)?;
7420                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
7421                 for _ in 0..forward_htlcs_count {
7422                         let short_channel_id = Readable::read(reader)?;
7423                         let pending_forwards_count: u64 = Readable::read(reader)?;
7424                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
7425                         for _ in 0..pending_forwards_count {
7426                                 pending_forwards.push(Readable::read(reader)?);
7427                         }
7428                         forward_htlcs.insert(short_channel_id, pending_forwards);
7429                 }
7430
7431                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
7432                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
7433                 for _ in 0..claimable_htlcs_count {
7434                         let payment_hash = Readable::read(reader)?;
7435                         let previous_hops_len: u64 = Readable::read(reader)?;
7436                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
7437                         for _ in 0..previous_hops_len {
7438                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
7439                         }
7440                         claimable_htlcs_list.push((payment_hash, previous_hops));
7441                 }
7442
7443                 let peer_count: u64 = Readable::read(reader)?;
7444                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState<<SP::Target as SignerProvider>::Signer>>)>()));
7445                 for _ in 0..peer_count {
7446                         let peer_pubkey = Readable::read(reader)?;
7447                         let peer_state = PeerState {
7448                                 channel_by_id: peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new()),
7449                                 latest_features: Readable::read(reader)?,
7450                                 pending_msg_events: Vec::new(),
7451                                 monitor_update_blocked_actions: BTreeMap::new(),
7452                                 is_connected: false,
7453                         };
7454                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
7455                 }
7456
7457                 let event_count: u64 = Readable::read(reader)?;
7458                 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>()));
7459                 for _ in 0..event_count {
7460                         match MaybeReadable::read(reader)? {
7461                                 Some(event) => pending_events_read.push(event),
7462                                 None => continue,
7463                         }
7464                 }
7465
7466                 let background_event_count: u64 = Readable::read(reader)?;
7467                 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>()));
7468                 for _ in 0..background_event_count {
7469                         match <u8 as Readable>::read(reader)? {
7470                                 0 => pending_background_events_read.push(BackgroundEvent::ClosingMonitorUpdate((Readable::read(reader)?, Readable::read(reader)?))),
7471                                 _ => return Err(DecodeError::InvalidValue),
7472                         }
7473                 }
7474
7475                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
7476                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
7477
7478                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
7479                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
7480                 for _ in 0..pending_inbound_payment_count {
7481                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
7482                                 return Err(DecodeError::InvalidValue);
7483                         }
7484                 }
7485
7486                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
7487                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
7488                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
7489                 for _ in 0..pending_outbound_payments_count_compat {
7490                         let session_priv = Readable::read(reader)?;
7491                         let payment = PendingOutboundPayment::Legacy {
7492                                 session_privs: [session_priv].iter().cloned().collect()
7493                         };
7494                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
7495                                 return Err(DecodeError::InvalidValue)
7496                         };
7497                 }
7498
7499                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
7500                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
7501                 let mut pending_outbound_payments = None;
7502                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
7503                 let mut received_network_pubkey: Option<PublicKey> = None;
7504                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
7505                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
7506                 let mut claimable_htlc_purposes = None;
7507                 let mut pending_claiming_payments = Some(HashMap::new());
7508                 let mut monitor_update_blocked_actions_per_peer = Some(Vec::new());
7509                 read_tlv_fields!(reader, {
7510                         (1, pending_outbound_payments_no_retry, option),
7511                         (2, pending_intercepted_htlcs, option),
7512                         (3, pending_outbound_payments, option),
7513                         (4, pending_claiming_payments, option),
7514                         (5, received_network_pubkey, option),
7515                         (6, monitor_update_blocked_actions_per_peer, option),
7516                         (7, fake_scid_rand_bytes, option),
7517                         (9, claimable_htlc_purposes, vec_type),
7518                         (11, probing_cookie_secret, option),
7519                 });
7520                 if fake_scid_rand_bytes.is_none() {
7521                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
7522                 }
7523
7524                 if probing_cookie_secret.is_none() {
7525                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
7526                 }
7527
7528                 if !channel_closures.is_empty() {
7529                         pending_events_read.append(&mut channel_closures);
7530                 }
7531
7532                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
7533                         pending_outbound_payments = Some(pending_outbound_payments_compat);
7534                 } else if pending_outbound_payments.is_none() {
7535                         let mut outbounds = HashMap::new();
7536                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
7537                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
7538                         }
7539                         pending_outbound_payments = Some(outbounds);
7540                 }
7541                 let pending_outbounds = OutboundPayments {
7542                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
7543                         retry_lock: Mutex::new(())
7544                 };
7545
7546                 {
7547                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
7548                         // ChannelMonitor data for any channels for which we do not have authorative state
7549                         // (i.e. those for which we just force-closed above or we otherwise don't have a
7550                         // corresponding `Channel` at all).
7551                         // This avoids several edge-cases where we would otherwise "forget" about pending
7552                         // payments which are still in-flight via their on-chain state.
7553                         // We only rebuild the pending payments map if we were most recently serialized by
7554                         // 0.0.102+
7555                         for (_, monitor) in args.channel_monitors.iter() {
7556                                 if id_to_peer.get(&monitor.get_funding_txo().0.to_channel_id()).is_none() {
7557                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
7558                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, payment_secret, .. } = htlc_source {
7559                                                         if path.is_empty() {
7560                                                                 log_error!(args.logger, "Got an empty path for a pending payment");
7561                                                                 return Err(DecodeError::InvalidValue);
7562                                                         }
7563
7564                                                         let path_amt = path.last().unwrap().fee_msat;
7565                                                         let mut session_priv_bytes = [0; 32];
7566                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
7567                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
7568                                                                 hash_map::Entry::Occupied(mut entry) => {
7569                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
7570                                                                         log_info!(args.logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
7571                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), log_bytes!(htlc.payment_hash.0));
7572                                                                 },
7573                                                                 hash_map::Entry::Vacant(entry) => {
7574                                                                         let path_fee = path.get_path_fees();
7575                                                                         entry.insert(PendingOutboundPayment::Retryable {
7576                                                                                 retry_strategy: None,
7577                                                                                 attempts: PaymentAttempts::new(),
7578                                                                                 payment_params: None,
7579                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
7580                                                                                 payment_hash: htlc.payment_hash,
7581                                                                                 payment_secret,
7582                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
7583                                                                                 pending_amt_msat: path_amt,
7584                                                                                 pending_fee_msat: Some(path_fee),
7585                                                                                 total_msat: path_amt,
7586                                                                                 starting_block_height: best_block_height,
7587                                                                         });
7588                                                                         log_info!(args.logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
7589                                                                                 path_amt, log_bytes!(htlc.payment_hash.0),  log_bytes!(session_priv_bytes));
7590                                                                 }
7591                                                         }
7592                                                 }
7593                                         }
7594                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
7595                                                 match htlc_source {
7596                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
7597                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
7598                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
7599                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
7600                                                                 };
7601                                                                 // The ChannelMonitor is now responsible for this HTLC's
7602                                                                 // failure/success and will let us know what its outcome is. If we
7603                                                                 // still have an entry for this HTLC in `forward_htlcs` or
7604                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
7605                                                                 // the monitor was when forwarding the payment.
7606                                                                 forward_htlcs.retain(|_, forwards| {
7607                                                                         forwards.retain(|forward| {
7608                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
7609                                                                                         if pending_forward_matches_htlc(&htlc_info) {
7610                                                                                                 log_info!(args.logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
7611                                                                                                         log_bytes!(htlc.payment_hash.0), log_bytes!(monitor.get_funding_txo().0.to_channel_id()));
7612                                                                                                 false
7613                                                                                         } else { true }
7614                                                                                 } else { true }
7615                                                                         });
7616                                                                         !forwards.is_empty()
7617                                                                 });
7618                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
7619                                                                         if pending_forward_matches_htlc(&htlc_info) {
7620                                                                                 log_info!(args.logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
7621                                                                                         log_bytes!(htlc.payment_hash.0), log_bytes!(monitor.get_funding_txo().0.to_channel_id()));
7622                                                                                 pending_events_read.retain(|event| {
7623                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
7624                                                                                                 intercepted_id != ev_id
7625                                                                                         } else { true }
7626                                                                                 });
7627                                                                                 false
7628                                                                         } else { true }
7629                                                                 });
7630                                                         },
7631                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
7632                                                                 if let Some(preimage) = preimage_opt {
7633                                                                         let pending_events = Mutex::new(pending_events_read);
7634                                                                         // Note that we set `from_onchain` to "false" here,
7635                                                                         // deliberately keeping the pending payment around forever.
7636                                                                         // Given it should only occur when we have a channel we're
7637                                                                         // force-closing for being stale that's okay.
7638                                                                         // The alternative would be to wipe the state when claiming,
7639                                                                         // generating a `PaymentPathSuccessful` event but regenerating
7640                                                                         // it and the `PaymentSent` on every restart until the
7641                                                                         // `ChannelMonitor` is removed.
7642                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv, path, false, &pending_events, &args.logger);
7643                                                                         pending_events_read = pending_events.into_inner().unwrap();
7644                                                                 }
7645                                                         },
7646                                                 }
7647                                         }
7648                                 }
7649                         }
7650                 }
7651
7652                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
7653                         // If we have pending HTLCs to forward, assume we either dropped a
7654                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
7655                         // shut down before the timer hit. Either way, set the time_forwardable to a small
7656                         // constant as enough time has likely passed that we should simply handle the forwards
7657                         // now, or at least after the user gets a chance to reconnect to our peers.
7658                         pending_events_read.push(events::Event::PendingHTLCsForwardable {
7659                                 time_forwardable: Duration::from_secs(2),
7660                         });
7661                 }
7662
7663                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
7664                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
7665
7666                 let mut claimable_htlcs = HashMap::with_capacity(claimable_htlcs_list.len());
7667                 if let Some(mut purposes) = claimable_htlc_purposes {
7668                         if purposes.len() != claimable_htlcs_list.len() {
7669                                 return Err(DecodeError::InvalidValue);
7670                         }
7671                         for (purpose, (payment_hash, previous_hops)) in purposes.drain(..).zip(claimable_htlcs_list.drain(..)) {
7672                                 claimable_htlcs.insert(payment_hash, (purpose, previous_hops));
7673                         }
7674                 } else {
7675                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
7676                         // include a `_legacy_hop_data` in the `OnionPayload`.
7677                         for (payment_hash, previous_hops) in claimable_htlcs_list.drain(..) {
7678                                 if previous_hops.is_empty() {
7679                                         return Err(DecodeError::InvalidValue);
7680                                 }
7681                                 let purpose = match &previous_hops[0].onion_payload {
7682                                         OnionPayload::Invoice { _legacy_hop_data } => {
7683                                                 if let Some(hop_data) = _legacy_hop_data {
7684                                                         events::PaymentPurpose::InvoicePayment {
7685                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
7686                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
7687                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
7688                                                                                 Ok((payment_preimage, _)) => payment_preimage,
7689                                                                                 Err(()) => {
7690                                                                                         log_error!(args.logger, "Failed to read claimable payment data for HTLC with payment hash {} - was not a pending inbound payment and didn't match our payment key", log_bytes!(payment_hash.0));
7691                                                                                         return Err(DecodeError::InvalidValue);
7692                                                                                 }
7693                                                                         }
7694                                                                 },
7695                                                                 payment_secret: hop_data.payment_secret,
7696                                                         }
7697                                                 } else { return Err(DecodeError::InvalidValue); }
7698                                         },
7699                                         OnionPayload::Spontaneous(payment_preimage) =>
7700                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
7701                                 };
7702                                 claimable_htlcs.insert(payment_hash, (purpose, previous_hops));
7703                         }
7704                 }
7705
7706                 let mut secp_ctx = Secp256k1::new();
7707                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
7708
7709                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
7710                         Ok(key) => key,
7711                         Err(()) => return Err(DecodeError::InvalidValue)
7712                 };
7713                 if let Some(network_pubkey) = received_network_pubkey {
7714                         if network_pubkey != our_network_pubkey {
7715                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
7716                                 return Err(DecodeError::InvalidValue);
7717                         }
7718                 }
7719
7720                 let mut outbound_scid_aliases = HashSet::new();
7721                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
7722                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7723                         let peer_state = &mut *peer_state_lock;
7724                         for (chan_id, chan) in peer_state.channel_by_id.iter_mut() {
7725                                 if chan.outbound_scid_alias() == 0 {
7726                                         let mut outbound_scid_alias;
7727                                         loop {
7728                                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias
7729                                                         .get_fake_scid(best_block_height, &genesis_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
7730                                                 if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
7731                                         }
7732                                         chan.set_outbound_scid_alias(outbound_scid_alias);
7733                                 } else if !outbound_scid_aliases.insert(chan.outbound_scid_alias()) {
7734                                         // Note that in rare cases its possible to hit this while reading an older
7735                                         // channel if we just happened to pick a colliding outbound alias above.
7736                                         log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.outbound_scid_alias());
7737                                         return Err(DecodeError::InvalidValue);
7738                                 }
7739                                 if chan.is_usable() {
7740                                         if short_to_chan_info.insert(chan.outbound_scid_alias(), (chan.get_counterparty_node_id(), *chan_id)).is_some() {
7741                                                 // Note that in rare cases its possible to hit this while reading an older
7742                                                 // channel if we just happened to pick a colliding outbound alias above.
7743                                                 log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.outbound_scid_alias());
7744                                                 return Err(DecodeError::InvalidValue);
7745                                         }
7746                                 }
7747                         }
7748                 }
7749
7750                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
7751
7752                 for (_, monitor) in args.channel_monitors.iter() {
7753                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
7754                                 if let Some((payment_purpose, claimable_htlcs)) = claimable_htlcs.remove(&payment_hash) {
7755                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", log_bytes!(payment_hash.0));
7756                                         let mut claimable_amt_msat = 0;
7757                                         let mut receiver_node_id = Some(our_network_pubkey);
7758                                         let phantom_shared_secret = claimable_htlcs[0].prev_hop.phantom_shared_secret;
7759                                         if phantom_shared_secret.is_some() {
7760                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
7761                                                         .expect("Failed to get node_id for phantom node recipient");
7762                                                 receiver_node_id = Some(phantom_pubkey)
7763                                         }
7764                                         for claimable_htlc in claimable_htlcs {
7765                                                 claimable_amt_msat += claimable_htlc.value;
7766
7767                                                 // Add a holding-cell claim of the payment to the Channel, which should be
7768                                                 // applied ~immediately on peer reconnection. Because it won't generate a
7769                                                 // new commitment transaction we can just provide the payment preimage to
7770                                                 // the corresponding ChannelMonitor and nothing else.
7771                                                 //
7772                                                 // We do so directly instead of via the normal ChannelMonitor update
7773                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
7774                                                 // we're not allowed to call it directly yet. Further, we do the update
7775                                                 // without incrementing the ChannelMonitor update ID as there isn't any
7776                                                 // reason to.
7777                                                 // If we were to generate a new ChannelMonitor update ID here and then
7778                                                 // crash before the user finishes block connect we'd end up force-closing
7779                                                 // this channel as well. On the flip side, there's no harm in restarting
7780                                                 // without the new monitor persisted - we'll end up right back here on
7781                                                 // restart.
7782                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
7783                                                 if let Some(peer_node_id) = id_to_peer.get(&previous_channel_id){
7784                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
7785                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7786                                                         let peer_state = &mut *peer_state_lock;
7787                                                         if let Some(channel) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
7788                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &args.logger);
7789                                                         }
7790                                                 }
7791                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
7792                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
7793                                                 }
7794                                         }
7795                                         pending_events_read.push(events::Event::PaymentClaimed {
7796                                                 receiver_node_id,
7797                                                 payment_hash,
7798                                                 purpose: payment_purpose,
7799                                                 amount_msat: claimable_amt_msat,
7800                                         });
7801                                 }
7802                         }
7803                 }
7804
7805                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
7806                         if let Some(peer_state) = per_peer_state.get_mut(&node_id) {
7807                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
7808                         } else {
7809                                 log_error!(args.logger, "Got blocked actions without a per-peer-state for {}", node_id);
7810                                 return Err(DecodeError::InvalidValue);
7811                         }
7812                 }
7813
7814                 let channel_manager = ChannelManager {
7815                         genesis_hash,
7816                         fee_estimator: bounded_fee_estimator,
7817                         chain_monitor: args.chain_monitor,
7818                         tx_broadcaster: args.tx_broadcaster,
7819                         router: args.router,
7820
7821                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
7822
7823                         inbound_payment_key: expanded_inbound_key,
7824                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
7825                         pending_outbound_payments: pending_outbounds,
7826                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
7827
7828                         forward_htlcs: Mutex::new(forward_htlcs),
7829                         claimable_payments: Mutex::new(ClaimablePayments { claimable_htlcs, pending_claiming_payments: pending_claiming_payments.unwrap() }),
7830                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
7831                         id_to_peer: Mutex::new(id_to_peer),
7832                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
7833                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
7834
7835                         probing_cookie_secret: probing_cookie_secret.unwrap(),
7836
7837                         our_network_pubkey,
7838                         secp_ctx,
7839
7840                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
7841
7842                         per_peer_state: FairRwLock::new(per_peer_state),
7843
7844                         pending_events: Mutex::new(pending_events_read),
7845                         pending_background_events: Mutex::new(pending_background_events_read),
7846                         total_consistency_lock: RwLock::new(()),
7847                         persistence_notifier: Notifier::new(),
7848
7849                         entropy_source: args.entropy_source,
7850                         node_signer: args.node_signer,
7851                         signer_provider: args.signer_provider,
7852
7853                         logger: args.logger,
7854                         default_configuration: args.default_config,
7855                 };
7856
7857                 for htlc_source in failed_htlcs.drain(..) {
7858                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
7859                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
7860                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
7861                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
7862                 }
7863
7864                 //TODO: Broadcast channel update for closed channels, but only after we've made a
7865                 //connection or two.
7866
7867                 Ok((best_block_hash.clone(), channel_manager))
7868         }
7869 }
7870
7871 #[cfg(test)]
7872 mod tests {
7873         use bitcoin::hashes::Hash;
7874         use bitcoin::hashes::sha256::Hash as Sha256;
7875         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
7876         use core::time::Duration;
7877         use core::sync::atomic::Ordering;
7878         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
7879         use crate::ln::channelmanager::{inbound_payment, PaymentId, PaymentSendFailure, InterceptId};
7880         use crate::ln::functional_test_utils::*;
7881         use crate::ln::msgs;
7882         use crate::ln::msgs::ChannelMessageHandler;
7883         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
7884         use crate::util::errors::APIError;
7885         use crate::util::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
7886         use crate::util::test_utils;
7887         use crate::util::config::ChannelConfig;
7888         use crate::chain::keysinterface::EntropySource;
7889
7890         #[test]
7891         fn test_notify_limits() {
7892                 // Check that a few cases which don't require the persistence of a new ChannelManager,
7893                 // indeed, do not cause the persistence of a new ChannelManager.
7894                 let chanmon_cfgs = create_chanmon_cfgs(3);
7895                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7896                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7897                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7898
7899                 // All nodes start with a persistable update pending as `create_network` connects each node
7900                 // with all other nodes to make most tests simpler.
7901                 assert!(nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7902                 assert!(nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7903                 assert!(nodes[2].node.await_persistable_update_timeout(Duration::from_millis(1)));
7904
7905                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7906
7907                 // We check that the channel info nodes have doesn't change too early, even though we try
7908                 // to connect messages with new values
7909                 chan.0.contents.fee_base_msat *= 2;
7910                 chan.1.contents.fee_base_msat *= 2;
7911                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
7912                         &nodes[1].node.get_our_node_id()).pop().unwrap();
7913                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
7914                         &nodes[0].node.get_our_node_id()).pop().unwrap();
7915
7916                 // The first two nodes (which opened a channel) should now require fresh persistence
7917                 assert!(nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7918                 assert!(nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7919                 // ... but the last node should not.
7920                 assert!(!nodes[2].node.await_persistable_update_timeout(Duration::from_millis(1)));
7921                 // After persisting the first two nodes they should no longer need fresh persistence.
7922                 assert!(!nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7923                 assert!(!nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7924
7925                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
7926                 // about the channel.
7927                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
7928                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
7929                 assert!(!nodes[2].node.await_persistable_update_timeout(Duration::from_millis(1)));
7930
7931                 // The nodes which are a party to the channel should also ignore messages from unrelated
7932                 // parties.
7933                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
7934                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
7935                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
7936                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
7937                 assert!(!nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7938                 assert!(!nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7939
7940                 // At this point the channel info given by peers should still be the same.
7941                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
7942                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
7943
7944                 // An earlier version of handle_channel_update didn't check the directionality of the
7945                 // update message and would always update the local fee info, even if our peer was
7946                 // (spuriously) forwarding us our own channel_update.
7947                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
7948                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
7949                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
7950
7951                 // First deliver each peers' own message, checking that the node doesn't need to be
7952                 // persisted and that its channel info remains the same.
7953                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
7954                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
7955                 assert!(!nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7956                 assert!(!nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7957                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
7958                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
7959
7960                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
7961                 // the channel info has updated.
7962                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
7963                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
7964                 assert!(nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7965                 assert!(nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7966                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
7967                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
7968         }
7969
7970         #[test]
7971         fn test_keysend_dup_hash_partial_mpp() {
7972                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
7973                 // expected.
7974                 let chanmon_cfgs = create_chanmon_cfgs(2);
7975                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7976                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7977                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7978                 create_announced_chan_between_nodes(&nodes, 0, 1);
7979
7980                 // First, send a partial MPP payment.
7981                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
7982                 let mut mpp_route = route.clone();
7983                 mpp_route.paths.push(mpp_route.paths[0].clone());
7984
7985                 let payment_id = PaymentId([42; 32]);
7986                 // Use the utility function send_payment_along_path to send the payment with MPP data which
7987                 // indicates there are more HTLCs coming.
7988                 let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match.
7989                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &mpp_route).unwrap();
7990                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash, &Some(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
7991                 check_added_monitors!(nodes[0], 1);
7992                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7993                 assert_eq!(events.len(), 1);
7994                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
7995
7996                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
7997                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), PaymentId(payment_preimage.0)).unwrap();
7998                 check_added_monitors!(nodes[0], 1);
7999                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8000                 assert_eq!(events.len(), 1);
8001                 let ev = events.drain(..).next().unwrap();
8002                 let payment_event = SendEvent::from_event(ev);
8003                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8004                 check_added_monitors!(nodes[1], 0);
8005                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8006                 expect_pending_htlcs_forwardable!(nodes[1]);
8007                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
8008                 check_added_monitors!(nodes[1], 1);
8009                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8010                 assert!(updates.update_add_htlcs.is_empty());
8011                 assert!(updates.update_fulfill_htlcs.is_empty());
8012                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8013                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8014                 assert!(updates.update_fee.is_none());
8015                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
8016                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
8017                 expect_payment_failed!(nodes[0], our_payment_hash, true);
8018
8019                 // Send the second half of the original MPP payment.
8020                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash, &Some(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
8021                 check_added_monitors!(nodes[0], 1);
8022                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8023                 assert_eq!(events.len(), 1);
8024                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
8025
8026                 // Claim the full MPP payment. Note that we can't use a test utility like
8027                 // claim_funds_along_route because the ordering of the messages causes the second half of the
8028                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
8029                 // lightning messages manually.
8030                 nodes[1].node.claim_funds(payment_preimage);
8031                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
8032                 check_added_monitors!(nodes[1], 2);
8033
8034                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8035                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
8036                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
8037                 check_added_monitors!(nodes[0], 1);
8038                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8039                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
8040                 check_added_monitors!(nodes[1], 1);
8041                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8042                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
8043                 check_added_monitors!(nodes[1], 1);
8044                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
8045                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
8046                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
8047                 check_added_monitors!(nodes[0], 1);
8048                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8049                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
8050                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8051                 check_added_monitors!(nodes[0], 1);
8052                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
8053                 check_added_monitors!(nodes[1], 1);
8054                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
8055                 check_added_monitors!(nodes[1], 1);
8056                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
8057                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
8058                 check_added_monitors!(nodes[0], 1);
8059
8060                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
8061                 // path's success and a PaymentPathSuccessful event for each path's success.
8062                 let events = nodes[0].node.get_and_clear_pending_events();
8063                 assert_eq!(events.len(), 3);
8064                 match events[0] {
8065                         Event::PaymentSent { payment_id: ref id, payment_preimage: ref preimage, payment_hash: ref hash, .. } => {
8066                                 assert_eq!(Some(payment_id), *id);
8067                                 assert_eq!(payment_preimage, *preimage);
8068                                 assert_eq!(our_payment_hash, *hash);
8069                         },
8070                         _ => panic!("Unexpected event"),
8071                 }
8072                 match events[1] {
8073                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
8074                                 assert_eq!(payment_id, *actual_payment_id);
8075                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
8076                                 assert_eq!(route.paths[0], *path);
8077                         },
8078                         _ => panic!("Unexpected event"),
8079                 }
8080                 match events[2] {
8081                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
8082                                 assert_eq!(payment_id, *actual_payment_id);
8083                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
8084                                 assert_eq!(route.paths[0], *path);
8085                         },
8086                         _ => panic!("Unexpected event"),
8087                 }
8088         }
8089
8090         #[test]
8091         fn test_keysend_dup_payment_hash() {
8092                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
8093                 //      outbound regular payment fails as expected.
8094                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
8095                 //      fails as expected.
8096                 let chanmon_cfgs = create_chanmon_cfgs(2);
8097                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8098                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8099                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8100                 create_announced_chan_between_nodes(&nodes, 0, 1);
8101                 let scorer = test_utils::TestScorer::new();
8102                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
8103
8104                 // To start (1), send a regular payment but don't claim it.
8105                 let expected_route = [&nodes[1]];
8106                 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &expected_route, 100_000);
8107
8108                 // Next, attempt a keysend payment and make sure it fails.
8109                 let route_params = RouteParameters {
8110                         payment_params: PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV),
8111                         final_value_msat: 100_000,
8112                 };
8113                 let route = find_route(
8114                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
8115                         None, nodes[0].logger, &scorer, &random_seed_bytes
8116                 ).unwrap();
8117                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), PaymentId(payment_preimage.0)).unwrap();
8118                 check_added_monitors!(nodes[0], 1);
8119                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8120                 assert_eq!(events.len(), 1);
8121                 let ev = events.drain(..).next().unwrap();
8122                 let payment_event = SendEvent::from_event(ev);
8123                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8124                 check_added_monitors!(nodes[1], 0);
8125                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8126                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
8127                 // fails), the second will process the resulting failure and fail the HTLC backward
8128                 expect_pending_htlcs_forwardable!(nodes[1]);
8129                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
8130                 check_added_monitors!(nodes[1], 1);
8131                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8132                 assert!(updates.update_add_htlcs.is_empty());
8133                 assert!(updates.update_fulfill_htlcs.is_empty());
8134                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8135                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8136                 assert!(updates.update_fee.is_none());
8137                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
8138                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
8139                 expect_payment_failed!(nodes[0], payment_hash, true);
8140
8141                 // Finally, claim the original payment.
8142                 claim_payment(&nodes[0], &expected_route, payment_preimage);
8143
8144                 // To start (2), send a keysend payment but don't claim it.
8145                 let payment_preimage = PaymentPreimage([42; 32]);
8146                 let route = find_route(
8147                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
8148                         None, nodes[0].logger, &scorer, &random_seed_bytes
8149                 ).unwrap();
8150                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), PaymentId(payment_preimage.0)).unwrap();
8151                 check_added_monitors!(nodes[0], 1);
8152                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8153                 assert_eq!(events.len(), 1);
8154                 let event = events.pop().unwrap();
8155                 let path = vec![&nodes[1]];
8156                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
8157
8158                 // Next, attempt a regular payment and make sure it fails.
8159                 let payment_secret = PaymentSecret([43; 32]);
8160                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8161                 check_added_monitors!(nodes[0], 1);
8162                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8163                 assert_eq!(events.len(), 1);
8164                 let ev = events.drain(..).next().unwrap();
8165                 let payment_event = SendEvent::from_event(ev);
8166                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8167                 check_added_monitors!(nodes[1], 0);
8168                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8169                 expect_pending_htlcs_forwardable!(nodes[1]);
8170                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
8171                 check_added_monitors!(nodes[1], 1);
8172                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8173                 assert!(updates.update_add_htlcs.is_empty());
8174                 assert!(updates.update_fulfill_htlcs.is_empty());
8175                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8176                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8177                 assert!(updates.update_fee.is_none());
8178                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
8179                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
8180                 expect_payment_failed!(nodes[0], payment_hash, true);
8181
8182                 // Finally, succeed the keysend payment.
8183                 claim_payment(&nodes[0], &expected_route, payment_preimage);
8184         }
8185
8186         #[test]
8187         fn test_keysend_hash_mismatch() {
8188                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
8189                 // preimage doesn't match the msg's payment hash.
8190                 let chanmon_cfgs = create_chanmon_cfgs(2);
8191                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8192                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8193                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8194
8195                 let payer_pubkey = nodes[0].node.get_our_node_id();
8196                 let payee_pubkey = nodes[1].node.get_our_node_id();
8197
8198                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
8199                 let route_params = RouteParameters {
8200                         payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
8201                         final_value_msat: 10_000,
8202                 };
8203                 let network_graph = nodes[0].network_graph.clone();
8204                 let first_hops = nodes[0].node.list_usable_channels();
8205                 let scorer = test_utils::TestScorer::new();
8206                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
8207                 let route = find_route(
8208                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
8209                         nodes[0].logger, &scorer, &random_seed_bytes
8210                 ).unwrap();
8211
8212                 let test_preimage = PaymentPreimage([42; 32]);
8213                 let mismatch_payment_hash = PaymentHash([43; 32]);
8214                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash, None, PaymentId(mismatch_payment_hash.0), &route).unwrap();
8215                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash, &None, Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
8216                 check_added_monitors!(nodes[0], 1);
8217
8218                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8219                 assert_eq!(updates.update_add_htlcs.len(), 1);
8220                 assert!(updates.update_fulfill_htlcs.is_empty());
8221                 assert!(updates.update_fail_htlcs.is_empty());
8222                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8223                 assert!(updates.update_fee.is_none());
8224                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8225
8226                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
8227         }
8228
8229         #[test]
8230         fn test_keysend_msg_with_secret_err() {
8231                 // Test that we error as expected if we receive a keysend payment that includes a payment secret.
8232                 let chanmon_cfgs = create_chanmon_cfgs(2);
8233                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8234                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8235                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8236
8237                 let payer_pubkey = nodes[0].node.get_our_node_id();
8238                 let payee_pubkey = nodes[1].node.get_our_node_id();
8239
8240                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
8241                 let route_params = RouteParameters {
8242                         payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
8243                         final_value_msat: 10_000,
8244                 };
8245                 let network_graph = nodes[0].network_graph.clone();
8246                 let first_hops = nodes[0].node.list_usable_channels();
8247                 let scorer = test_utils::TestScorer::new();
8248                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
8249                 let route = find_route(
8250                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
8251                         nodes[0].logger, &scorer, &random_seed_bytes
8252                 ).unwrap();
8253
8254                 let test_preimage = PaymentPreimage([42; 32]);
8255                 let test_secret = PaymentSecret([43; 32]);
8256                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).into_inner());
8257                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash, Some(test_secret), PaymentId(payment_hash.0), &route).unwrap();
8258                 nodes[0].node.test_send_payment_internal(&route, payment_hash, &Some(test_secret), Some(test_preimage), PaymentId(payment_hash.0), None, session_privs).unwrap();
8259                 check_added_monitors!(nodes[0], 1);
8260
8261                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8262                 assert_eq!(updates.update_add_htlcs.len(), 1);
8263                 assert!(updates.update_fulfill_htlcs.is_empty());
8264                 assert!(updates.update_fail_htlcs.is_empty());
8265                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8266                 assert!(updates.update_fee.is_none());
8267                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8268
8269                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
8270         }
8271
8272         #[test]
8273         fn test_multi_hop_missing_secret() {
8274                 let chanmon_cfgs = create_chanmon_cfgs(4);
8275                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8276                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8277                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8278
8279                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8280                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8281                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8282                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8283
8284                 // Marshall an MPP route.
8285                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8286                 let path = route.paths[0].clone();
8287                 route.paths.push(path);
8288                 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8289                 route.paths[0][0].short_channel_id = chan_1_id;
8290                 route.paths[0][1].short_channel_id = chan_3_id;
8291                 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8292                 route.paths[1][0].short_channel_id = chan_2_id;
8293                 route.paths[1][1].short_channel_id = chan_4_id;
8294
8295                 match nodes[0].node.send_payment(&route, payment_hash, &None, PaymentId(payment_hash.0)).unwrap_err() {
8296                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
8297                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
8298                         },
8299                         _ => panic!("unexpected error")
8300                 }
8301         }
8302
8303         #[test]
8304         fn test_drop_disconnected_peers_when_removing_channels() {
8305                 let chanmon_cfgs = create_chanmon_cfgs(2);
8306                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8307                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8308                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8309
8310                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
8311
8312                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
8313                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
8314
8315                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
8316                 check_closed_broadcast!(nodes[0], true);
8317                 check_added_monitors!(nodes[0], 1);
8318                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
8319
8320                 {
8321                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
8322                         // disconnected and the channel between has been force closed.
8323                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8324                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
8325                         assert_eq!(nodes_0_per_peer_state.len(), 1);
8326                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
8327                 }
8328
8329                 nodes[0].node.timer_tick_occurred();
8330
8331                 {
8332                         // Assert that nodes[1] has now been removed.
8333                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
8334                 }
8335         }
8336
8337         #[test]
8338         fn bad_inbound_payment_hash() {
8339                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
8340                 let chanmon_cfgs = create_chanmon_cfgs(2);
8341                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8342                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8343                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8344
8345                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
8346                 let payment_data = msgs::FinalOnionHopData {
8347                         payment_secret,
8348                         total_msat: 100_000,
8349                 };
8350
8351                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
8352                 // payment verification fails as expected.
8353                 let mut bad_payment_hash = payment_hash.clone();
8354                 bad_payment_hash.0[0] += 1;
8355                 match inbound_payment::verify(bad_payment_hash, &payment_data, nodes[0].node.highest_seen_timestamp.load(Ordering::Acquire) as u64, &nodes[0].node.inbound_payment_key, &nodes[0].logger) {
8356                         Ok(_) => panic!("Unexpected ok"),
8357                         Err(()) => {
8358                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
8359                         }
8360                 }
8361
8362                 // Check that using the original payment hash succeeds.
8363                 assert!(inbound_payment::verify(payment_hash, &payment_data, nodes[0].node.highest_seen_timestamp.load(Ordering::Acquire) as u64, &nodes[0].node.inbound_payment_key, &nodes[0].logger).is_ok());
8364         }
8365
8366         #[test]
8367         fn test_id_to_peer_coverage() {
8368                 // Test that the `ChannelManager:id_to_peer` contains channels which have been assigned
8369                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
8370                 // the channel is successfully closed.
8371                 let chanmon_cfgs = create_chanmon_cfgs(2);
8372                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8373                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8374                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8375
8376                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
8377                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8378                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
8379                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8380                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
8381
8382                 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
8383                 let channel_id = &tx.txid().into_inner();
8384                 {
8385                         // Ensure that the `id_to_peer` map is empty until either party has received the
8386                         // funding transaction, and have the real `channel_id`.
8387                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
8388                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
8389                 }
8390
8391                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8392                 {
8393                         // Assert that `nodes[0]`'s `id_to_peer` map is populated with the channel as soon as
8394                         // as it has the funding transaction.
8395                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
8396                         assert_eq!(nodes_0_lock.len(), 1);
8397                         assert!(nodes_0_lock.contains_key(channel_id));
8398                 }
8399
8400                 assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
8401
8402                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8403
8404                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8405                 {
8406                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
8407                         assert_eq!(nodes_0_lock.len(), 1);
8408                         assert!(nodes_0_lock.contains_key(channel_id));
8409                 }
8410
8411                 {
8412                         // Assert that `nodes[1]`'s `id_to_peer` map is populated with the channel as soon as
8413                         // as it has the funding transaction.
8414                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
8415                         assert_eq!(nodes_1_lock.len(), 1);
8416                         assert!(nodes_1_lock.contains_key(channel_id));
8417                 }
8418                 check_added_monitors!(nodes[1], 1);
8419                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8420                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
8421                 check_added_monitors!(nodes[0], 1);
8422                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8423                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8424                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
8425
8426                 nodes[0].node.close_channel(channel_id, &nodes[1].node.get_our_node_id()).unwrap();
8427                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id()));
8428                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
8429                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
8430
8431                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
8432                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
8433                 {
8434                         // Assert that the channel is kept in the `id_to_peer` map for both nodes until the
8435                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
8436                         // fee for the closing transaction has been negotiated and the parties has the other
8437                         // party's signature for the fee negotiated closing transaction.)
8438                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
8439                         assert_eq!(nodes_0_lock.len(), 1);
8440                         assert!(nodes_0_lock.contains_key(channel_id));
8441                 }
8442
8443                 {
8444                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
8445                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
8446                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
8447                         // kept in the `nodes[1]`'s `id_to_peer` map.
8448                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
8449                         assert_eq!(nodes_1_lock.len(), 1);
8450                         assert!(nodes_1_lock.contains_key(channel_id));
8451                 }
8452
8453                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id()));
8454                 {
8455                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
8456                         // therefore has all it needs to fully close the channel (both signatures for the
8457                         // closing transaction).
8458                         // Assert that the channel is removed from `nodes[0]`'s `id_to_peer` map as it can be
8459                         // fully closed by `nodes[0]`.
8460                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
8461
8462                         // Assert that the channel is still in `nodes[1]`'s  `id_to_peer` map, as `nodes[1]`
8463                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
8464                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
8465                         assert_eq!(nodes_1_lock.len(), 1);
8466                         assert!(nodes_1_lock.contains_key(channel_id));
8467                 }
8468
8469                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
8470
8471                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
8472                 {
8473                         // Assert that the channel has now been removed from both parties `id_to_peer` map once
8474                         // they both have everything required to fully close the channel.
8475                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
8476                 }
8477                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
8478
8479                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
8480                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
8481         }
8482
8483         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
8484                 let expected_message = format!("Not connected to node: {}", expected_public_key);
8485                 check_api_error_message(expected_message, res_err)
8486         }
8487
8488         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
8489                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
8490                 check_api_error_message(expected_message, res_err)
8491         }
8492
8493         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
8494                 match res_err {
8495                         Err(APIError::APIMisuseError { err }) => {
8496                                 assert_eq!(err, expected_err_message);
8497                         },
8498                         Err(APIError::ChannelUnavailable { err }) => {
8499                                 assert_eq!(err, expected_err_message);
8500                         },
8501                         Ok(_) => panic!("Unexpected Ok"),
8502                         Err(_) => panic!("Unexpected Error"),
8503                 }
8504         }
8505
8506         #[test]
8507         fn test_api_calls_with_unkown_counterparty_node() {
8508                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
8509                 // expected if the `counterparty_node_id` is an unkown peer in the
8510                 // `ChannelManager::per_peer_state` map.
8511                 let chanmon_cfg = create_chanmon_cfgs(2);
8512                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8513                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8514                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8515
8516                 // Dummy values
8517                 let channel_id = [4; 32];
8518                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
8519                 let intercept_id = InterceptId([0; 32]);
8520
8521                 // Test the API functions.
8522                 check_not_connected_to_peer_error(nodes[0].node.create_channel(unkown_public_key, 1_000_000, 500_000_000, 42, None), unkown_public_key);
8523
8524                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
8525
8526                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
8527
8528                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
8529
8530                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
8531
8532                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
8533
8534                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
8535         }
8536
8537         #[test]
8538         fn test_connection_limiting() {
8539                 // Test that we limit un-channel'd peers and un-funded channels properly.
8540                 let chanmon_cfgs = create_chanmon_cfgs(2);
8541                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8542                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8543                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8544
8545                 // Note that create_network connects the nodes together for us
8546
8547                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
8548                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8549
8550                 let mut funding_tx = None;
8551                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
8552                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
8553                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8554
8555                         if idx == 0 {
8556                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
8557                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
8558                                 funding_tx = Some(tx.clone());
8559                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
8560                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8561
8562                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8563                                 check_added_monitors!(nodes[1], 1);
8564                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8565
8566                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
8567                                 check_added_monitors!(nodes[0], 1);
8568                         }
8569                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
8570                 }
8571
8572                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
8573                 open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
8574                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
8575                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
8576                         open_channel_msg.temporary_channel_id);
8577
8578                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
8579                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
8580                 // limit.
8581                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
8582                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
8583                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
8584                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
8585                         peer_pks.push(random_pk);
8586                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
8587                                 features: nodes[0].node.init_features(), remote_network_address: None }, true).unwrap();
8588                 }
8589                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
8590                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
8591                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
8592                         features: nodes[0].node.init_features(), remote_network_address: None }, true).unwrap_err();
8593
8594                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
8595                 // them if we have too many un-channel'd peers.
8596                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
8597                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
8598                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
8599                 for ev in chan_closed_events {
8600                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
8601                 }
8602                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
8603                         features: nodes[0].node.init_features(), remote_network_address: None }, true).unwrap();
8604                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
8605                         features: nodes[0].node.init_features(), remote_network_address: None }, true).unwrap_err();
8606
8607                 // but of course if the connection is outbound its allowed...
8608                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
8609                         features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
8610                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
8611
8612                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
8613                 // Even though we accept one more connection from new peers, we won't actually let them
8614                 // open channels.
8615                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
8616                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
8617                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
8618                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
8619                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
8620                 }
8621                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
8622                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
8623                         open_channel_msg.temporary_channel_id);
8624
8625                 // Of course, however, outbound channels are always allowed
8626                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None).unwrap();
8627                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
8628
8629                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
8630                 // "protected" and can connect again.
8631                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
8632                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
8633                         features: nodes[0].node.init_features(), remote_network_address: None }, true).unwrap();
8634                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8635
8636                 // Further, because the first channel was funded, we can open another channel with
8637                 // last_random_pk.
8638                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
8639                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
8640         }
8641
8642         #[test]
8643         fn test_outbound_chans_unlimited() {
8644                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
8645                 let chanmon_cfgs = create_chanmon_cfgs(2);
8646                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8647                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8648                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8649
8650                 // Note that create_network connects the nodes together for us
8651
8652                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
8653                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8654
8655                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
8656                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
8657                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8658                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
8659                 }
8660
8661                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
8662                 // rejected.
8663                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
8664                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
8665                         open_channel_msg.temporary_channel_id);
8666
8667                 // but we can still open an outbound channel.
8668                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
8669                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8670
8671                 // but even with such an outbound channel, additional inbound channels will still fail.
8672                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
8673                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
8674                         open_channel_msg.temporary_channel_id);
8675         }
8676
8677         #[test]
8678         fn test_0conf_limiting() {
8679                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
8680                 // flag set and (sometimes) accept channels as 0conf.
8681                 let chanmon_cfgs = create_chanmon_cfgs(2);
8682                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8683                 let mut settings = test_default_channel_config();
8684                 settings.manually_accept_inbound_channels = true;
8685                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
8686                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8687
8688                 // Note that create_network connects the nodes together for us
8689
8690                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
8691                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8692
8693                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
8694                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
8695                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
8696                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
8697                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
8698                                 features: nodes[0].node.init_features(), remote_network_address: None }, true).unwrap();
8699
8700                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
8701                         let events = nodes[1].node.get_and_clear_pending_events();
8702                         match events[0] {
8703                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8704                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
8705                                 }
8706                                 _ => panic!("Unexpected event"),
8707                         }
8708                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
8709                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
8710                 }
8711
8712                 // If we try to accept a channel from another peer non-0conf it will fail.
8713                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
8714                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
8715                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
8716                         features: nodes[0].node.init_features(), remote_network_address: None }, true).unwrap();
8717                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
8718                 let events = nodes[1].node.get_and_clear_pending_events();
8719                 match events[0] {
8720                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
8721                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
8722                                         Err(APIError::APIMisuseError { err }) =>
8723                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
8724                                         _ => panic!(),
8725                                 }
8726                         }
8727                         _ => panic!("Unexpected event"),
8728                 }
8729                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
8730                         open_channel_msg.temporary_channel_id);
8731
8732                 // ...however if we accept the same channel 0conf it should work just fine.
8733                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
8734                 let events = nodes[1].node.get_and_clear_pending_events();
8735                 match events[0] {
8736                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
8737                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
8738                         }
8739                         _ => panic!("Unexpected event"),
8740                 }
8741                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
8742         }
8743
8744         #[cfg(anchors)]
8745         #[test]
8746         fn test_anchors_zero_fee_htlc_tx_fallback() {
8747                 // Tests that if both nodes support anchors, but the remote node does not want to accept
8748                 // anchor channels at the moment, an error it sent to the local node such that it can retry
8749                 // the channel without the anchors feature.
8750                 let chanmon_cfgs = create_chanmon_cfgs(2);
8751                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8752                 let mut anchors_config = test_default_channel_config();
8753                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
8754                 anchors_config.manually_accept_inbound_channels = true;
8755                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
8756                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8757
8758                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None).unwrap();
8759                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8760                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
8761
8762                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
8763                 let events = nodes[1].node.get_and_clear_pending_events();
8764                 match events[0] {
8765                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
8766                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8767                         }
8768                         _ => panic!("Unexpected event"),
8769                 }
8770
8771                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
8772                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
8773
8774                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8775                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
8776
8777                 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8778         }
8779 }
8780
8781 #[cfg(all(any(test, feature = "_test_utils"), feature = "_bench_unstable"))]
8782 pub mod bench {
8783         use crate::chain::Listen;
8784         use crate::chain::chainmonitor::{ChainMonitor, Persist};
8785         use crate::chain::keysinterface::{EntropySource, KeysManager, InMemorySigner};
8786         use crate::ln::channelmanager::{self, BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId};
8787         use crate::ln::functional_test_utils::*;
8788         use crate::ln::msgs::{ChannelMessageHandler, Init};
8789         use crate::routing::gossip::NetworkGraph;
8790         use crate::routing::router::{PaymentParameters, get_route};
8791         use crate::util::test_utils;
8792         use crate::util::config::UserConfig;
8793         use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
8794
8795         use bitcoin::hashes::Hash;
8796         use bitcoin::hashes::sha256::Hash as Sha256;
8797         use bitcoin::{Block, BlockHeader, PackedLockTime, Transaction, TxMerkleNode, TxOut};
8798
8799         use crate::sync::{Arc, Mutex};
8800
8801         use test::Bencher;
8802
8803         struct NodeHolder<'a, P: Persist<InMemorySigner>> {
8804                 node: &'a ChannelManager<
8805                         &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
8806                                 &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
8807                                 &'a test_utils::TestLogger, &'a P>,
8808                         &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
8809                         &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
8810                         &'a test_utils::TestLogger>,
8811         }
8812
8813         #[cfg(test)]
8814         #[bench]
8815         fn bench_sends(bench: &mut Bencher) {
8816                 bench_two_sends(bench, test_utils::TestPersister::new(), test_utils::TestPersister::new());
8817         }
8818
8819         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Bencher, persister_a: P, persister_b: P) {
8820                 // Do a simple benchmark of sending a payment back and forth between two nodes.
8821                 // Note that this is unrealistic as each payment send will require at least two fsync
8822                 // calls per node.
8823                 let network = bitcoin::Network::Testnet;
8824
8825                 let tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
8826                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
8827                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
8828                 let scorer = Mutex::new(test_utils::TestScorer::new());
8829                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &scorer);
8830
8831                 let mut config: UserConfig = Default::default();
8832                 config.channel_handshake_config.minimum_depth = 1;
8833
8834                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
8835                 let seed_a = [1u8; 32];
8836                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
8837                 let node_a = ChannelManager::new(&fee_estimator, &chain_monitor_a, &tx_broadcaster, &router, &logger_a, &keys_manager_a, &keys_manager_a, &keys_manager_a, config.clone(), ChainParameters {
8838                         network,
8839                         best_block: BestBlock::from_network(network),
8840                 });
8841                 let node_a_holder = NodeHolder { node: &node_a };
8842
8843                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
8844                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
8845                 let seed_b = [2u8; 32];
8846                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
8847                 let node_b = ChannelManager::new(&fee_estimator, &chain_monitor_b, &tx_broadcaster, &router, &logger_b, &keys_manager_b, &keys_manager_b, &keys_manager_b, config.clone(), ChainParameters {
8848                         network,
8849                         best_block: BestBlock::from_network(network),
8850                 });
8851                 let node_b_holder = NodeHolder { node: &node_b };
8852
8853                 node_a.peer_connected(&node_b.get_our_node_id(), &Init { features: node_b.init_features(), remote_network_address: None }, true).unwrap();
8854                 node_b.peer_connected(&node_a.get_our_node_id(), &Init { features: node_a.init_features(), remote_network_address: None }, false).unwrap();
8855                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
8856                 node_b.handle_open_channel(&node_a.get_our_node_id(), &get_event_msg!(node_a_holder, MessageSendEvent::SendOpenChannel, node_b.get_our_node_id()));
8857                 node_a.handle_accept_channel(&node_b.get_our_node_id(), &get_event_msg!(node_b_holder, MessageSendEvent::SendAcceptChannel, node_a.get_our_node_id()));
8858
8859                 let tx;
8860                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
8861                         tx = Transaction { version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
8862                                 value: 8_000_000, script_pubkey: output_script,
8863                         }]};
8864                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
8865                 } else { panic!(); }
8866
8867                 node_b.handle_funding_created(&node_a.get_our_node_id(), &get_event_msg!(node_a_holder, MessageSendEvent::SendFundingCreated, node_b.get_our_node_id()));
8868                 node_a.handle_funding_signed(&node_b.get_our_node_id(), &get_event_msg!(node_b_holder, MessageSendEvent::SendFundingSigned, node_a.get_our_node_id()));
8869
8870                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
8871
8872                 let block = Block {
8873                         header: BlockHeader { version: 0x20000000, prev_blockhash: BestBlock::from_network(network).block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
8874                         txdata: vec![tx],
8875                 };
8876                 Listen::block_connected(&node_a, &block, 1);
8877                 Listen::block_connected(&node_b, &block, 1);
8878
8879                 node_a.handle_channel_ready(&node_b.get_our_node_id(), &get_event_msg!(node_b_holder, MessageSendEvent::SendChannelReady, node_a.get_our_node_id()));
8880                 let msg_events = node_a.get_and_clear_pending_msg_events();
8881                 assert_eq!(msg_events.len(), 2);
8882                 match msg_events[0] {
8883                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
8884                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
8885                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
8886                         },
8887                         _ => panic!(),
8888                 }
8889                 match msg_events[1] {
8890                         MessageSendEvent::SendChannelUpdate { .. } => {},
8891                         _ => panic!(),
8892                 }
8893
8894                 let events_a = node_a.get_and_clear_pending_events();
8895                 assert_eq!(events_a.len(), 1);
8896                 match events_a[0] {
8897                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
8898                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
8899                         },
8900                         _ => panic!("Unexpected event"),
8901                 }
8902
8903                 let events_b = node_b.get_and_clear_pending_events();
8904                 assert_eq!(events_b.len(), 1);
8905                 match events_b[0] {
8906                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
8907                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
8908                         },
8909                         _ => panic!("Unexpected event"),
8910                 }
8911
8912                 let dummy_graph = NetworkGraph::new(network, &logger_a);
8913
8914                 let mut payment_count: u64 = 0;
8915                 macro_rules! send_payment {
8916                         ($node_a: expr, $node_b: expr) => {
8917                                 let usable_channels = $node_a.list_usable_channels();
8918                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
8919                                         .with_features($node_b.invoice_features());
8920                                 let scorer = test_utils::TestScorer::new();
8921                                 let seed = [3u8; 32];
8922                                 let keys_manager = KeysManager::new(&seed, 42, 42);
8923                                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8924                                 let route = get_route(&$node_a.get_our_node_id(), &payment_params, &dummy_graph.read_only(),
8925                                         Some(&usable_channels.iter().map(|r| r).collect::<Vec<_>>()), 10_000, TEST_FINAL_CLTV, &logger_a, &scorer, &random_seed_bytes).unwrap();
8926
8927                                 let mut payment_preimage = PaymentPreimage([0; 32]);
8928                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
8929                                 payment_count += 1;
8930                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
8931                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
8932
8933                                 $node_a.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8934                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
8935                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
8936                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
8937                                 let (raa, cs) = do_get_revoke_commit_msgs!(NodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
8938                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
8939                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
8940                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &get_event_msg!(NodeHolder { node: &$node_a }, MessageSendEvent::SendRevokeAndACK, $node_b.get_our_node_id()));
8941
8942                                 expect_pending_htlcs_forwardable!(NodeHolder { node: &$node_b });
8943                                 expect_payment_claimable!(NodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
8944                                 $node_b.claim_funds(payment_preimage);
8945                                 expect_payment_claimed!(NodeHolder { node: &$node_b }, payment_hash, 10_000);
8946
8947                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
8948                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8949                                                 assert_eq!(node_id, $node_a.get_our_node_id());
8950                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8951                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
8952                                         },
8953                                         _ => panic!("Failed to generate claim event"),
8954                                 }
8955
8956                                 let (raa, cs) = do_get_revoke_commit_msgs!(NodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
8957                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
8958                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
8959                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &get_event_msg!(NodeHolder { node: &$node_b }, MessageSendEvent::SendRevokeAndACK, $node_a.get_our_node_id()));
8960
8961                                 expect_payment_sent!(NodeHolder { node: &$node_a }, payment_preimage);
8962                         }
8963                 }
8964
8965                 bench.iter(|| {
8966                         send_payment!(node_a, node_b);
8967                         send_payment!(node_b, node_a);
8968                 });
8969         }
8970 }