Merge pull request #2354 from alecchendev/2023-06-bump-default-dust-exp
[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, ChainHash};
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 use crate::events;
39 use crate::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination, PaymentFailureReason};
40 // Since this struct is returned in `list_channels` methods, expose it here in case users want to
41 // construct one themselves.
42 use crate::ln::{inbound_payment, PaymentHash, PaymentPreimage, PaymentSecret};
43 use crate::ln::channel::{Channel, ChannelContext, ChannelError, ChannelUpdateStatus, ShutdownResult, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel};
44 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
45 #[cfg(any(feature = "_test_utils", test))]
46 use crate::ln::features::InvoiceFeatures;
47 use crate::routing::gossip::NetworkGraph;
48 use crate::routing::router::{BlindedTail, DefaultRouter, InFlightHtlcs, Path, Payee, PaymentParameters, Route, RouteHop, RouteParameters, Router};
49 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
50 use crate::ln::msgs;
51 use crate::ln::onion_utils;
52 use crate::ln::onion_utils::HTLCFailReason;
53 use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
54 #[cfg(test)]
55 use crate::ln::outbound_payment;
56 use crate::ln::outbound_payment::{OutboundPayments, PaymentAttempts, PendingOutboundPayment};
57 use crate::ln::wire::Encode;
58 use crate::sign::{EntropySource, KeysManager, NodeSigner, Recipient, SignerProvider, ChannelSigner, WriteableEcdsaChannelSigner};
59 use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
60 use crate::util::wakers::{Future, Notifier};
61 use crate::util::scid_utils::fake_scid;
62 use crate::util::string::UntrustedString;
63 use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
64 use crate::util::logger::{Level, Logger};
65 use crate::util::errors::APIError;
66
67 use alloc::collections::BTreeMap;
68
69 use crate::io;
70 use crate::prelude::*;
71 use core::{cmp, mem};
72 use core::cell::RefCell;
73 use crate::io::Read;
74 use crate::sync::{Arc, Mutex, RwLock, RwLockReadGuard, FairRwLock, LockTestExt, LockHeldState};
75 use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
76 use core::time::Duration;
77 use core::ops::Deref;
78
79 // Re-export this for use in the public API.
80 pub use crate::ln::outbound_payment::{PaymentSendFailure, Retry, RetryableSendFailure, RecipientOnionFields};
81 use crate::ln::script::ShutdownScript;
82
83 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
84 //
85 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
86 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
87 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
88 //
89 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
90 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
91 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
92 // before we forward it.
93 //
94 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
95 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
96 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
97 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
98 // our payment, which we can use to decode errors or inform the user that the payment was sent.
99
100 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
101 pub(super) enum PendingHTLCRouting {
102         Forward {
103                 onion_packet: msgs::OnionPacket,
104                 /// The SCID from the onion that we should forward to. This could be a real SCID or a fake one
105                 /// generated using `get_fake_scid` from the scid_utils::fake_scid module.
106                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
107         },
108         Receive {
109                 payment_data: msgs::FinalOnionHopData,
110                 payment_metadata: Option<Vec<u8>>,
111                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
112                 phantom_shared_secret: Option<[u8; 32]>,
113         },
114         ReceiveKeysend {
115                 /// This was added in 0.0.116 and will break deserialization on downgrades.
116                 payment_data: Option<msgs::FinalOnionHopData>,
117                 payment_preimage: PaymentPreimage,
118                 payment_metadata: Option<Vec<u8>>,
119                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
120         },
121 }
122
123 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
124 pub(super) struct PendingHTLCInfo {
125         pub(super) routing: PendingHTLCRouting,
126         pub(super) incoming_shared_secret: [u8; 32],
127         payment_hash: PaymentHash,
128         /// Amount received
129         pub(super) incoming_amt_msat: Option<u64>, // Added in 0.0.113
130         /// Sender intended amount to forward or receive (actual amount received
131         /// may overshoot this in either case)
132         pub(super) outgoing_amt_msat: u64,
133         pub(super) outgoing_cltv_value: u32,
134         /// The fee being skimmed off the top of this HTLC. If this is a forward, it'll be the fee we are
135         /// skimming. If we're receiving this HTLC, it's the fee that our counterparty skimmed.
136         pub(super) skimmed_fee_msat: Option<u64>,
137 }
138
139 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
140 pub(super) enum HTLCFailureMsg {
141         Relay(msgs::UpdateFailHTLC),
142         Malformed(msgs::UpdateFailMalformedHTLC),
143 }
144
145 /// Stores whether we can't forward an HTLC or relevant forwarding info
146 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
147 pub(super) enum PendingHTLCStatus {
148         Forward(PendingHTLCInfo),
149         Fail(HTLCFailureMsg),
150 }
151
152 pub(super) struct PendingAddHTLCInfo {
153         pub(super) forward_info: PendingHTLCInfo,
154
155         // These fields are produced in `forward_htlcs()` and consumed in
156         // `process_pending_htlc_forwards()` for constructing the
157         // `HTLCSource::PreviousHopData` for failed and forwarded
158         // HTLCs.
159         //
160         // Note that this may be an outbound SCID alias for the associated channel.
161         prev_short_channel_id: u64,
162         prev_htlc_id: u64,
163         prev_funding_outpoint: OutPoint,
164         prev_user_channel_id: u128,
165 }
166
167 pub(super) enum HTLCForwardInfo {
168         AddHTLC(PendingAddHTLCInfo),
169         FailHTLC {
170                 htlc_id: u64,
171                 err_packet: msgs::OnionErrorPacket,
172         },
173 }
174
175 /// Tracks the inbound corresponding to an outbound HTLC
176 #[derive(Clone, Hash, PartialEq, Eq)]
177 pub(crate) struct HTLCPreviousHopData {
178         // Note that this may be an outbound SCID alias for the associated channel.
179         short_channel_id: u64,
180         htlc_id: u64,
181         incoming_packet_shared_secret: [u8; 32],
182         phantom_shared_secret: Option<[u8; 32]>,
183
184         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
185         // channel with a preimage provided by the forward channel.
186         outpoint: OutPoint,
187 }
188
189 enum OnionPayload {
190         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
191         Invoice {
192                 /// This is only here for backwards-compatibility in serialization, in the future it can be
193                 /// removed, breaking clients running 0.0.106 and earlier.
194                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
195         },
196         /// Contains the payer-provided preimage.
197         Spontaneous(PaymentPreimage),
198 }
199
200 /// HTLCs that are to us and can be failed/claimed by the user
201 struct ClaimableHTLC {
202         prev_hop: HTLCPreviousHopData,
203         cltv_expiry: u32,
204         /// The amount (in msats) of this MPP part
205         value: u64,
206         /// The amount (in msats) that the sender intended to be sent in this MPP
207         /// part (used for validating total MPP amount)
208         sender_intended_value: u64,
209         onion_payload: OnionPayload,
210         timer_ticks: u8,
211         /// The total value received for a payment (sum of all MPP parts if the payment is a MPP).
212         /// Gets set to the amount reported when pushing [`Event::PaymentClaimable`].
213         total_value_received: Option<u64>,
214         /// The sender intended sum total of all MPP parts specified in the onion
215         total_msat: u64,
216         /// The extra fee our counterparty skimmed off the top of this HTLC.
217         counterparty_skimmed_fee_msat: Option<u64>,
218 }
219
220 /// A payment identifier used to uniquely identify a payment to LDK.
221 ///
222 /// This is not exported to bindings users as we just use [u8; 32] directly
223 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
224 pub struct PaymentId(pub [u8; 32]);
225
226 impl Writeable for PaymentId {
227         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
228                 self.0.write(w)
229         }
230 }
231
232 impl Readable for PaymentId {
233         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
234                 let buf: [u8; 32] = Readable::read(r)?;
235                 Ok(PaymentId(buf))
236         }
237 }
238
239 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
240 ///
241 /// This is not exported to bindings users as we just use [u8; 32] directly
242 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
243 pub struct InterceptId(pub [u8; 32]);
244
245 impl Writeable for InterceptId {
246         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
247                 self.0.write(w)
248         }
249 }
250
251 impl Readable for InterceptId {
252         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
253                 let buf: [u8; 32] = Readable::read(r)?;
254                 Ok(InterceptId(buf))
255         }
256 }
257
258 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
259 /// Uniquely describes an HTLC by its source. Just the guaranteed-unique subset of [`HTLCSource`].
260 pub(crate) enum SentHTLCId {
261         PreviousHopData { short_channel_id: u64, htlc_id: u64 },
262         OutboundRoute { session_priv: SecretKey },
263 }
264 impl SentHTLCId {
265         pub(crate) fn from_source(source: &HTLCSource) -> Self {
266                 match source {
267                         HTLCSource::PreviousHopData(hop_data) => Self::PreviousHopData {
268                                 short_channel_id: hop_data.short_channel_id,
269                                 htlc_id: hop_data.htlc_id,
270                         },
271                         HTLCSource::OutboundRoute { session_priv, .. } =>
272                                 Self::OutboundRoute { session_priv: *session_priv },
273                 }
274         }
275 }
276 impl_writeable_tlv_based_enum!(SentHTLCId,
277         (0, PreviousHopData) => {
278                 (0, short_channel_id, required),
279                 (2, htlc_id, required),
280         },
281         (2, OutboundRoute) => {
282                 (0, session_priv, required),
283         };
284 );
285
286
287 /// Tracks the inbound corresponding to an outbound HTLC
288 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
289 #[derive(Clone, PartialEq, Eq)]
290 pub(crate) enum HTLCSource {
291         PreviousHopData(HTLCPreviousHopData),
292         OutboundRoute {
293                 path: Path,
294                 session_priv: SecretKey,
295                 /// Technically we can recalculate this from the route, but we cache it here to avoid
296                 /// doing a double-pass on route when we get a failure back
297                 first_hop_htlc_msat: u64,
298                 payment_id: PaymentId,
299         },
300 }
301 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
302 impl core::hash::Hash for HTLCSource {
303         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
304                 match self {
305                         HTLCSource::PreviousHopData(prev_hop_data) => {
306                                 0u8.hash(hasher);
307                                 prev_hop_data.hash(hasher);
308                         },
309                         HTLCSource::OutboundRoute { path, session_priv, payment_id, first_hop_htlc_msat } => {
310                                 1u8.hash(hasher);
311                                 path.hash(hasher);
312                                 session_priv[..].hash(hasher);
313                                 payment_id.hash(hasher);
314                                 first_hop_htlc_msat.hash(hasher);
315                         },
316                 }
317         }
318 }
319 impl HTLCSource {
320         #[cfg(all(feature = "_test_vectors", not(feature = "grind_signatures")))]
321         #[cfg(test)]
322         pub fn dummy() -> Self {
323                 HTLCSource::OutboundRoute {
324                         path: Path { hops: Vec::new(), blinded_tail: None },
325                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
326                         first_hop_htlc_msat: 0,
327                         payment_id: PaymentId([2; 32]),
328                 }
329         }
330
331         #[cfg(debug_assertions)]
332         /// Checks whether this HTLCSource could possibly match the given HTLC output in a commitment
333         /// transaction. Useful to ensure different datastructures match up.
334         pub(crate) fn possibly_matches_output(&self, htlc: &super::chan_utils::HTLCOutputInCommitment) -> bool {
335                 if let HTLCSource::OutboundRoute { first_hop_htlc_msat, .. } = self {
336                         *first_hop_htlc_msat == htlc.amount_msat
337                 } else {
338                         // There's nothing we can check for forwarded HTLCs
339                         true
340                 }
341         }
342 }
343
344 struct ReceiveError {
345         err_code: u16,
346         err_data: Vec<u8>,
347         msg: &'static str,
348 }
349
350 /// This enum is used to specify which error data to send to peers when failing back an HTLC
351 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
352 ///
353 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
354 #[derive(Clone, Copy)]
355 pub enum FailureCode {
356         /// We had a temporary error processing the payment. Useful if no other error codes fit
357         /// and you want to indicate that the payer may want to retry.
358         TemporaryNodeFailure             = 0x2000 | 2,
359         /// We have a required feature which was not in this onion. For example, you may require
360         /// some additional metadata that was not provided with this payment.
361         RequiredNodeFeatureMissing       = 0x4000 | 0x2000 | 3,
362         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
363         /// the HTLC is too close to the current block height for safe handling.
364         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
365         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
366         IncorrectOrUnknownPaymentDetails = 0x4000 | 15,
367 }
368
369 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
370 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
371 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
372 /// peer_state lock. We then return the set of things that need to be done outside the lock in
373 /// this struct and call handle_error!() on it.
374
375 struct MsgHandleErrInternal {
376         err: msgs::LightningError,
377         chan_id: Option<([u8; 32], u128)>, // If Some a channel of ours has been closed
378         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
379 }
380 impl MsgHandleErrInternal {
381         #[inline]
382         fn send_err_msg_no_close(err: String, channel_id: [u8; 32]) -> Self {
383                 Self {
384                         err: LightningError {
385                                 err: err.clone(),
386                                 action: msgs::ErrorAction::SendErrorMessage {
387                                         msg: msgs::ErrorMessage {
388                                                 channel_id,
389                                                 data: err
390                                         },
391                                 },
392                         },
393                         chan_id: None,
394                         shutdown_finish: None,
395                 }
396         }
397         #[inline]
398         fn from_no_close(err: msgs::LightningError) -> Self {
399                 Self { err, chan_id: None, shutdown_finish: None }
400         }
401         #[inline]
402         fn from_finish_shutdown(err: String, channel_id: [u8; 32], user_channel_id: u128, shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
403                 Self {
404                         err: LightningError {
405                                 err: err.clone(),
406                                 action: msgs::ErrorAction::SendErrorMessage {
407                                         msg: msgs::ErrorMessage {
408                                                 channel_id,
409                                                 data: err
410                                         },
411                                 },
412                         },
413                         chan_id: Some((channel_id, user_channel_id)),
414                         shutdown_finish: Some((shutdown_res, channel_update)),
415                 }
416         }
417         #[inline]
418         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
419                 Self {
420                         err: match err {
421                                 ChannelError::Warn(msg) =>  LightningError {
422                                         err: msg.clone(),
423                                         action: msgs::ErrorAction::SendWarningMessage {
424                                                 msg: msgs::WarningMessage {
425                                                         channel_id,
426                                                         data: msg
427                                                 },
428                                                 log_level: Level::Warn,
429                                         },
430                                 },
431                                 ChannelError::Ignore(msg) => LightningError {
432                                         err: msg,
433                                         action: msgs::ErrorAction::IgnoreError,
434                                 },
435                                 ChannelError::Close(msg) => LightningError {
436                                         err: msg.clone(),
437                                         action: msgs::ErrorAction::SendErrorMessage {
438                                                 msg: msgs::ErrorMessage {
439                                                         channel_id,
440                                                         data: msg
441                                                 },
442                                         },
443                                 },
444                         },
445                         chan_id: None,
446                         shutdown_finish: None,
447                 }
448         }
449 }
450
451 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
452 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
453 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
454 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
455 pub(super) const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
456
457 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
458 /// be sent in the order they appear in the return value, however sometimes the order needs to be
459 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
460 /// they were originally sent). In those cases, this enum is also returned.
461 #[derive(Clone, PartialEq)]
462 pub(super) enum RAACommitmentOrder {
463         /// Send the CommitmentUpdate messages first
464         CommitmentFirst,
465         /// Send the RevokeAndACK message first
466         RevokeAndACKFirst,
467 }
468
469 /// Information about a payment which is currently being claimed.
470 struct ClaimingPayment {
471         amount_msat: u64,
472         payment_purpose: events::PaymentPurpose,
473         receiver_node_id: PublicKey,
474 }
475 impl_writeable_tlv_based!(ClaimingPayment, {
476         (0, amount_msat, required),
477         (2, payment_purpose, required),
478         (4, receiver_node_id, required),
479 });
480
481 struct ClaimablePayment {
482         purpose: events::PaymentPurpose,
483         onion_fields: Option<RecipientOnionFields>,
484         htlcs: Vec<ClaimableHTLC>,
485 }
486
487 /// Information about claimable or being-claimed payments
488 struct ClaimablePayments {
489         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
490         /// failed/claimed by the user.
491         ///
492         /// Note that, no consistency guarantees are made about the channels given here actually
493         /// existing anymore by the time you go to read them!
494         ///
495         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
496         /// we don't get a duplicate payment.
497         claimable_payments: HashMap<PaymentHash, ClaimablePayment>,
498
499         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
500         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
501         /// as an [`events::Event::PaymentClaimed`].
502         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
503 }
504
505 /// Events which we process internally but cannot be processed immediately at the generation site
506 /// usually because we're running pre-full-init. They are handled immediately once we detect we are
507 /// running normally, and specifically must be processed before any other non-background
508 /// [`ChannelMonitorUpdate`]s are applied.
509 enum BackgroundEvent {
510         /// Handle a ChannelMonitorUpdate which closes the channel. This is only separated from
511         /// [`Self::MonitorUpdateRegeneratedOnStartup`] as the maybe-non-closing variant needs a public
512         /// key to handle channel resumption, whereas if the channel has been force-closed we do not
513         /// need the counterparty node_id.
514         ///
515         /// Note that any such events are lost on shutdown, so in general they must be updates which
516         /// are regenerated on startup.
517         ClosingMonitorUpdateRegeneratedOnStartup((OutPoint, ChannelMonitorUpdate)),
518         /// Handle a ChannelMonitorUpdate which may or may not close the channel and may unblock the
519         /// channel to continue normal operation.
520         ///
521         /// In general this should be used rather than
522         /// [`Self::ClosingMonitorUpdateRegeneratedOnStartup`], however in cases where the
523         /// `counterparty_node_id` is not available as the channel has closed from a [`ChannelMonitor`]
524         /// error the other variant is acceptable.
525         ///
526         /// Note that any such events are lost on shutdown, so in general they must be updates which
527         /// are regenerated on startup.
528         MonitorUpdateRegeneratedOnStartup {
529                 counterparty_node_id: PublicKey,
530                 funding_txo: OutPoint,
531                 update: ChannelMonitorUpdate
532         },
533 }
534
535 #[derive(Debug)]
536 pub(crate) enum MonitorUpdateCompletionAction {
537         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
538         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
539         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
540         /// event can be generated.
541         PaymentClaimed { payment_hash: PaymentHash },
542         /// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
543         /// operation of another channel.
544         ///
545         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
546         /// from completing a monitor update which removes the payment preimage until the inbound edge
547         /// completes a monitor update containing the payment preimage. In that case, after the inbound
548         /// edge completes, we will surface an [`Event::PaymentForwarded`] as well as unblock the
549         /// outbound edge.
550         EmitEventAndFreeOtherChannel {
551                 event: events::Event,
552                 downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, RAAMonitorUpdateBlockingAction)>,
553         },
554 }
555
556 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
557         (0, PaymentClaimed) => { (0, payment_hash, required) },
558         (2, EmitEventAndFreeOtherChannel) => {
559                 (0, event, upgradable_required),
560                 // LDK prior to 0.0.116 did not have this field as the monitor update application order was
561                 // required by clients. If we downgrade to something prior to 0.0.116 this may result in
562                 // monitor updates which aren't properly blocked or resumed, however that's fine - we don't
563                 // support async monitor updates even in LDK 0.0.116 and once we do we'll require no
564                 // downgrades to prior versions.
565                 (1, downstream_counterparty_and_funding_outpoint, option),
566         },
567 );
568
569 #[derive(Clone, Debug, PartialEq, Eq)]
570 pub(crate) enum EventCompletionAction {
571         ReleaseRAAChannelMonitorUpdate {
572                 counterparty_node_id: PublicKey,
573                 channel_funding_outpoint: OutPoint,
574         },
575 }
576 impl_writeable_tlv_based_enum!(EventCompletionAction,
577         (0, ReleaseRAAChannelMonitorUpdate) => {
578                 (0, channel_funding_outpoint, required),
579                 (2, counterparty_node_id, required),
580         };
581 );
582
583 #[derive(Clone, PartialEq, Eq, Debug)]
584 /// If something is blocked on the completion of an RAA-generated [`ChannelMonitorUpdate`] we track
585 /// the blocked action here. See enum variants for more info.
586 pub(crate) enum RAAMonitorUpdateBlockingAction {
587         /// A forwarded payment was claimed. We block the downstream channel completing its monitor
588         /// update which removes the HTLC preimage until the upstream channel has gotten the preimage
589         /// durably to disk.
590         ForwardedPaymentInboundClaim {
591                 /// The upstream channel ID (i.e. the inbound edge).
592                 channel_id: [u8; 32],
593                 /// The HTLC ID on the inbound edge.
594                 htlc_id: u64,
595         },
596 }
597
598 impl RAAMonitorUpdateBlockingAction {
599         #[allow(unused)]
600         fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
601                 Self::ForwardedPaymentInboundClaim {
602                         channel_id: prev_hop.outpoint.to_channel_id(),
603                         htlc_id: prev_hop.htlc_id,
604                 }
605         }
606 }
607
608 impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
609         (0, ForwardedPaymentInboundClaim) => { (0, channel_id, required), (2, htlc_id, required) }
610 ;);
611
612
613 /// State we hold per-peer.
614 pub(super) struct PeerState<Signer: ChannelSigner> {
615         /// `channel_id` -> `Channel`.
616         ///
617         /// Holds all funded channels where the peer is the counterparty.
618         pub(super) channel_by_id: HashMap<[u8; 32], Channel<Signer>>,
619         /// `temporary_channel_id` -> `OutboundV1Channel`.
620         ///
621         /// Holds all outbound V1 channels where the peer is the counterparty. Once an outbound channel has
622         /// been assigned a `channel_id`, the entry in this map is removed and one is created in
623         /// `channel_by_id`.
624         pub(super) outbound_v1_channel_by_id: HashMap<[u8; 32], OutboundV1Channel<Signer>>,
625         /// `temporary_channel_id` -> `InboundV1Channel`.
626         ///
627         /// Holds all inbound V1 channels where the peer is the counterparty. Once an inbound channel has
628         /// been assigned a `channel_id`, the entry in this map is removed and one is created in
629         /// `channel_by_id`.
630         pub(super) inbound_v1_channel_by_id: HashMap<[u8; 32], InboundV1Channel<Signer>>,
631         /// The latest `InitFeatures` we heard from the peer.
632         latest_features: InitFeatures,
633         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
634         /// for broadcast messages, where ordering isn't as strict).
635         pub(super) pending_msg_events: Vec<MessageSendEvent>,
636         /// Map from Channel IDs to pending [`ChannelMonitorUpdate`]s which have been passed to the
637         /// user but which have not yet completed.
638         ///
639         /// Note that the channel may no longer exist. For example if the channel was closed but we
640         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
641         /// for a missing channel.
642         in_flight_monitor_updates: BTreeMap<OutPoint, Vec<ChannelMonitorUpdate>>,
643         /// Map from a specific channel to some action(s) that should be taken when all pending
644         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
645         ///
646         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
647         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
648         /// channels with a peer this will just be one allocation and will amount to a linear list of
649         /// channels to walk, avoiding the whole hashing rigmarole.
650         ///
651         /// Note that the channel may no longer exist. For example, if a channel was closed but we
652         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
653         /// for a missing channel. While a malicious peer could construct a second channel with the
654         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
655         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
656         /// duplicates do not occur, so such channels should fail without a monitor update completing.
657         monitor_update_blocked_actions: BTreeMap<[u8; 32], Vec<MonitorUpdateCompletionAction>>,
658         /// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
659         /// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
660         /// will remove a preimage that needs to be durably in an upstream channel first), we put an
661         /// entry here to note that the channel with the key's ID is blocked on a set of actions.
662         actions_blocking_raa_monitor_updates: BTreeMap<[u8; 32], Vec<RAAMonitorUpdateBlockingAction>>,
663         /// The peer is currently connected (i.e. we've seen a
664         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
665         /// [`ChannelMessageHandler::peer_disconnected`].
666         is_connected: bool,
667 }
668
669 impl <Signer: ChannelSigner> PeerState<Signer> {
670         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
671         /// If true is passed for `require_disconnected`, the function will return false if we haven't
672         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
673         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
674                 if require_disconnected && self.is_connected {
675                         return false
676                 }
677                 self.channel_by_id.is_empty() && self.monitor_update_blocked_actions.is_empty()
678                         && self.in_flight_monitor_updates.is_empty()
679         }
680
681         // Returns a count of all channels we have with this peer, including pending channels.
682         fn total_channel_count(&self) -> usize {
683                 self.channel_by_id.len() +
684                         self.outbound_v1_channel_by_id.len() +
685                         self.inbound_v1_channel_by_id.len()
686         }
687
688         // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer.
689         fn has_channel(&self, channel_id: &[u8; 32]) -> bool {
690                 self.channel_by_id.contains_key(channel_id) ||
691                         self.outbound_v1_channel_by_id.contains_key(channel_id) ||
692                         self.inbound_v1_channel_by_id.contains_key(channel_id)
693         }
694 }
695
696 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
697 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
698 ///
699 /// For users who don't want to bother doing their own payment preimage storage, we also store that
700 /// here.
701 ///
702 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
703 /// and instead encoding it in the payment secret.
704 struct PendingInboundPayment {
705         /// The payment secret that the sender must use for us to accept this payment
706         payment_secret: PaymentSecret,
707         /// Time at which this HTLC expires - blocks with a header time above this value will result in
708         /// this payment being removed.
709         expiry_time: u64,
710         /// Arbitrary identifier the user specifies (or not)
711         user_payment_id: u64,
712         // Other required attributes of the payment, optionally enforced:
713         payment_preimage: Option<PaymentPreimage>,
714         min_value_msat: Option<u64>,
715 }
716
717 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
718 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
719 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
720 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
721 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
722 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
723 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
724 /// of [`KeysManager`] and [`DefaultRouter`].
725 ///
726 /// This is not exported to bindings users as Arcs don't make sense in bindings
727 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
728         Arc<M>,
729         Arc<T>,
730         Arc<KeysManager>,
731         Arc<KeysManager>,
732         Arc<KeysManager>,
733         Arc<F>,
734         Arc<DefaultRouter<
735                 Arc<NetworkGraph<Arc<L>>>,
736                 Arc<L>,
737                 Arc<Mutex<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
738                 ProbabilisticScoringFeeParameters,
739                 ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
740         >>,
741         Arc<L>
742 >;
743
744 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
745 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
746 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
747 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
748 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
749 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
750 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
751 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
752 /// of [`KeysManager`] and [`DefaultRouter`].
753 ///
754 /// This is not exported to bindings users as Arcs don't make sense in bindings
755 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
756         ChannelManager<
757                 &'a M,
758                 &'b T,
759                 &'c KeysManager,
760                 &'c KeysManager,
761                 &'c KeysManager,
762                 &'d F,
763                 &'e DefaultRouter<
764                         &'f NetworkGraph<&'g L>,
765                         &'g L,
766                         &'h Mutex<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
767                         ProbabilisticScoringFeeParameters,
768                         ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
769                 >,
770                 &'g L
771         >;
772
773 macro_rules! define_test_pub_trait { ($vis: vis) => {
774 /// A trivial trait which describes any [`ChannelManager`] used in testing.
775 $vis trait AChannelManager {
776         type Watch: chain::Watch<Self::Signer> + ?Sized;
777         type M: Deref<Target = Self::Watch>;
778         type Broadcaster: BroadcasterInterface + ?Sized;
779         type T: Deref<Target = Self::Broadcaster>;
780         type EntropySource: EntropySource + ?Sized;
781         type ES: Deref<Target = Self::EntropySource>;
782         type NodeSigner: NodeSigner + ?Sized;
783         type NS: Deref<Target = Self::NodeSigner>;
784         type Signer: WriteableEcdsaChannelSigner + Sized;
785         type SignerProvider: SignerProvider<Signer = Self::Signer> + ?Sized;
786         type SP: Deref<Target = Self::SignerProvider>;
787         type FeeEstimator: FeeEstimator + ?Sized;
788         type F: Deref<Target = Self::FeeEstimator>;
789         type Router: Router + ?Sized;
790         type R: Deref<Target = Self::Router>;
791         type Logger: Logger + ?Sized;
792         type L: Deref<Target = Self::Logger>;
793         fn get_cm(&self) -> &ChannelManager<Self::M, Self::T, Self::ES, Self::NS, Self::SP, Self::F, Self::R, Self::L>;
794 }
795 } }
796 #[cfg(any(test, feature = "_test_utils"))]
797 define_test_pub_trait!(pub);
798 #[cfg(not(any(test, feature = "_test_utils")))]
799 define_test_pub_trait!(pub(crate));
800 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> AChannelManager
801 for ChannelManager<M, T, ES, NS, SP, F, R, L>
802 where
803         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
804         T::Target: BroadcasterInterface,
805         ES::Target: EntropySource,
806         NS::Target: NodeSigner,
807         SP::Target: SignerProvider,
808         F::Target: FeeEstimator,
809         R::Target: Router,
810         L::Target: Logger,
811 {
812         type Watch = M::Target;
813         type M = M;
814         type Broadcaster = T::Target;
815         type T = T;
816         type EntropySource = ES::Target;
817         type ES = ES;
818         type NodeSigner = NS::Target;
819         type NS = NS;
820         type Signer = <SP::Target as SignerProvider>::Signer;
821         type SignerProvider = SP::Target;
822         type SP = SP;
823         type FeeEstimator = F::Target;
824         type F = F;
825         type Router = R::Target;
826         type R = R;
827         type Logger = L::Target;
828         type L = L;
829         fn get_cm(&self) -> &ChannelManager<M, T, ES, NS, SP, F, R, L> { self }
830 }
831
832 /// Manager which keeps track of a number of channels and sends messages to the appropriate
833 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
834 ///
835 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
836 /// to individual Channels.
837 ///
838 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
839 /// all peers during write/read (though does not modify this instance, only the instance being
840 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
841 /// called [`funding_transaction_generated`] for outbound channels) being closed.
842 ///
843 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
844 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST write each monitor update out to disk before
845 /// returning from [`chain::Watch::watch_channel`]/[`update_channel`], with ChannelManagers, writing updates
846 /// happens out-of-band (and will prevent any other `ChannelManager` operations from occurring during
847 /// the serialization process). If the deserialized version is out-of-date compared to the
848 /// [`ChannelMonitor`] passed by reference to [`read`], those channels will be force-closed based on the
849 /// `ChannelMonitor` state and no funds will be lost (mod on-chain transaction fees).
850 ///
851 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
852 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
853 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
854 ///
855 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
856 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
857 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
858 /// offline for a full minute. In order to track this, you must call
859 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
860 ///
861 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
862 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
863 /// not have a channel with being unable to connect to us or open new channels with us if we have
864 /// many peers with unfunded channels.
865 ///
866 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
867 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
868 /// never limited. Please ensure you limit the count of such channels yourself.
869 ///
870 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
871 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
872 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
873 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
874 /// you're using lightning-net-tokio.
875 ///
876 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
877 /// [`funding_created`]: msgs::FundingCreated
878 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
879 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
880 /// [`update_channel`]: chain::Watch::update_channel
881 /// [`ChannelUpdate`]: msgs::ChannelUpdate
882 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
883 /// [`read`]: ReadableArgs::read
884 //
885 // Lock order:
886 // The tree structure below illustrates the lock order requirements for the different locks of the
887 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
888 // and should then be taken in the order of the lowest to the highest level in the tree.
889 // Note that locks on different branches shall not be taken at the same time, as doing so will
890 // create a new lock order for those specific locks in the order they were taken.
891 //
892 // Lock order tree:
893 //
894 // `total_consistency_lock`
895 //  |
896 //  |__`forward_htlcs`
897 //  |   |
898 //  |   |__`pending_intercepted_htlcs`
899 //  |
900 //  |__`per_peer_state`
901 //  |   |
902 //  |   |__`pending_inbound_payments`
903 //  |       |
904 //  |       |__`claimable_payments`
905 //  |       |
906 //  |       |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
907 //  |           |
908 //  |           |__`peer_state`
909 //  |               |
910 //  |               |__`id_to_peer`
911 //  |               |
912 //  |               |__`short_to_chan_info`
913 //  |               |
914 //  |               |__`outbound_scid_aliases`
915 //  |               |
916 //  |               |__`best_block`
917 //  |               |
918 //  |               |__`pending_events`
919 //  |                   |
920 //  |                   |__`pending_background_events`
921 //
922 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
923 where
924         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
925         T::Target: BroadcasterInterface,
926         ES::Target: EntropySource,
927         NS::Target: NodeSigner,
928         SP::Target: SignerProvider,
929         F::Target: FeeEstimator,
930         R::Target: Router,
931         L::Target: Logger,
932 {
933         default_configuration: UserConfig,
934         genesis_hash: BlockHash,
935         fee_estimator: LowerBoundedFeeEstimator<F>,
936         chain_monitor: M,
937         tx_broadcaster: T,
938         #[allow(unused)]
939         router: R,
940
941         /// See `ChannelManager` struct-level documentation for lock order requirements.
942         #[cfg(test)]
943         pub(super) best_block: RwLock<BestBlock>,
944         #[cfg(not(test))]
945         best_block: RwLock<BestBlock>,
946         secp_ctx: Secp256k1<secp256k1::All>,
947
948         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
949         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
950         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
951         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
952         ///
953         /// See `ChannelManager` struct-level documentation for lock order requirements.
954         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
955
956         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
957         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
958         /// (if the channel has been force-closed), however we track them here to prevent duplicative
959         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
960         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
961         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
962         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
963         /// after reloading from disk while replaying blocks against ChannelMonitors.
964         ///
965         /// See `PendingOutboundPayment` documentation for more info.
966         ///
967         /// See `ChannelManager` struct-level documentation for lock order requirements.
968         pending_outbound_payments: OutboundPayments,
969
970         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
971         ///
972         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
973         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
974         /// and via the classic SCID.
975         ///
976         /// Note that no consistency guarantees are made about the existence of a channel with the
977         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
978         ///
979         /// See `ChannelManager` struct-level documentation for lock order requirements.
980         #[cfg(test)]
981         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
982         #[cfg(not(test))]
983         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
984         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
985         /// until the user tells us what we should do with them.
986         ///
987         /// See `ChannelManager` struct-level documentation for lock order requirements.
988         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
989
990         /// The sets of payments which are claimable or currently being claimed. See
991         /// [`ClaimablePayments`]' individual field docs for more info.
992         ///
993         /// See `ChannelManager` struct-level documentation for lock order requirements.
994         claimable_payments: Mutex<ClaimablePayments>,
995
996         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
997         /// and some closed channels which reached a usable state prior to being closed. This is used
998         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
999         /// active channel list on load.
1000         ///
1001         /// See `ChannelManager` struct-level documentation for lock order requirements.
1002         outbound_scid_aliases: Mutex<HashSet<u64>>,
1003
1004         /// `channel_id` -> `counterparty_node_id`.
1005         ///
1006         /// Only `channel_id`s are allowed as keys in this map, and not `temporary_channel_id`s. As
1007         /// multiple channels with the same `temporary_channel_id` to different peers can exist,
1008         /// allowing `temporary_channel_id`s in this map would cause collisions for such channels.
1009         ///
1010         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
1011         /// the corresponding channel for the event, as we only have access to the `channel_id` during
1012         /// the handling of the events.
1013         ///
1014         /// Note that no consistency guarantees are made about the existence of a peer with the
1015         /// `counterparty_node_id` in our other maps.
1016         ///
1017         /// TODO:
1018         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
1019         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
1020         /// would break backwards compatability.
1021         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
1022         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
1023         /// required to access the channel with the `counterparty_node_id`.
1024         ///
1025         /// See `ChannelManager` struct-level documentation for lock order requirements.
1026         id_to_peer: Mutex<HashMap<[u8; 32], PublicKey>>,
1027
1028         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
1029         ///
1030         /// Outbound SCID aliases are added here once the channel is available for normal use, with
1031         /// SCIDs being added once the funding transaction is confirmed at the channel's required
1032         /// confirmation depth.
1033         ///
1034         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
1035         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
1036         /// channel with the `channel_id` in our other maps.
1037         ///
1038         /// See `ChannelManager` struct-level documentation for lock order requirements.
1039         #[cfg(test)]
1040         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, [u8; 32])>>,
1041         #[cfg(not(test))]
1042         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, [u8; 32])>>,
1043
1044         our_network_pubkey: PublicKey,
1045
1046         inbound_payment_key: inbound_payment::ExpandedKey,
1047
1048         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
1049         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
1050         /// we encrypt the namespace identifier using these bytes.
1051         ///
1052         /// [fake scids]: crate::util::scid_utils::fake_scid
1053         fake_scid_rand_bytes: [u8; 32],
1054
1055         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
1056         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
1057         /// keeping additional state.
1058         probing_cookie_secret: [u8; 32],
1059
1060         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
1061         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
1062         /// very far in the past, and can only ever be up to two hours in the future.
1063         highest_seen_timestamp: AtomicUsize,
1064
1065         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
1066         /// basis, as well as the peer's latest features.
1067         ///
1068         /// If we are connected to a peer we always at least have an entry here, even if no channels
1069         /// are currently open with that peer.
1070         ///
1071         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
1072         /// operate on the inner value freely. This opens up for parallel per-peer operation for
1073         /// channels.
1074         ///
1075         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
1076         ///
1077         /// See `ChannelManager` struct-level documentation for lock order requirements.
1078         #[cfg(not(any(test, feature = "_test_utils")))]
1079         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<<SP::Target as SignerProvider>::Signer>>>>,
1080         #[cfg(any(test, feature = "_test_utils"))]
1081         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<<SP::Target as SignerProvider>::Signer>>>>,
1082
1083         /// The set of events which we need to give to the user to handle. In some cases an event may
1084         /// require some further action after the user handles it (currently only blocking a monitor
1085         /// update from being handed to the user to ensure the included changes to the channel state
1086         /// are handled by the user before they're persisted durably to disk). In that case, the second
1087         /// element in the tuple is set to `Some` with further details of the action.
1088         ///
1089         /// Note that events MUST NOT be removed from pending_events after deserialization, as they
1090         /// could be in the middle of being processed without the direct mutex held.
1091         ///
1092         /// See `ChannelManager` struct-level documentation for lock order requirements.
1093         pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1094         /// A simple atomic flag to ensure only one task at a time can be processing events asynchronously.
1095         pending_events_processor: AtomicBool,
1096
1097         /// If we are running during init (either directly during the deserialization method or in
1098         /// block connection methods which run after deserialization but before normal operation) we
1099         /// cannot provide the user with [`ChannelMonitorUpdate`]s through the normal update flow -
1100         /// prior to normal operation the user may not have loaded the [`ChannelMonitor`]s into their
1101         /// [`ChainMonitor`] and thus attempting to update it will fail or panic.
1102         ///
1103         /// Thus, we place them here to be handled as soon as possible once we are running normally.
1104         ///
1105         /// See `ChannelManager` struct-level documentation for lock order requirements.
1106         ///
1107         /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1108         pending_background_events: Mutex<Vec<BackgroundEvent>>,
1109         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
1110         /// Essentially just when we're serializing ourselves out.
1111         /// Taken first everywhere where we are making changes before any other locks.
1112         /// When acquiring this lock in read mode, rather than acquiring it directly, call
1113         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
1114         /// Notifier the lock contains sends out a notification when the lock is released.
1115         total_consistency_lock: RwLock<()>,
1116
1117         #[cfg(debug_assertions)]
1118         background_events_processed_since_startup: AtomicBool,
1119
1120         persistence_notifier: Notifier,
1121
1122         entropy_source: ES,
1123         node_signer: NS,
1124         signer_provider: SP,
1125
1126         logger: L,
1127 }
1128
1129 /// Chain-related parameters used to construct a new `ChannelManager`.
1130 ///
1131 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1132 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1133 /// are not needed when deserializing a previously constructed `ChannelManager`.
1134 #[derive(Clone, Copy, PartialEq)]
1135 pub struct ChainParameters {
1136         /// The network for determining the `chain_hash` in Lightning messages.
1137         pub network: Network,
1138
1139         /// The hash and height of the latest block successfully connected.
1140         ///
1141         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1142         pub best_block: BestBlock,
1143 }
1144
1145 #[derive(Copy, Clone, PartialEq)]
1146 #[must_use]
1147 enum NotifyOption {
1148         DoPersist,
1149         SkipPersist,
1150 }
1151
1152 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
1153 /// desirable to notify any listeners on `await_persistable_update_timeout`/
1154 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
1155 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
1156 /// sending the aforementioned notification (since the lock being released indicates that the
1157 /// updates are ready for persistence).
1158 ///
1159 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
1160 /// notify or not based on whether relevant changes have been made, providing a closure to
1161 /// `optionally_notify` which returns a `NotifyOption`.
1162 struct PersistenceNotifierGuard<'a, F: Fn() -> NotifyOption> {
1163         persistence_notifier: &'a Notifier,
1164         should_persist: F,
1165         // We hold onto this result so the lock doesn't get released immediately.
1166         _read_guard: RwLockReadGuard<'a, ()>,
1167 }
1168
1169 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
1170         fn notify_on_drop<C: AChannelManager>(cm: &'a C) -> PersistenceNotifierGuard<'a, impl Fn() -> NotifyOption> {
1171                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1172                 let _ = cm.get_cm().process_background_events(); // We always persist
1173
1174                 PersistenceNotifierGuard {
1175                         persistence_notifier: &cm.get_cm().persistence_notifier,
1176                         should_persist: || -> NotifyOption { NotifyOption::DoPersist },
1177                         _read_guard: read_guard,
1178                 }
1179
1180         }
1181
1182         /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated,
1183         /// [`ChannelManager::process_background_events`] MUST be called first.
1184         fn optionally_notify<F: Fn() -> NotifyOption>(lock: &'a RwLock<()>, notifier: &'a Notifier, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
1185                 let read_guard = lock.read().unwrap();
1186
1187                 PersistenceNotifierGuard {
1188                         persistence_notifier: notifier,
1189                         should_persist: persist_check,
1190                         _read_guard: read_guard,
1191                 }
1192         }
1193 }
1194
1195 impl<'a, F: Fn() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
1196         fn drop(&mut self) {
1197                 if (self.should_persist)() == NotifyOption::DoPersist {
1198                         self.persistence_notifier.notify();
1199                 }
1200         }
1201 }
1202
1203 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1204 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1205 ///
1206 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1207 ///
1208 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1209 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
1210 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
1211 /// the maximum required amount in lnd as of March 2021.
1212 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
1213
1214 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1215 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1216 ///
1217 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1218 ///
1219 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1220 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
1221 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
1222 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
1223 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
1224 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
1225 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
1226 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
1227 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
1228 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
1229 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
1230 // routing failure for any HTLC sender picking up an LDK node among the first hops.
1231 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
1232
1233 /// Minimum CLTV difference between the current block height and received inbound payments.
1234 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1235 /// this value.
1236 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
1237 // any payments to succeed. Further, we don't want payments to fail if a block was found while
1238 // a payment was being routed, so we add an extra block to be safe.
1239 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
1240
1241 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
1242 // ie that if the next-hop peer fails the HTLC within
1243 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
1244 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
1245 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
1246 // LATENCY_GRACE_PERIOD_BLOCKS.
1247 #[deny(const_err)]
1248 #[allow(dead_code)]
1249 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;
1250
1251 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
1252 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
1253 #[deny(const_err)]
1254 #[allow(dead_code)]
1255 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
1256
1257 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
1258 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
1259
1260 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until we time-out the
1261 /// idempotency of payments by [`PaymentId`]. See
1262 /// [`OutboundPayments::remove_stale_resolved_payments`].
1263 pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
1264
1265 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is disconnected
1266 /// until we mark the channel disabled and gossip the update.
1267 pub(crate) const DISABLE_GOSSIP_TICKS: u8 = 10;
1268
1269 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is connected until
1270 /// we mark the channel enabled and gossip the update.
1271 pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
1272
1273 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1274 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1275 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1276 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1277
1278 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1279 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1280 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1281
1282 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1283 /// many peers we reject new (inbound) connections.
1284 const MAX_NO_CHANNEL_PEERS: usize = 250;
1285
1286 /// Information needed for constructing an invoice route hint for this channel.
1287 #[derive(Clone, Debug, PartialEq)]
1288 pub struct CounterpartyForwardingInfo {
1289         /// Base routing fee in millisatoshis.
1290         pub fee_base_msat: u32,
1291         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1292         pub fee_proportional_millionths: u32,
1293         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1294         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1295         /// `cltv_expiry_delta` for more details.
1296         pub cltv_expiry_delta: u16,
1297 }
1298
1299 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1300 /// to better separate parameters.
1301 #[derive(Clone, Debug, PartialEq)]
1302 pub struct ChannelCounterparty {
1303         /// The node_id of our counterparty
1304         pub node_id: PublicKey,
1305         /// The Features the channel counterparty provided upon last connection.
1306         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1307         /// many routing-relevant features are present in the init context.
1308         pub features: InitFeatures,
1309         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1310         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1311         /// claiming at least this value on chain.
1312         ///
1313         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1314         ///
1315         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1316         pub unspendable_punishment_reserve: u64,
1317         /// Information on the fees and requirements that the counterparty requires when forwarding
1318         /// payments to us through this channel.
1319         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1320         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1321         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1322         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1323         pub outbound_htlc_minimum_msat: Option<u64>,
1324         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1325         pub outbound_htlc_maximum_msat: Option<u64>,
1326 }
1327
1328 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1329 #[derive(Clone, Debug, PartialEq)]
1330 pub struct ChannelDetails {
1331         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1332         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1333         /// Note that this means this value is *not* persistent - it can change once during the
1334         /// lifetime of the channel.
1335         pub channel_id: [u8; 32],
1336         /// Parameters which apply to our counterparty. See individual fields for more information.
1337         pub counterparty: ChannelCounterparty,
1338         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1339         /// our counterparty already.
1340         ///
1341         /// Note that, if this has been set, `channel_id` will be equivalent to
1342         /// `funding_txo.unwrap().to_channel_id()`.
1343         pub funding_txo: Option<OutPoint>,
1344         /// The features which this channel operates with. See individual features for more info.
1345         ///
1346         /// `None` until negotiation completes and the channel type is finalized.
1347         pub channel_type: Option<ChannelTypeFeatures>,
1348         /// The position of the funding transaction in the chain. None if the funding transaction has
1349         /// not yet been confirmed and the channel fully opened.
1350         ///
1351         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1352         /// payments instead of this. See [`get_inbound_payment_scid`].
1353         ///
1354         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1355         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1356         ///
1357         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1358         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1359         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1360         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1361         /// [`confirmations_required`]: Self::confirmations_required
1362         pub short_channel_id: Option<u64>,
1363         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1364         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1365         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1366         /// `Some(0)`).
1367         ///
1368         /// This will be `None` as long as the channel is not available for routing outbound payments.
1369         ///
1370         /// [`short_channel_id`]: Self::short_channel_id
1371         /// [`confirmations_required`]: Self::confirmations_required
1372         pub outbound_scid_alias: Option<u64>,
1373         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1374         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1375         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1376         /// when they see a payment to be routed to us.
1377         ///
1378         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1379         /// previous values for inbound payment forwarding.
1380         ///
1381         /// [`short_channel_id`]: Self::short_channel_id
1382         pub inbound_scid_alias: Option<u64>,
1383         /// The value, in satoshis, of this channel as appears in the funding output
1384         pub channel_value_satoshis: u64,
1385         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1386         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1387         /// this value on chain.
1388         ///
1389         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1390         ///
1391         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1392         ///
1393         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1394         pub unspendable_punishment_reserve: Option<u64>,
1395         /// The `user_channel_id` passed in to create_channel, or a random value if the channel was
1396         /// inbound. This may be zero for inbound channels serialized with LDK versions prior to
1397         /// 0.0.113.
1398         pub user_channel_id: u128,
1399         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1400         /// which is applied to commitment and HTLC transactions.
1401         ///
1402         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1403         pub feerate_sat_per_1000_weight: Option<u32>,
1404         /// Our total balance.  This is the amount we would get if we close the channel.
1405         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1406         /// amount is not likely to be recoverable on close.
1407         ///
1408         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1409         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1410         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1411         /// This does not consider any on-chain fees.
1412         ///
1413         /// See also [`ChannelDetails::outbound_capacity_msat`]
1414         pub balance_msat: u64,
1415         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1416         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1417         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1418         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1419         ///
1420         /// See also [`ChannelDetails::balance_msat`]
1421         ///
1422         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1423         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1424         /// should be able to spend nearly this amount.
1425         pub outbound_capacity_msat: u64,
1426         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1427         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1428         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1429         /// to use a limit as close as possible to the HTLC limit we can currently send.
1430         ///
1431         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`],
1432         /// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`].
1433         pub next_outbound_htlc_limit_msat: u64,
1434         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
1435         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
1436         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
1437         /// route which is valid.
1438         pub next_outbound_htlc_minimum_msat: u64,
1439         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1440         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1441         /// available for inclusion in new inbound HTLCs).
1442         /// Note that there are some corner cases not fully handled here, so the actual available
1443         /// inbound capacity may be slightly higher than this.
1444         ///
1445         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1446         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1447         /// However, our counterparty should be able to spend nearly this amount.
1448         pub inbound_capacity_msat: u64,
1449         /// The number of required confirmations on the funding transaction before the funding will be
1450         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1451         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1452         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1453         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1454         ///
1455         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1456         ///
1457         /// [`is_outbound`]: ChannelDetails::is_outbound
1458         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1459         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1460         pub confirmations_required: Option<u32>,
1461         /// The current number of confirmations on the funding transaction.
1462         ///
1463         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1464         pub confirmations: Option<u32>,
1465         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1466         /// until we can claim our funds after we force-close the channel. During this time our
1467         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1468         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1469         /// time to claim our non-HTLC-encumbered funds.
1470         ///
1471         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1472         pub force_close_spend_delay: Option<u16>,
1473         /// True if the channel was initiated (and thus funded) by us.
1474         pub is_outbound: bool,
1475         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1476         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1477         /// required confirmation count has been reached (and we were connected to the peer at some
1478         /// point after the funding transaction received enough confirmations). The required
1479         /// confirmation count is provided in [`confirmations_required`].
1480         ///
1481         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1482         pub is_channel_ready: bool,
1483         /// The stage of the channel's shutdown.
1484         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
1485         pub channel_shutdown_state: Option<ChannelShutdownState>,
1486         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1487         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1488         ///
1489         /// This is a strict superset of `is_channel_ready`.
1490         pub is_usable: bool,
1491         /// True if this channel is (or will be) publicly-announced.
1492         pub is_public: bool,
1493         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1494         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1495         pub inbound_htlc_minimum_msat: Option<u64>,
1496         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1497         pub inbound_htlc_maximum_msat: Option<u64>,
1498         /// Set of configurable parameters that affect channel operation.
1499         ///
1500         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1501         pub config: Option<ChannelConfig>,
1502 }
1503
1504 impl ChannelDetails {
1505         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1506         /// This should be used for providing invoice hints or in any other context where our
1507         /// counterparty will forward a payment to us.
1508         ///
1509         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1510         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1511         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1512                 self.inbound_scid_alias.or(self.short_channel_id)
1513         }
1514
1515         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1516         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1517         /// we're sending or forwarding a payment outbound over this channel.
1518         ///
1519         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1520         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1521         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1522                 self.short_channel_id.or(self.outbound_scid_alias)
1523         }
1524
1525         fn from_channel_context<Signer: WriteableEcdsaChannelSigner, F: Deref>(
1526                 context: &ChannelContext<Signer>, best_block_height: u32, latest_features: InitFeatures,
1527                 fee_estimator: &LowerBoundedFeeEstimator<F>
1528         ) -> Self
1529         where F::Target: FeeEstimator
1530         {
1531                 let balance = context.get_available_balances(fee_estimator);
1532                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1533                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
1534                 ChannelDetails {
1535                         channel_id: context.channel_id(),
1536                         counterparty: ChannelCounterparty {
1537                                 node_id: context.get_counterparty_node_id(),
1538                                 features: latest_features,
1539                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1540                                 forwarding_info: context.counterparty_forwarding_info(),
1541                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1542                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1543                                 // message (as they are always the first message from the counterparty).
1544                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1545                                 // default `0` value set by `Channel::new_outbound`.
1546                                 outbound_htlc_minimum_msat: if context.have_received_message() {
1547                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
1548                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
1549                         },
1550                         funding_txo: context.get_funding_txo(),
1551                         // Note that accept_channel (or open_channel) is always the first message, so
1552                         // `have_received_message` indicates that type negotiation has completed.
1553                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
1554                         short_channel_id: context.get_short_channel_id(),
1555                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
1556                         inbound_scid_alias: context.latest_inbound_scid_alias(),
1557                         channel_value_satoshis: context.get_value_satoshis(),
1558                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
1559                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1560                         balance_msat: balance.balance_msat,
1561                         inbound_capacity_msat: balance.inbound_capacity_msat,
1562                         outbound_capacity_msat: balance.outbound_capacity_msat,
1563                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1564                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
1565                         user_channel_id: context.get_user_id(),
1566                         confirmations_required: context.minimum_depth(),
1567                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
1568                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
1569                         is_outbound: context.is_outbound(),
1570                         is_channel_ready: context.is_usable(),
1571                         is_usable: context.is_live(),
1572                         is_public: context.should_announce(),
1573                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
1574                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
1575                         config: Some(context.config()),
1576                         channel_shutdown_state: Some(context.shutdown_state()),
1577                 }
1578         }
1579 }
1580
1581 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1582 /// Further information on the details of the channel shutdown.
1583 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
1584 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
1585 /// the channel will be removed shortly.
1586 /// Also note, that in normal operation, peers could disconnect at any of these states
1587 /// and require peer re-connection before making progress onto other states
1588 pub enum ChannelShutdownState {
1589         /// Channel has not sent or received a shutdown message.
1590         NotShuttingDown,
1591         /// Local node has sent a shutdown message for this channel.
1592         ShutdownInitiated,
1593         /// Shutdown message exchanges have concluded and the channels are in the midst of
1594         /// resolving all existing open HTLCs before closing can continue.
1595         ResolvingHTLCs,
1596         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
1597         NegotiatingClosingFee,
1598         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
1599         /// to drop the channel.
1600         ShutdownComplete,
1601 }
1602
1603 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1604 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1605 #[derive(Debug, PartialEq)]
1606 pub enum RecentPaymentDetails {
1607         /// When a payment is still being sent and awaiting successful delivery.
1608         Pending {
1609                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1610                 /// abandoned.
1611                 payment_hash: PaymentHash,
1612                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1613                 /// not just the amount currently inflight.
1614                 total_msat: u64,
1615         },
1616         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1617         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1618         /// payment is removed from tracking.
1619         Fulfilled {
1620                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1621                 /// made before LDK version 0.0.104.
1622                 payment_hash: Option<PaymentHash>,
1623         },
1624         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1625         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1626         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1627         Abandoned {
1628                 /// Hash of the payment that we have given up trying to send.
1629                 payment_hash: PaymentHash,
1630         },
1631 }
1632
1633 /// Route hints used in constructing invoices for [phantom node payents].
1634 ///
1635 /// [phantom node payments]: crate::sign::PhantomKeysManager
1636 #[derive(Clone)]
1637 pub struct PhantomRouteHints {
1638         /// The list of channels to be included in the invoice route hints.
1639         pub channels: Vec<ChannelDetails>,
1640         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1641         /// route hints.
1642         pub phantom_scid: u64,
1643         /// The pubkey of the real backing node that would ultimately receive the payment.
1644         pub real_node_pubkey: PublicKey,
1645 }
1646
1647 macro_rules! handle_error {
1648         ($self: ident, $internal: expr, $counterparty_node_id: expr) => { {
1649                 // In testing, ensure there are no deadlocks where the lock is already held upon
1650                 // entering the macro.
1651                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1652                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1653
1654                 match $internal {
1655                         Ok(msg) => Ok(msg),
1656                         Err(MsgHandleErrInternal { err, chan_id, shutdown_finish }) => {
1657                                 let mut msg_events = Vec::with_capacity(2);
1658
1659                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1660                                         $self.finish_force_close_channel(shutdown_res);
1661                                         if let Some(update) = update_option {
1662                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1663                                                         msg: update
1664                                                 });
1665                                         }
1666                                         if let Some((channel_id, user_channel_id)) = chan_id {
1667                                                 $self.pending_events.lock().unwrap().push_back((events::Event::ChannelClosed {
1668                                                         channel_id, user_channel_id,
1669                                                         reason: ClosureReason::ProcessingError { err: err.err.clone() }
1670                                                 }, None));
1671                                         }
1672                                 }
1673
1674                                 log_error!($self.logger, "{}", err.err);
1675                                 if let msgs::ErrorAction::IgnoreError = err.action {
1676                                 } else {
1677                                         msg_events.push(events::MessageSendEvent::HandleError {
1678                                                 node_id: $counterparty_node_id,
1679                                                 action: err.action.clone()
1680                                         });
1681                                 }
1682
1683                                 if !msg_events.is_empty() {
1684                                         let per_peer_state = $self.per_peer_state.read().unwrap();
1685                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
1686                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
1687                                                 peer_state.pending_msg_events.append(&mut msg_events);
1688                                         }
1689                                 }
1690
1691                                 // Return error in case higher-API need one
1692                                 Err(err)
1693                         },
1694                 }
1695         } };
1696         ($self: ident, $internal: expr) => {
1697                 match $internal {
1698                         Ok(res) => Ok(res),
1699                         Err((chan, msg_handle_err)) => {
1700                                 let counterparty_node_id = chan.get_counterparty_node_id();
1701                                 handle_error!($self, Err(msg_handle_err), counterparty_node_id).map_err(|err| (chan, err))
1702                         },
1703                 }
1704         };
1705 }
1706
1707 macro_rules! update_maps_on_chan_removal {
1708         ($self: expr, $channel_context: expr) => {{
1709                 $self.id_to_peer.lock().unwrap().remove(&$channel_context.channel_id());
1710                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1711                 if let Some(short_id) = $channel_context.get_short_channel_id() {
1712                         short_to_chan_info.remove(&short_id);
1713                 } else {
1714                         // If the channel was never confirmed on-chain prior to its closure, remove the
1715                         // outbound SCID alias we used for it from the collision-prevention set. While we
1716                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
1717                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
1718                         // opening a million channels with us which are closed before we ever reach the funding
1719                         // stage.
1720                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel_context.outbound_scid_alias());
1721                         debug_assert!(alias_removed);
1722                 }
1723                 short_to_chan_info.remove(&$channel_context.outbound_scid_alias());
1724         }}
1725 }
1726
1727 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
1728 macro_rules! convert_chan_err {
1729         ($self: ident, $err: expr, $channel: expr, $channel_id: expr) => {
1730                 match $err {
1731                         ChannelError::Warn(msg) => {
1732                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), $channel_id.clone()))
1733                         },
1734                         ChannelError::Ignore(msg) => {
1735                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $channel_id.clone()))
1736                         },
1737                         ChannelError::Close(msg) => {
1738                                 log_error!($self.logger, "Closing channel {} due to close-required error: {}", log_bytes!($channel_id[..]), msg);
1739                                 update_maps_on_chan_removal!($self, &$channel.context);
1740                                 let shutdown_res = $channel.context.force_shutdown(true);
1741                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, $channel.context.get_user_id(),
1742                                         shutdown_res, $self.get_channel_update_for_broadcast(&$channel).ok()))
1743                         },
1744                 }
1745         };
1746         ($self: ident, $err: expr, $channel_context: expr, $channel_id: expr, PREFUNDED) => {
1747                 match $err {
1748                         // We should only ever have `ChannelError::Close` when prefunded channels error.
1749                         // In any case, just close the channel.
1750                         ChannelError::Warn(msg) | ChannelError::Ignore(msg) | ChannelError::Close(msg) => {
1751                                 log_error!($self.logger, "Closing prefunded channel {} due to an error: {}", log_bytes!($channel_id[..]), msg);
1752                                 update_maps_on_chan_removal!($self, &$channel_context);
1753                                 let shutdown_res = $channel_context.force_shutdown(false);
1754                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, $channel_context.get_user_id(),
1755                                         shutdown_res, None))
1756                         },
1757                 }
1758         }
1759 }
1760
1761 macro_rules! break_chan_entry {
1762         ($self: ident, $res: expr, $entry: expr) => {
1763                 match $res {
1764                         Ok(res) => res,
1765                         Err(e) => {
1766                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut(), $entry.key());
1767                                 if drop {
1768                                         $entry.remove_entry();
1769                                 }
1770                                 break Err(res);
1771                         }
1772                 }
1773         }
1774 }
1775
1776 macro_rules! try_v1_outbound_chan_entry {
1777         ($self: ident, $res: expr, $entry: expr) => {
1778                 match $res {
1779                         Ok(res) => res,
1780                         Err(e) => {
1781                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut().context, $entry.key(), PREFUNDED);
1782                                 if drop {
1783                                         $entry.remove_entry();
1784                                 }
1785                                 return Err(res);
1786                         }
1787                 }
1788         }
1789 }
1790
1791 macro_rules! try_chan_entry {
1792         ($self: ident, $res: expr, $entry: expr) => {
1793                 match $res {
1794                         Ok(res) => res,
1795                         Err(e) => {
1796                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut(), $entry.key());
1797                                 if drop {
1798                                         $entry.remove_entry();
1799                                 }
1800                                 return Err(res);
1801                         }
1802                 }
1803         }
1804 }
1805
1806 macro_rules! remove_channel {
1807         ($self: expr, $entry: expr) => {
1808                 {
1809                         let channel = $entry.remove_entry().1;
1810                         update_maps_on_chan_removal!($self, &channel.context);
1811                         channel
1812                 }
1813         }
1814 }
1815
1816 macro_rules! send_channel_ready {
1817         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
1818                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
1819                         node_id: $channel.context.get_counterparty_node_id(),
1820                         msg: $channel_ready_msg,
1821                 });
1822                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
1823                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
1824                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1825                 let outbound_alias_insert = short_to_chan_info.insert($channel.context.outbound_scid_alias(), ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
1826                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
1827                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
1828                 if let Some(real_scid) = $channel.context.get_short_channel_id() {
1829                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
1830                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
1831                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
1832                 }
1833         }}
1834 }
1835
1836 macro_rules! emit_channel_pending_event {
1837         ($locked_events: expr, $channel: expr) => {
1838                 if $channel.context.should_emit_channel_pending_event() {
1839                         $locked_events.push_back((events::Event::ChannelPending {
1840                                 channel_id: $channel.context.channel_id(),
1841                                 former_temporary_channel_id: $channel.context.temporary_channel_id(),
1842                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
1843                                 user_channel_id: $channel.context.get_user_id(),
1844                                 funding_txo: $channel.context.get_funding_txo().unwrap().into_bitcoin_outpoint(),
1845                         }, None));
1846                         $channel.context.set_channel_pending_event_emitted();
1847                 }
1848         }
1849 }
1850
1851 macro_rules! emit_channel_ready_event {
1852         ($locked_events: expr, $channel: expr) => {
1853                 if $channel.context.should_emit_channel_ready_event() {
1854                         debug_assert!($channel.context.channel_pending_event_emitted());
1855                         $locked_events.push_back((events::Event::ChannelReady {
1856                                 channel_id: $channel.context.channel_id(),
1857                                 user_channel_id: $channel.context.get_user_id(),
1858                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
1859                                 channel_type: $channel.context.get_channel_type().clone(),
1860                         }, None));
1861                         $channel.context.set_channel_ready_event_emitted();
1862                 }
1863         }
1864 }
1865
1866 macro_rules! handle_monitor_update_completion {
1867         ($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
1868                 let mut updates = $chan.monitor_updating_restored(&$self.logger,
1869                         &$self.node_signer, $self.genesis_hash, &$self.default_configuration,
1870                         $self.best_block.read().unwrap().height());
1871                 let counterparty_node_id = $chan.context.get_counterparty_node_id();
1872                 let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
1873                         // We only send a channel_update in the case where we are just now sending a
1874                         // channel_ready and the channel is in a usable state. We may re-send a
1875                         // channel_update later through the announcement_signatures process for public
1876                         // channels, but there's no reason not to just inform our counterparty of our fees
1877                         // now.
1878                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
1879                                 Some(events::MessageSendEvent::SendChannelUpdate {
1880                                         node_id: counterparty_node_id,
1881                                         msg,
1882                                 })
1883                         } else { None }
1884                 } else { None };
1885
1886                 let update_actions = $peer_state.monitor_update_blocked_actions
1887                         .remove(&$chan.context.channel_id()).unwrap_or(Vec::new());
1888
1889                 let htlc_forwards = $self.handle_channel_resumption(
1890                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
1891                         updates.commitment_update, updates.order, updates.accepted_htlcs,
1892                         updates.funding_broadcastable, updates.channel_ready,
1893                         updates.announcement_sigs);
1894                 if let Some(upd) = channel_update {
1895                         $peer_state.pending_msg_events.push(upd);
1896                 }
1897
1898                 let channel_id = $chan.context.channel_id();
1899                 core::mem::drop($peer_state_lock);
1900                 core::mem::drop($per_peer_state_lock);
1901
1902                 $self.handle_monitor_update_completion_actions(update_actions);
1903
1904                 if let Some(forwards) = htlc_forwards {
1905                         $self.forward_htlcs(&mut [forwards][..]);
1906                 }
1907                 $self.finalize_claims(updates.finalized_claimed_htlcs);
1908                 for failure in updates.failed_htlcs.drain(..) {
1909                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
1910                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
1911                 }
1912         } }
1913 }
1914
1915 macro_rules! handle_new_monitor_update {
1916         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, _internal, $remove: expr, $completed: expr) => { {
1917                 // update_maps_on_chan_removal needs to be able to take id_to_peer, so make sure we can in
1918                 // any case so that it won't deadlock.
1919                 debug_assert_ne!($self.id_to_peer.held_by_thread(), LockHeldState::HeldByThread);
1920                 #[cfg(debug_assertions)] {
1921                         debug_assert!($self.background_events_processed_since_startup.load(Ordering::Acquire));
1922                 }
1923                 match $update_res {
1924                         ChannelMonitorUpdateStatus::InProgress => {
1925                                 log_debug!($self.logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
1926                                         log_bytes!($chan.context.channel_id()[..]));
1927                                 Ok(false)
1928                         },
1929                         ChannelMonitorUpdateStatus::PermanentFailure => {
1930                                 log_error!($self.logger, "Closing channel {} due to monitor update ChannelMonitorUpdateStatus::PermanentFailure",
1931                                         log_bytes!($chan.context.channel_id()[..]));
1932                                 update_maps_on_chan_removal!($self, &$chan.context);
1933                                 let res = Err(MsgHandleErrInternal::from_finish_shutdown(
1934                                         "ChannelMonitor storage failure".to_owned(), $chan.context.channel_id(),
1935                                         $chan.context.get_user_id(), $chan.context.force_shutdown(false),
1936                                         $self.get_channel_update_for_broadcast(&$chan).ok()));
1937                                 $remove;
1938                                 res
1939                         },
1940                         ChannelMonitorUpdateStatus::Completed => {
1941                                 $completed;
1942                                 Ok(true)
1943                         },
1944                 }
1945         } };
1946         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, MANUALLY_REMOVING_INITIAL_MONITOR, $remove: expr) => {
1947                 handle_new_monitor_update!($self, $update_res, $peer_state_lock, $peer_state,
1948                         $per_peer_state_lock, $chan, _internal, $remove,
1949                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan))
1950         };
1951         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan_entry: expr, INITIAL_MONITOR) => {
1952                 handle_new_monitor_update!($self, $update_res, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan_entry.get_mut(), MANUALLY_REMOVING_INITIAL_MONITOR, $chan_entry.remove_entry())
1953         };
1954         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, MANUALLY_REMOVING, $remove: expr) => { {
1955                 let in_flight_updates = $peer_state.in_flight_monitor_updates.entry($funding_txo)
1956                         .or_insert_with(Vec::new);
1957                 // During startup, we push monitor updates as background events through to here in
1958                 // order to replay updates that were in-flight when we shut down. Thus, we have to
1959                 // filter for uniqueness here.
1960                 let idx = in_flight_updates.iter().position(|upd| upd == &$update)
1961                         .unwrap_or_else(|| {
1962                                 in_flight_updates.push($update);
1963                                 in_flight_updates.len() - 1
1964                         });
1965                 let update_res = $self.chain_monitor.update_channel($funding_txo, &in_flight_updates[idx]);
1966                 handle_new_monitor_update!($self, update_res, $peer_state_lock, $peer_state,
1967                         $per_peer_state_lock, $chan, _internal, $remove,
1968                         {
1969                                 let _ = in_flight_updates.remove(idx);
1970                                 if in_flight_updates.is_empty() && $chan.blocked_monitor_updates_pending() == 0 {
1971                                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
1972                                 }
1973                         })
1974         } };
1975         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan_entry: expr) => {
1976                 handle_new_monitor_update!($self, $funding_txo, $update, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan_entry.get_mut(), MANUALLY_REMOVING, $chan_entry.remove_entry())
1977         }
1978 }
1979
1980 macro_rules! process_events_body {
1981         ($self: expr, $event_to_handle: expr, $handle_event: expr) => {
1982                 let mut processed_all_events = false;
1983                 while !processed_all_events {
1984                         if $self.pending_events_processor.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
1985                                 return;
1986                         }
1987
1988                         let mut result = NotifyOption::SkipPersist;
1989
1990                         {
1991                                 // We'll acquire our total consistency lock so that we can be sure no other
1992                                 // persists happen while processing monitor events.
1993                                 let _read_guard = $self.total_consistency_lock.read().unwrap();
1994
1995                                 // Because `handle_post_event_actions` may send `ChannelMonitorUpdate`s to the user we must
1996                                 // ensure any startup-generated background events are handled first.
1997                                 if $self.process_background_events() == NotifyOption::DoPersist { result = NotifyOption::DoPersist; }
1998
1999                                 // TODO: This behavior should be documented. It's unintuitive that we query
2000                                 // ChannelMonitors when clearing other events.
2001                                 if $self.process_pending_monitor_events() {
2002                                         result = NotifyOption::DoPersist;
2003                                 }
2004                         }
2005
2006                         let pending_events = $self.pending_events.lock().unwrap().clone();
2007                         let num_events = pending_events.len();
2008                         if !pending_events.is_empty() {
2009                                 result = NotifyOption::DoPersist;
2010                         }
2011
2012                         let mut post_event_actions = Vec::new();
2013
2014                         for (event, action_opt) in pending_events {
2015                                 $event_to_handle = event;
2016                                 $handle_event;
2017                                 if let Some(action) = action_opt {
2018                                         post_event_actions.push(action);
2019                                 }
2020                         }
2021
2022                         {
2023                                 let mut pending_events = $self.pending_events.lock().unwrap();
2024                                 pending_events.drain(..num_events);
2025                                 processed_all_events = pending_events.is_empty();
2026                                 $self.pending_events_processor.store(false, Ordering::Release);
2027                         }
2028
2029                         if !post_event_actions.is_empty() {
2030                                 $self.handle_post_event_actions(post_event_actions);
2031                                 // If we had some actions, go around again as we may have more events now
2032                                 processed_all_events = false;
2033                         }
2034
2035                         if result == NotifyOption::DoPersist {
2036                                 $self.persistence_notifier.notify();
2037                         }
2038                 }
2039         }
2040 }
2041
2042 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>
2043 where
2044         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
2045         T::Target: BroadcasterInterface,
2046         ES::Target: EntropySource,
2047         NS::Target: NodeSigner,
2048         SP::Target: SignerProvider,
2049         F::Target: FeeEstimator,
2050         R::Target: Router,
2051         L::Target: Logger,
2052 {
2053         /// Constructs a new `ChannelManager` to hold several channels and route between them.
2054         ///
2055         /// The current time or latest block header time can be provided as the `current_timestamp`.
2056         ///
2057         /// This is the main "logic hub" for all channel-related actions, and implements
2058         /// [`ChannelMessageHandler`].
2059         ///
2060         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2061         ///
2062         /// Users need to notify the new `ChannelManager` when a new block is connected or
2063         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2064         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2065         /// more details.
2066         ///
2067         /// [`block_connected`]: chain::Listen::block_connected
2068         /// [`block_disconnected`]: chain::Listen::block_disconnected
2069         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2070         pub fn new(
2071                 fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES,
2072                 node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters,
2073                 current_timestamp: u32,
2074         ) -> Self {
2075                 let mut secp_ctx = Secp256k1::new();
2076                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
2077                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
2078                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
2079                 ChannelManager {
2080                         default_configuration: config.clone(),
2081                         genesis_hash: genesis_block(params.network).header.block_hash(),
2082                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
2083                         chain_monitor,
2084                         tx_broadcaster,
2085                         router,
2086
2087                         best_block: RwLock::new(params.best_block),
2088
2089                         outbound_scid_aliases: Mutex::new(HashSet::new()),
2090                         pending_inbound_payments: Mutex::new(HashMap::new()),
2091                         pending_outbound_payments: OutboundPayments::new(),
2092                         forward_htlcs: Mutex::new(HashMap::new()),
2093                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments: HashMap::new(), pending_claiming_payments: HashMap::new() }),
2094                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
2095                         id_to_peer: Mutex::new(HashMap::new()),
2096                         short_to_chan_info: FairRwLock::new(HashMap::new()),
2097
2098                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
2099                         secp_ctx,
2100
2101                         inbound_payment_key: expanded_inbound_key,
2102                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
2103
2104                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
2105
2106                         highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
2107
2108                         per_peer_state: FairRwLock::new(HashMap::new()),
2109
2110                         pending_events: Mutex::new(VecDeque::new()),
2111                         pending_events_processor: AtomicBool::new(false),
2112                         pending_background_events: Mutex::new(Vec::new()),
2113                         total_consistency_lock: RwLock::new(()),
2114                         #[cfg(debug_assertions)]
2115                         background_events_processed_since_startup: AtomicBool::new(false),
2116                         persistence_notifier: Notifier::new(),
2117
2118                         entropy_source,
2119                         node_signer,
2120                         signer_provider,
2121
2122                         logger,
2123                 }
2124         }
2125
2126         /// Gets the current configuration applied to all new channels.
2127         pub fn get_current_default_configuration(&self) -> &UserConfig {
2128                 &self.default_configuration
2129         }
2130
2131         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
2132                 let height = self.best_block.read().unwrap().height();
2133                 let mut outbound_scid_alias = 0;
2134                 let mut i = 0;
2135                 loop {
2136                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
2137                                 outbound_scid_alias += 1;
2138                         } else {
2139                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2140                         }
2141                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
2142                                 break;
2143                         }
2144                         i += 1;
2145                         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"); }
2146                 }
2147                 outbound_scid_alias
2148         }
2149
2150         /// Creates a new outbound channel to the given remote node and with the given value.
2151         ///
2152         /// `user_channel_id` will be provided back as in
2153         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2154         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2155         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2156         /// is simply copied to events and otherwise ignored.
2157         ///
2158         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2159         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2160         ///
2161         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2162         /// generate a shutdown scriptpubkey or destination script set by
2163         /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2164         ///
2165         /// Note that we do not check if you are currently connected to the given peer. If no
2166         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2167         /// the channel eventually being silently forgotten (dropped on reload).
2168         ///
2169         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2170         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2171         /// [`ChannelDetails::channel_id`] until after
2172         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2173         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2174         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2175         ///
2176         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2177         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2178         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2179         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> {
2180                 if channel_value_satoshis < 1000 {
2181                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
2182                 }
2183
2184                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2185                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
2186                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
2187
2188                 let per_peer_state = self.per_peer_state.read().unwrap();
2189
2190                 let peer_state_mutex = per_peer_state.get(&their_network_key)
2191                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
2192
2193                 let mut peer_state = peer_state_mutex.lock().unwrap();
2194                 let channel = {
2195                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
2196                         let their_features = &peer_state.latest_features;
2197                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
2198                         match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
2199                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
2200                                 self.best_block.read().unwrap().height(), outbound_scid_alias)
2201                         {
2202                                 Ok(res) => res,
2203                                 Err(e) => {
2204                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
2205                                         return Err(e);
2206                                 },
2207                         }
2208                 };
2209                 let res = channel.get_open_channel(self.genesis_hash.clone());
2210
2211                 let temporary_channel_id = channel.context.channel_id();
2212                 match peer_state.outbound_v1_channel_by_id.entry(temporary_channel_id) {
2213                         hash_map::Entry::Occupied(_) => {
2214                                 if cfg!(fuzzing) {
2215                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
2216                                 } else {
2217                                         panic!("RNG is bad???");
2218                                 }
2219                         },
2220                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
2221                 }
2222
2223                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
2224                         node_id: their_network_key,
2225                         msg: res,
2226                 });
2227                 Ok(temporary_channel_id)
2228         }
2229
2230         fn list_funded_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<<SP::Target as SignerProvider>::Signer>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
2231                 // Allocate our best estimate of the number of channels we have in the `res`
2232                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2233                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2234                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2235                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2236                 // the same channel.
2237                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2238                 {
2239                         let best_block_height = self.best_block.read().unwrap().height();
2240                         let per_peer_state = self.per_peer_state.read().unwrap();
2241                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2242                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2243                                 let peer_state = &mut *peer_state_lock;
2244                                 for (_channel_id, channel) in peer_state.channel_by_id.iter().filter(f) {
2245                                         let details = ChannelDetails::from_channel_context(&channel.context, best_block_height,
2246                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2247                                         res.push(details);
2248                                 }
2249                         }
2250                 }
2251                 res
2252         }
2253
2254         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2255         /// more information.
2256         pub fn list_channels(&self) -> Vec<ChannelDetails> {
2257                 // Allocate our best estimate of the number of channels we have in the `res`
2258                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2259                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2260                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2261                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2262                 // the same channel.
2263                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2264                 {
2265                         let best_block_height = self.best_block.read().unwrap().height();
2266                         let per_peer_state = self.per_peer_state.read().unwrap();
2267                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2268                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2269                                 let peer_state = &mut *peer_state_lock;
2270                                 for (_channel_id, channel) in peer_state.channel_by_id.iter() {
2271                                         let details = ChannelDetails::from_channel_context(&channel.context, best_block_height,
2272                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2273                                         res.push(details);
2274                                 }
2275                                 for (_channel_id, channel) in peer_state.inbound_v1_channel_by_id.iter() {
2276                                         let details = ChannelDetails::from_channel_context(&channel.context, best_block_height,
2277                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2278                                         res.push(details);
2279                                 }
2280                                 for (_channel_id, channel) in peer_state.outbound_v1_channel_by_id.iter() {
2281                                         let details = ChannelDetails::from_channel_context(&channel.context, best_block_height,
2282                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2283                                         res.push(details);
2284                                 }
2285                         }
2286                 }
2287                 res
2288         }
2289
2290         /// Gets the list of usable channels, in random order. Useful as an argument to
2291         /// [`Router::find_route`] to ensure non-announced channels are used.
2292         ///
2293         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2294         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2295         /// are.
2296         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
2297                 // Note we use is_live here instead of usable which leads to somewhat confused
2298                 // internal/external nomenclature, but that's ok cause that's probably what the user
2299                 // really wanted anyway.
2300                 self.list_funded_channels_with_filter(|&(_, ref channel)| channel.context.is_live())
2301         }
2302
2303         /// Gets the list of channels we have with a given counterparty, in random order.
2304         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
2305                 let best_block_height = self.best_block.read().unwrap().height();
2306                 let per_peer_state = self.per_peer_state.read().unwrap();
2307
2308                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
2309                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2310                         let peer_state = &mut *peer_state_lock;
2311                         let features = &peer_state.latest_features;
2312                         return peer_state.channel_by_id
2313                                 .iter()
2314                                 .map(|(_, channel)|
2315                                         ChannelDetails::from_channel_context(&channel.context, best_block_height,
2316                                         features.clone(), &self.fee_estimator))
2317                                 .collect();
2318                 }
2319                 vec![]
2320         }
2321
2322         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2323         /// successful path, or have unresolved HTLCs.
2324         ///
2325         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2326         /// result of a crash. If such a payment exists, is not listed here, and an
2327         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2328         ///
2329         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2330         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
2331                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
2332                         .filter_map(|(_, pending_outbound_payment)| match pending_outbound_payment {
2333                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
2334                                         Some(RecentPaymentDetails::Pending {
2335                                                 payment_hash: *payment_hash,
2336                                                 total_msat: *total_msat,
2337                                         })
2338                                 },
2339                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
2340                                         Some(RecentPaymentDetails::Abandoned { payment_hash: *payment_hash })
2341                                 },
2342                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
2343                                         Some(RecentPaymentDetails::Fulfilled { payment_hash: *payment_hash })
2344                                 },
2345                                 PendingOutboundPayment::Legacy { .. } => None
2346                         })
2347                         .collect()
2348         }
2349
2350         /// Helper function that issues the channel close events
2351         fn issue_channel_close_events(&self, context: &ChannelContext<<SP::Target as SignerProvider>::Signer>, closure_reason: ClosureReason) {
2352                 let mut pending_events_lock = self.pending_events.lock().unwrap();
2353                 match context.unbroadcasted_funding() {
2354                         Some(transaction) => {
2355                                 pending_events_lock.push_back((events::Event::DiscardFunding {
2356                                         channel_id: context.channel_id(), transaction
2357                                 }, None));
2358                         },
2359                         None => {},
2360                 }
2361                 pending_events_lock.push_back((events::Event::ChannelClosed {
2362                         channel_id: context.channel_id(),
2363                         user_channel_id: context.get_user_id(),
2364                         reason: closure_reason
2365                 }, None));
2366         }
2367
2368         fn close_channel_internal(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: Option<u32>, override_shutdown_script: Option<ShutdownScript>) -> Result<(), APIError> {
2369                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2370
2371                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)>;
2372                 let result: Result<(), _> = loop {
2373                         let per_peer_state = self.per_peer_state.read().unwrap();
2374
2375                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2376                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2377
2378                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2379                         let peer_state = &mut *peer_state_lock;
2380                         match peer_state.channel_by_id.entry(channel_id.clone()) {
2381                                 hash_map::Entry::Occupied(mut chan_entry) => {
2382                                         let funding_txo_opt = chan_entry.get().context.get_funding_txo();
2383                                         let their_features = &peer_state.latest_features;
2384                                         let (shutdown_msg, mut monitor_update_opt, htlcs) = chan_entry.get_mut()
2385                                                 .get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2386                                         failed_htlcs = htlcs;
2387
2388                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
2389                                         // here as we don't need the monitor update to complete until we send a
2390                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
2391                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2392                                                 node_id: *counterparty_node_id,
2393                                                 msg: shutdown_msg,
2394                                         });
2395
2396                                         // Update the monitor with the shutdown script if necessary.
2397                                         if let Some(monitor_update) = monitor_update_opt.take() {
2398                                                 break handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2399                                                         peer_state_lock, peer_state, per_peer_state, chan_entry).map(|_| ());
2400                                         }
2401
2402                                         if chan_entry.get().is_shutdown() {
2403                                                 let channel = remove_channel!(self, chan_entry);
2404                                                 if let Ok(channel_update) = self.get_channel_update_for_broadcast(&channel) {
2405                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2406                                                                 msg: channel_update
2407                                                         });
2408                                                 }
2409                                                 self.issue_channel_close_events(&channel.context, ClosureReason::HolderForceClosed);
2410                                         }
2411                                         break Ok(());
2412                                 },
2413                                 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) })
2414                         }
2415                 };
2416
2417                 for htlc_source in failed_htlcs.drain(..) {
2418                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2419                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
2420                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
2421                 }
2422
2423                 let _ = handle_error!(self, result, *counterparty_node_id);
2424                 Ok(())
2425         }
2426
2427         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2428         /// will be accepted on the given channel, and after additional timeout/the closing of all
2429         /// pending HTLCs, the channel will be closed on chain.
2430         ///
2431         ///  * If we are the channel initiator, we will pay between our [`Background`] and
2432         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2433         ///    estimate.
2434         ///  * If our counterparty is the channel initiator, we will require a channel closing
2435         ///    transaction feerate of at least our [`Background`] feerate or the feerate which
2436         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2437         ///    counterparty to pay as much fee as they'd like, however.
2438         ///
2439         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2440         ///
2441         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2442         /// generate a shutdown scriptpubkey or destination script set by
2443         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2444         /// channel.
2445         ///
2446         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2447         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2448         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2449         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2450         pub fn close_channel(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey) -> Result<(), APIError> {
2451                 self.close_channel_internal(channel_id, counterparty_node_id, None, None)
2452         }
2453
2454         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2455         /// will be accepted on the given channel, and after additional timeout/the closing of all
2456         /// pending HTLCs, the channel will be closed on chain.
2457         ///
2458         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2459         /// the channel being closed or not:
2460         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2461         ///    transaction. The upper-bound is set by
2462         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2463         ///    estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2464         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2465         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2466         ///    will appear on a force-closure transaction, whichever is lower).
2467         ///
2468         /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2469         /// Will fail if a shutdown script has already been set for this channel by
2470         /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2471         /// also be compatible with our and the counterparty's features.
2472         ///
2473         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2474         ///
2475         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2476         /// generate a shutdown scriptpubkey or destination script set by
2477         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2478         /// channel.
2479         ///
2480         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2481         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2482         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2483         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2484         pub fn close_channel_with_feerate_and_script(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: Option<u32>, shutdown_script: Option<ShutdownScript>) -> Result<(), APIError> {
2485                 self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
2486         }
2487
2488         #[inline]
2489         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
2490                 let (monitor_update_option, mut failed_htlcs) = shutdown_res;
2491                 log_debug!(self.logger, "Finishing force-closure of channel with {} HTLCs to fail", failed_htlcs.len());
2492                 for htlc_source in failed_htlcs.drain(..) {
2493                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
2494                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2495                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2496                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
2497                 }
2498                 if let Some((_, funding_txo, monitor_update)) = monitor_update_option {
2499                         // There isn't anything we can do if we get an update failure - we're already
2500                         // force-closing. The monitor update on the required in-memory copy should broadcast
2501                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
2502                         // ignore the result here.
2503                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
2504                 }
2505         }
2506
2507         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2508         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2509         fn force_close_channel_with_peer(&self, channel_id: &[u8; 32], peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2510         -> Result<PublicKey, APIError> {
2511                 let per_peer_state = self.per_peer_state.read().unwrap();
2512                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2513                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2514                 let (update_opt, counterparty_node_id) = {
2515                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2516                         let peer_state = &mut *peer_state_lock;
2517                         let closure_reason = if let Some(peer_msg) = peer_msg {
2518                                 ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg.to_string()) }
2519                         } else {
2520                                 ClosureReason::HolderForceClosed
2521                         };
2522                         if let hash_map::Entry::Occupied(chan) = peer_state.channel_by_id.entry(channel_id.clone()) {
2523                                 log_error!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
2524                                 self.issue_channel_close_events(&chan.get().context, closure_reason);
2525                                 let mut chan = remove_channel!(self, chan);
2526                                 self.finish_force_close_channel(chan.context.force_shutdown(broadcast));
2527                                 (self.get_channel_update_for_broadcast(&chan).ok(), chan.context.get_counterparty_node_id())
2528                         } else if let hash_map::Entry::Occupied(chan) = peer_state.outbound_v1_channel_by_id.entry(channel_id.clone()) {
2529                                 log_error!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
2530                                 self.issue_channel_close_events(&chan.get().context, closure_reason);
2531                                 let mut chan = remove_channel!(self, chan);
2532                                 self.finish_force_close_channel(chan.context.force_shutdown(false));
2533                                 // Prefunded channel has no update
2534                                 (None, chan.context.get_counterparty_node_id())
2535                         } else if let hash_map::Entry::Occupied(chan) = peer_state.inbound_v1_channel_by_id.entry(channel_id.clone()) {
2536                                 log_error!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
2537                                 self.issue_channel_close_events(&chan.get().context, closure_reason);
2538                                 let mut chan = remove_channel!(self, chan);
2539                                 self.finish_force_close_channel(chan.context.force_shutdown(false));
2540                                 // Prefunded channel has no update
2541                                 (None, chan.context.get_counterparty_node_id())
2542                         } else {
2543                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(*channel_id), peer_node_id) });
2544                         }
2545                 };
2546                 if let Some(update) = update_opt {
2547                         let mut peer_state = peer_state_mutex.lock().unwrap();
2548                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2549                                 msg: update
2550                         });
2551                 }
2552
2553                 Ok(counterparty_node_id)
2554         }
2555
2556         fn force_close_sending_error(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
2557                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2558                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
2559                         Ok(counterparty_node_id) => {
2560                                 let per_peer_state = self.per_peer_state.read().unwrap();
2561                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2562                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2563                                         peer_state.pending_msg_events.push(
2564                                                 events::MessageSendEvent::HandleError {
2565                                                         node_id: counterparty_node_id,
2566                                                         action: msgs::ErrorAction::SendErrorMessage {
2567                                                                 msg: msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() }
2568                                                         },
2569                                                 }
2570                                         );
2571                                 }
2572                                 Ok(())
2573                         },
2574                         Err(e) => Err(e)
2575                 }
2576         }
2577
2578         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2579         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2580         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
2581         /// channel.
2582         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey)
2583         -> Result<(), APIError> {
2584                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
2585         }
2586
2587         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
2588         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
2589         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
2590         ///
2591         /// You can always get the latest local transaction(s) to broadcast from
2592         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
2593         pub fn force_close_without_broadcasting_txn(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey)
2594         -> Result<(), APIError> {
2595                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
2596         }
2597
2598         /// Force close all channels, immediately broadcasting the latest local commitment transaction
2599         /// for each to the chain and rejecting new HTLCs on each.
2600         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
2601                 for chan in self.list_channels() {
2602                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
2603                 }
2604         }
2605
2606         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
2607         /// local transaction(s).
2608         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
2609                 for chan in self.list_channels() {
2610                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
2611                 }
2612         }
2613
2614         fn construct_recv_pending_htlc_info(
2615                 &self, hop_data: msgs::OnionHopData, shared_secret: [u8; 32], payment_hash: PaymentHash,
2616                 amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>, allow_underpay: bool,
2617                 counterparty_skimmed_fee_msat: Option<u64>,
2618         ) -> Result<PendingHTLCInfo, ReceiveError> {
2619                 // final_incorrect_cltv_expiry
2620                 if hop_data.outgoing_cltv_value > cltv_expiry {
2621                         return Err(ReceiveError {
2622                                 msg: "Upstream node set CLTV to less than the CLTV set by the sender",
2623                                 err_code: 18,
2624                                 err_data: cltv_expiry.to_be_bytes().to_vec()
2625                         })
2626                 }
2627                 // final_expiry_too_soon
2628                 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure
2629                 // we have at least HTLC_FAIL_BACK_BUFFER blocks to go.
2630                 //
2631                 // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
2632                 // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
2633                 // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
2634                 let current_height: u32 = self.best_block.read().unwrap().height();
2635                 if (hop_data.outgoing_cltv_value as u64) <= current_height as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1 {
2636                         let mut err_data = Vec::with_capacity(12);
2637                         err_data.extend_from_slice(&amt_msat.to_be_bytes());
2638                         err_data.extend_from_slice(&current_height.to_be_bytes());
2639                         return Err(ReceiveError {
2640                                 err_code: 0x4000 | 15, err_data,
2641                                 msg: "The final CLTV expiry is too soon to handle",
2642                         });
2643                 }
2644                 if (!allow_underpay && hop_data.amt_to_forward > amt_msat) ||
2645                         (allow_underpay && hop_data.amt_to_forward >
2646                          amt_msat.saturating_add(counterparty_skimmed_fee_msat.unwrap_or(0)))
2647                 {
2648                         return Err(ReceiveError {
2649                                 err_code: 19,
2650                                 err_data: amt_msat.to_be_bytes().to_vec(),
2651                                 msg: "Upstream node sent less than we were supposed to receive in payment",
2652                         });
2653                 }
2654
2655                 let routing = match hop_data.format {
2656                         msgs::OnionHopDataFormat::NonFinalNode { .. } => {
2657                                 return Err(ReceiveError {
2658                                         err_code: 0x4000|22,
2659                                         err_data: Vec::new(),
2660                                         msg: "Got non final data with an HMAC of 0",
2661                                 });
2662                         },
2663                         msgs::OnionHopDataFormat::FinalNode { payment_data, keysend_preimage, payment_metadata } => {
2664                                 if let Some(payment_preimage) = keysend_preimage {
2665                                         // We need to check that the sender knows the keysend preimage before processing this
2666                                         // payment further. Otherwise, an intermediary routing hop forwarding non-keysend-HTLC X
2667                                         // could discover the final destination of X, by probing the adjacent nodes on the route
2668                                         // with a keysend payment of identical payment hash to X and observing the processing
2669                                         // time discrepancies due to a hash collision with X.
2670                                         let hashed_preimage = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
2671                                         if hashed_preimage != payment_hash {
2672                                                 return Err(ReceiveError {
2673                                                         err_code: 0x4000|22,
2674                                                         err_data: Vec::new(),
2675                                                         msg: "Payment preimage didn't match payment hash",
2676                                                 });
2677                                         }
2678                                         if !self.default_configuration.accept_mpp_keysend && payment_data.is_some() {
2679                                                 return Err(ReceiveError {
2680                                                         err_code: 0x4000|22,
2681                                                         err_data: Vec::new(),
2682                                                         msg: "We don't support MPP keysend payments",
2683                                                 });
2684                                         }
2685                                         PendingHTLCRouting::ReceiveKeysend {
2686                                                 payment_data,
2687                                                 payment_preimage,
2688                                                 payment_metadata,
2689                                                 incoming_cltv_expiry: hop_data.outgoing_cltv_value,
2690                                         }
2691                                 } else if let Some(data) = payment_data {
2692                                         PendingHTLCRouting::Receive {
2693                                                 payment_data: data,
2694                                                 payment_metadata,
2695                                                 incoming_cltv_expiry: hop_data.outgoing_cltv_value,
2696                                                 phantom_shared_secret,
2697                                         }
2698                                 } else {
2699                                         return Err(ReceiveError {
2700                                                 err_code: 0x4000|0x2000|3,
2701                                                 err_data: Vec::new(),
2702                                                 msg: "We require payment_secrets",
2703                                         });
2704                                 }
2705                         },
2706                 };
2707                 Ok(PendingHTLCInfo {
2708                         routing,
2709                         payment_hash,
2710                         incoming_shared_secret: shared_secret,
2711                         incoming_amt_msat: Some(amt_msat),
2712                         outgoing_amt_msat: hop_data.amt_to_forward,
2713                         outgoing_cltv_value: hop_data.outgoing_cltv_value,
2714                         skimmed_fee_msat: counterparty_skimmed_fee_msat,
2715                 })
2716         }
2717
2718         fn decode_update_add_htlc_onion(
2719                 &self, msg: &msgs::UpdateAddHTLC
2720         ) -> Result<(onion_utils::Hop, [u8; 32], Option<Result<PublicKey, secp256k1::Error>>), HTLCFailureMsg> {
2721                 macro_rules! return_malformed_err {
2722                         ($msg: expr, $err_code: expr) => {
2723                                 {
2724                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2725                                         return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
2726                                                 channel_id: msg.channel_id,
2727                                                 htlc_id: msg.htlc_id,
2728                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
2729                                                 failure_code: $err_code,
2730                                         }));
2731                                 }
2732                         }
2733                 }
2734
2735                 if let Err(_) = msg.onion_routing_packet.public_key {
2736                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
2737                 }
2738
2739                 let shared_secret = self.node_signer.ecdh(
2740                         Recipient::Node, &msg.onion_routing_packet.public_key.unwrap(), None
2741                 ).unwrap().secret_bytes();
2742
2743                 if msg.onion_routing_packet.version != 0 {
2744                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
2745                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
2746                         //the hash doesn't really serve any purpose - in the case of hashing all data, the
2747                         //receiving node would have to brute force to figure out which version was put in the
2748                         //packet by the node that send us the message, in the case of hashing the hop_data, the
2749                         //node knows the HMAC matched, so they already know what is there...
2750                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
2751                 }
2752                 macro_rules! return_err {
2753                         ($msg: expr, $err_code: expr, $data: expr) => {
2754                                 {
2755                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2756                                         return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2757                                                 channel_id: msg.channel_id,
2758                                                 htlc_id: msg.htlc_id,
2759                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
2760                                                         .get_encrypted_failure_packet(&shared_secret, &None),
2761                                         }));
2762                                 }
2763                         }
2764                 }
2765
2766                 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) {
2767                         Ok(res) => res,
2768                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
2769                                 return_malformed_err!(err_msg, err_code);
2770                         },
2771                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
2772                                 return_err!(err_msg, err_code, &[0; 0]);
2773                         },
2774                 };
2775                 let (outgoing_scid, outgoing_amt_msat, outgoing_cltv_value, next_packet_pk_opt) = match next_hop {
2776                         onion_utils::Hop::Forward {
2777                                 next_hop_data: msgs::OnionHopData {
2778                                         format: msgs::OnionHopDataFormat::NonFinalNode { short_channel_id }, amt_to_forward,
2779                                         outgoing_cltv_value,
2780                                 }, ..
2781                         } => {
2782                                 let next_pk = onion_utils::next_hop_packet_pubkey(&self.secp_ctx,
2783                                         msg.onion_routing_packet.public_key.unwrap(), &shared_secret);
2784                                 (short_channel_id, amt_to_forward, outgoing_cltv_value, Some(next_pk))
2785                         },
2786                         // We'll do receive checks in [`Self::construct_pending_htlc_info`] so we have access to the
2787                         // inbound channel's state.
2788                         onion_utils::Hop::Receive { .. } => return Ok((next_hop, shared_secret, None)),
2789                         onion_utils::Hop::Forward {
2790                                 next_hop_data: msgs::OnionHopData { format: msgs::OnionHopDataFormat::FinalNode { .. }, .. }, ..
2791                         } => {
2792                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0; 0]);
2793                         }
2794                 };
2795
2796                 // Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
2797                 // can't hold the outbound peer state lock at the same time as the inbound peer state lock.
2798                 if let Some((err, mut code, chan_update)) = loop {
2799                         let id_option = self.short_to_chan_info.read().unwrap().get(&outgoing_scid).cloned();
2800                         let forwarding_chan_info_opt = match id_option {
2801                                 None => { // unknown_next_peer
2802                                         // Note that this is likely a timing oracle for detecting whether an scid is a
2803                                         // phantom or an intercept.
2804                                         if (self.default_configuration.accept_intercept_htlcs &&
2805                                                 fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.genesis_hash)) ||
2806                                                 fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.genesis_hash)
2807                                         {
2808                                                 None
2809                                         } else {
2810                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2811                                         }
2812                                 },
2813                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
2814                         };
2815                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
2816                                 let per_peer_state = self.per_peer_state.read().unwrap();
2817                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
2818                                 if peer_state_mutex_opt.is_none() {
2819                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2820                                 }
2821                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
2822                                 let peer_state = &mut *peer_state_lock;
2823                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id) {
2824                                         None => {
2825                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
2826                                                 // have no consistency guarantees.
2827                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2828                                         },
2829                                         Some(chan) => chan
2830                                 };
2831                                 if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
2832                                         // Note that the behavior here should be identical to the above block - we
2833                                         // should NOT reveal the existence or non-existence of a private channel if
2834                                         // we don't allow forwards outbound over them.
2835                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
2836                                 }
2837                                 if chan.context.get_channel_type().supports_scid_privacy() && outgoing_scid != chan.context.outbound_scid_alias() {
2838                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
2839                                         // "refuse to forward unless the SCID alias was used", so we pretend
2840                                         // we don't have the channel here.
2841                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
2842                                 }
2843                                 let chan_update_opt = self.get_channel_update_for_onion(outgoing_scid, chan).ok();
2844
2845                                 // Note that we could technically not return an error yet here and just hope
2846                                 // that the connection is reestablished or monitor updated by the time we get
2847                                 // around to doing the actual forward, but better to fail early if we can and
2848                                 // hopefully an attacker trying to path-trace payments cannot make this occur
2849                                 // on a small/per-node/per-channel scale.
2850                                 if !chan.context.is_live() { // channel_disabled
2851                                         // If the channel_update we're going to return is disabled (i.e. the
2852                                         // peer has been disabled for some time), return `channel_disabled`,
2853                                         // otherwise return `temporary_channel_failure`.
2854                                         if chan_update_opt.as_ref().map(|u| u.contents.flags & 2 == 2).unwrap_or(false) {
2855                                                 break Some(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
2856                                         } else {
2857                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
2858                                         }
2859                                 }
2860                                 if outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
2861                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
2862                                 }
2863                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, outgoing_amt_msat, outgoing_cltv_value) {
2864                                         break Some((err, code, chan_update_opt));
2865                                 }
2866                                 chan_update_opt
2867                         } else {
2868                                 if (msg.cltv_expiry as u64) < (outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
2869                                         // We really should set `incorrect_cltv_expiry` here but as we're not
2870                                         // forwarding over a real channel we can't generate a channel_update
2871                                         // for it. Instead we just return a generic temporary_node_failure.
2872                                         break Some((
2873                                                         "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
2874                                                         0x2000 | 2, None,
2875                                         ));
2876                                 }
2877                                 None
2878                         };
2879
2880                         let cur_height = self.best_block.read().unwrap().height() + 1;
2881                         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now,
2882                         // but we want to be robust wrt to counterparty packet sanitization (see
2883                         // HTLC_FAIL_BACK_BUFFER rationale).
2884                         if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
2885                                 break Some(("CLTV expiry is too close", 0x1000 | 14, chan_update_opt));
2886                         }
2887                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
2888                                 break Some(("CLTV expiry is too far in the future", 21, None));
2889                         }
2890                         // If the HTLC expires ~now, don't bother trying to forward it to our
2891                         // counterparty. They should fail it anyway, but we don't want to bother with
2892                         // the round-trips or risk them deciding they definitely want the HTLC and
2893                         // force-closing to ensure they get it if we're offline.
2894                         // We previously had a much more aggressive check here which tried to ensure
2895                         // our counterparty receives an HTLC which has *our* risk threshold met on it,
2896                         // but there is no need to do that, and since we're a bit conservative with our
2897                         // risk threshold it just results in failing to forward payments.
2898                         if (outgoing_cltv_value) as u64 <= (cur_height + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
2899                                 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, chan_update_opt));
2900                         }
2901
2902                         break None;
2903                 }
2904                 {
2905                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
2906                         if let Some(chan_update) = chan_update {
2907                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
2908                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
2909                                 }
2910                                 else if code == 0x1000 | 13 {
2911                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
2912                                 }
2913                                 else if code == 0x1000 | 20 {
2914                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
2915                                         0u16.write(&mut res).expect("Writes cannot fail");
2916                                 }
2917                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
2918                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
2919                                 chan_update.write(&mut res).expect("Writes cannot fail");
2920                         } else if code & 0x1000 == 0x1000 {
2921                                 // If we're trying to return an error that requires a `channel_update` but
2922                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
2923                                 // generate an update), just use the generic "temporary_node_failure"
2924                                 // instead.
2925                                 code = 0x2000 | 2;
2926                         }
2927                         return_err!(err, code, &res.0[..]);
2928                 }
2929                 Ok((next_hop, shared_secret, next_packet_pk_opt))
2930         }
2931
2932         fn construct_pending_htlc_status<'a>(
2933                 &self, msg: &msgs::UpdateAddHTLC, shared_secret: [u8; 32], decoded_hop: onion_utils::Hop,
2934                 allow_underpay: bool, next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
2935         ) -> PendingHTLCStatus {
2936                 macro_rules! return_err {
2937                         ($msg: expr, $err_code: expr, $data: expr) => {
2938                                 {
2939                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2940                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2941                                                 channel_id: msg.channel_id,
2942                                                 htlc_id: msg.htlc_id,
2943                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
2944                                                         .get_encrypted_failure_packet(&shared_secret, &None),
2945                                         }));
2946                                 }
2947                         }
2948                 }
2949                 match decoded_hop {
2950                         onion_utils::Hop::Receive(next_hop_data) => {
2951                                 // OUR PAYMENT!
2952                                 match self.construct_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash,
2953                                         msg.amount_msat, msg.cltv_expiry, None, allow_underpay, msg.skimmed_fee_msat)
2954                                 {
2955                                         Ok(info) => {
2956                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
2957                                                 // message, however that would leak that we are the recipient of this payment, so
2958                                                 // instead we stay symmetric with the forwarding case, only responding (after a
2959                                                 // delay) once they've send us a commitment_signed!
2960                                                 PendingHTLCStatus::Forward(info)
2961                                         },
2962                                         Err(ReceiveError { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
2963                                 }
2964                         },
2965                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
2966                                 debug_assert!(next_packet_pubkey_opt.is_some());
2967                                 let outgoing_packet = msgs::OnionPacket {
2968                                         version: 0,
2969                                         public_key: next_packet_pubkey_opt.unwrap_or(Err(secp256k1::Error::InvalidPublicKey)),
2970                                         hop_data: new_packet_bytes,
2971                                         hmac: next_hop_hmac.clone(),
2972                                 };
2973
2974                                 let short_channel_id = match next_hop_data.format {
2975                                         msgs::OnionHopDataFormat::NonFinalNode { short_channel_id } => short_channel_id,
2976                                         msgs::OnionHopDataFormat::FinalNode { .. } => {
2977                                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0;0]);
2978                                         },
2979                                 };
2980
2981                                 PendingHTLCStatus::Forward(PendingHTLCInfo {
2982                                         routing: PendingHTLCRouting::Forward {
2983                                                 onion_packet: outgoing_packet,
2984                                                 short_channel_id,
2985                                         },
2986                                         payment_hash: msg.payment_hash.clone(),
2987                                         incoming_shared_secret: shared_secret,
2988                                         incoming_amt_msat: Some(msg.amount_msat),
2989                                         outgoing_amt_msat: next_hop_data.amt_to_forward,
2990                                         outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
2991                                         skimmed_fee_msat: None,
2992                                 })
2993                         }
2994                 }
2995         }
2996
2997         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
2998         /// public, and thus should be called whenever the result is going to be passed out in a
2999         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
3000         ///
3001         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
3002         /// corresponding to the channel's counterparty locked, as the channel been removed from the
3003         /// storage and the `peer_state` lock has been dropped.
3004         ///
3005         /// [`channel_update`]: msgs::ChannelUpdate
3006         /// [`internal_closing_signed`]: Self::internal_closing_signed
3007         fn get_channel_update_for_broadcast(&self, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
3008                 if !chan.context.should_announce() {
3009                         return Err(LightningError {
3010                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
3011                                 action: msgs::ErrorAction::IgnoreError
3012                         });
3013                 }
3014                 if chan.context.get_short_channel_id().is_none() {
3015                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
3016                 }
3017                 log_trace!(self.logger, "Attempting to generate broadcast channel update for channel {}", log_bytes!(chan.context.channel_id()));
3018                 self.get_channel_update_for_unicast(chan)
3019         }
3020
3021         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
3022         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
3023         /// and thus MUST NOT be called unless the recipient of the resulting message has already
3024         /// provided evidence that they know about the existence of the channel.
3025         ///
3026         /// Note that through [`internal_closing_signed`], this function is called without the
3027         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
3028         /// removed from the storage and the `peer_state` lock has been dropped.
3029         ///
3030         /// [`channel_update`]: msgs::ChannelUpdate
3031         /// [`internal_closing_signed`]: Self::internal_closing_signed
3032         fn get_channel_update_for_unicast(&self, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
3033                 log_trace!(self.logger, "Attempting to generate channel update for channel {}", log_bytes!(chan.context.channel_id()));
3034                 let short_channel_id = match chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias()) {
3035                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
3036                         Some(id) => id,
3037                 };
3038
3039                 self.get_channel_update_for_onion(short_channel_id, chan)
3040         }
3041
3042         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
3043                 log_trace!(self.logger, "Generating channel update for channel {}", log_bytes!(chan.context.channel_id()));
3044                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
3045
3046                 let enabled = chan.context.is_usable() && match chan.channel_update_status() {
3047                         ChannelUpdateStatus::Enabled => true,
3048                         ChannelUpdateStatus::DisabledStaged(_) => true,
3049                         ChannelUpdateStatus::Disabled => false,
3050                         ChannelUpdateStatus::EnabledStaged(_) => false,
3051                 };
3052
3053                 let unsigned = msgs::UnsignedChannelUpdate {
3054                         chain_hash: self.genesis_hash,
3055                         short_channel_id,
3056                         timestamp: chan.context.get_update_time_counter(),
3057                         flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
3058                         cltv_expiry_delta: chan.context.get_cltv_expiry_delta(),
3059                         htlc_minimum_msat: chan.context.get_counterparty_htlc_minimum_msat(),
3060                         htlc_maximum_msat: chan.context.get_announced_htlc_max_msat(),
3061                         fee_base_msat: chan.context.get_outbound_forwarding_fee_base_msat(),
3062                         fee_proportional_millionths: chan.context.get_fee_proportional_millionths(),
3063                         excess_data: Vec::new(),
3064                 };
3065                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
3066                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
3067                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
3068                 // channel.
3069                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
3070
3071                 Ok(msgs::ChannelUpdate {
3072                         signature: sig,
3073                         contents: unsigned
3074                 })
3075         }
3076
3077         #[cfg(test)]
3078         pub(crate) fn test_send_payment_along_path(&self, path: &Path, payment_hash: &PaymentHash, recipient_onion: RecipientOnionFields, total_value: u64, cur_height: u32, payment_id: PaymentId, keysend_preimage: &Option<PaymentPreimage>, session_priv_bytes: [u8; 32]) -> Result<(), APIError> {
3079                 let _lck = self.total_consistency_lock.read().unwrap();
3080                 self.send_payment_along_path(path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv_bytes)
3081         }
3082
3083         fn send_payment_along_path(&self, path: &Path, payment_hash: &PaymentHash, recipient_onion: RecipientOnionFields, total_value: u64, cur_height: u32, payment_id: PaymentId, keysend_preimage: &Option<PaymentPreimage>, session_priv_bytes: [u8; 32]) -> Result<(), APIError> {
3084                 // The top-level caller should hold the total_consistency_lock read lock.
3085                 debug_assert!(self.total_consistency_lock.try_write().is_err());
3086
3087                 log_trace!(self.logger, "Attempting to send payment for path with next hop {}", path.hops.first().unwrap().short_channel_id);
3088                 let prng_seed = self.entropy_source.get_secure_random_bytes();
3089                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
3090
3091                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
3092                         .map_err(|_| APIError::InvalidRoute{err: "Pubkey along hop was maliciously selected".to_owned()})?;
3093                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, recipient_onion, cur_height, keysend_preimage)?;
3094
3095                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash)
3096                         .map_err(|_| APIError::InvalidRoute { err: "Route size too large considering onion data".to_owned()})?;
3097
3098                 let err: Result<(), _> = loop {
3099                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.hops.first().unwrap().short_channel_id) {
3100                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
3101                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3102                         };
3103
3104                         let per_peer_state = self.per_peer_state.read().unwrap();
3105                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
3106                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
3107                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3108                         let peer_state = &mut *peer_state_lock;
3109                         if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(id) {
3110                                 if !chan.get().context.is_live() {
3111                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
3112                                 }
3113                                 let funding_txo = chan.get().context.get_funding_txo().unwrap();
3114                                 let send_res = chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(),
3115                                         htlc_cltv, HTLCSource::OutboundRoute {
3116                                                 path: path.clone(),
3117                                                 session_priv: session_priv.clone(),
3118                                                 first_hop_htlc_msat: htlc_msat,
3119                                                 payment_id,
3120                                         }, onion_packet, None, &self.fee_estimator, &self.logger);
3121                                 match break_chan_entry!(self, send_res, chan) {
3122                                         Some(monitor_update) => {
3123                                                 match handle_new_monitor_update!(self, funding_txo, monitor_update, peer_state_lock, peer_state, per_peer_state, chan) {
3124                                                         Err(e) => break Err(e),
3125                                                         Ok(false) => {
3126                                                                 // Note that MonitorUpdateInProgress here indicates (per function
3127                                                                 // docs) that we will resend the commitment update once monitor
3128                                                                 // updating completes. Therefore, we must return an error
3129                                                                 // indicating that it is unsafe to retry the payment wholesale,
3130                                                                 // which we do in the send_payment check for
3131                                                                 // MonitorUpdateInProgress, below.
3132                                                                 return Err(APIError::MonitorUpdateInProgress);
3133                                                         },
3134                                                         Ok(true) => {},
3135                                                 }
3136                                         },
3137                                         None => { },
3138                                 }
3139                         } else {
3140                                 // The channel was likely removed after we fetched the id from the
3141                                 // `short_to_chan_info` map, but before we successfully locked the
3142                                 // `channel_by_id` map.
3143                                 // This can occur as no consistency guarantees exists between the two maps.
3144                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
3145                         }
3146                         return Ok(());
3147                 };
3148
3149                 match handle_error!(self, err, path.hops.first().unwrap().pubkey) {
3150                         Ok(_) => unreachable!(),
3151                         Err(e) => {
3152                                 Err(APIError::ChannelUnavailable { err: e.err })
3153                         },
3154                 }
3155         }
3156
3157         /// Sends a payment along a given route.
3158         ///
3159         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
3160         /// fields for more info.
3161         ///
3162         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
3163         /// [`PeerManager::process_events`]).
3164         ///
3165         /// # Avoiding Duplicate Payments
3166         ///
3167         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
3168         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
3169         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
3170         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
3171         /// second payment with the same [`PaymentId`].
3172         ///
3173         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
3174         /// tracking of payments, including state to indicate once a payment has completed. Because you
3175         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
3176         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
3177         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
3178         ///
3179         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
3180         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
3181         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
3182         /// [`ChannelManager::list_recent_payments`] for more information.
3183         ///
3184         /// # Possible Error States on [`PaymentSendFailure`]
3185         ///
3186         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
3187         /// each entry matching the corresponding-index entry in the route paths, see
3188         /// [`PaymentSendFailure`] for more info.
3189         ///
3190         /// In general, a path may raise:
3191         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
3192         ///    node public key) is specified.
3193         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available for updates
3194         ///    (including due to previous monitor update failure or new permanent monitor update
3195         ///    failure).
3196         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
3197         ///    relevant updates.
3198         ///
3199         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
3200         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
3201         /// different route unless you intend to pay twice!
3202         ///
3203         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3204         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3205         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
3206         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
3207         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
3208         pub fn send_payment_with_route(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
3209                 let best_block_height = self.best_block.read().unwrap().height();
3210                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3211                 self.pending_outbound_payments
3212                         .send_payment_with_route(route, payment_hash, recipient_onion, payment_id, &self.entropy_source, &self.node_signer, best_block_height,
3213                                 |path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv|
3214                                 self.send_payment_along_path(path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv))
3215         }
3216
3217         /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
3218         /// `route_params` and retry failed payment paths based on `retry_strategy`.
3219         pub fn send_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
3220                 let best_block_height = self.best_block.read().unwrap().height();
3221                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3222                 self.pending_outbound_payments
3223                         .send_payment(payment_hash, recipient_onion, payment_id, retry_strategy, route_params,
3224                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
3225                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
3226                                 &self.pending_events,
3227                                 |path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv|
3228                                 self.send_payment_along_path(path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv))
3229         }
3230
3231         #[cfg(test)]
3232         pub(super) fn test_send_payment_internal(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>, onion_session_privs: Vec<[u8; 32]>) -> Result<(), PaymentSendFailure> {
3233                 let best_block_height = self.best_block.read().unwrap().height();
3234                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3235                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer, best_block_height,
3236                         |path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv|
3237                         self.send_payment_along_path(path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv))
3238         }
3239
3240         #[cfg(test)]
3241         pub(crate) fn test_add_new_pending_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route: &Route) -> Result<Vec<[u8; 32]>, PaymentSendFailure> {
3242                 let best_block_height = self.best_block.read().unwrap().height();
3243                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height)
3244         }
3245
3246         #[cfg(test)]
3247         pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>) {
3248                 self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
3249         }
3250
3251
3252         /// Signals that no further retries for the given payment should occur. Useful if you have a
3253         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
3254         /// retries are exhausted.
3255         ///
3256         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
3257         /// as there are no remaining pending HTLCs for this payment.
3258         ///
3259         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
3260         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
3261         /// determine the ultimate status of a payment.
3262         ///
3263         /// If an [`Event::PaymentFailed`] event is generated and we restart without this
3264         /// [`ChannelManager`] having been persisted, another [`Event::PaymentFailed`] may be generated.
3265         ///
3266         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3267         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3268         pub fn abandon_payment(&self, payment_id: PaymentId) {
3269                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3270                 self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
3271         }
3272
3273         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
3274         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
3275         /// the preimage, it must be a cryptographically secure random value that no intermediate node
3276         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
3277         /// never reach the recipient.
3278         ///
3279         /// See [`send_payment`] documentation for more details on the return value of this function
3280         /// and idempotency guarantees provided by the [`PaymentId`] key.
3281         ///
3282         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
3283         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
3284         ///
3285         /// [`send_payment`]: Self::send_payment
3286         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
3287                 let best_block_height = self.best_block.read().unwrap().height();
3288                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3289                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
3290                         route, payment_preimage, recipient_onion, payment_id, &self.entropy_source,
3291                         &self.node_signer, best_block_height,
3292                         |path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv|
3293                         self.send_payment_along_path(path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv))
3294         }
3295
3296         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
3297         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
3298         ///
3299         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
3300         /// payments.
3301         ///
3302         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
3303         pub fn send_spontaneous_payment_with_retry(&self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<PaymentHash, RetryableSendFailure> {
3304                 let best_block_height = self.best_block.read().unwrap().height();
3305                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3306                 self.pending_outbound_payments.send_spontaneous_payment(payment_preimage, recipient_onion,
3307                         payment_id, retry_strategy, route_params, &self.router, self.list_usable_channels(),
3308                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
3309                         &self.logger, &self.pending_events,
3310                         |path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv|
3311                         self.send_payment_along_path(path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv))
3312         }
3313
3314         /// Send a payment that is probing the given route for liquidity. We calculate the
3315         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
3316         /// us to easily discern them from real payments.
3317         pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
3318                 let best_block_height = self.best_block.read().unwrap().height();
3319                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3320                 self.pending_outbound_payments.send_probe(path, self.probing_cookie_secret, &self.entropy_source, &self.node_signer, best_block_height,
3321                         |path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv|
3322                         self.send_payment_along_path(path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv))
3323         }
3324
3325         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
3326         /// payment probe.
3327         #[cfg(test)]
3328         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
3329                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
3330         }
3331
3332         /// Handles the generation of a funding transaction, optionally (for tests) with a function
3333         /// which checks the correctness of the funding transaction given the associated channel.
3334         fn funding_transaction_generated_intern<FundingOutput: Fn(&OutboundV1Channel<<SP::Target as SignerProvider>::Signer>, &Transaction) -> Result<OutPoint, APIError>>(
3335                 &self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, funding_transaction: Transaction, find_funding_output: FundingOutput
3336         ) -> Result<(), APIError> {
3337                 let per_peer_state = self.per_peer_state.read().unwrap();
3338                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3339                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3340
3341                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3342                 let peer_state = &mut *peer_state_lock;
3343                 let (chan, msg) = match peer_state.outbound_v1_channel_by_id.remove(temporary_channel_id) {
3344                         Some(chan) => {
3345                                 let funding_txo = find_funding_output(&chan, &funding_transaction)?;
3346
3347                                 let funding_res = chan.get_outbound_funding_created(funding_transaction, funding_txo, &self.logger)
3348                                         .map_err(|(mut chan, e)| if let ChannelError::Close(msg) = e {
3349                                                 let channel_id = chan.context.channel_id();
3350                                                 let user_id = chan.context.get_user_id();
3351                                                 let shutdown_res = chan.context.force_shutdown(false);
3352                                                 (chan, MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, user_id, shutdown_res, None))
3353                                         } else { unreachable!(); });
3354                                 match funding_res {
3355                                         Ok((chan, funding_msg)) => (chan, funding_msg),
3356                                         Err((chan, err)) => {
3357                                                 mem::drop(peer_state_lock);
3358                                                 mem::drop(per_peer_state);
3359
3360                                                 let _: Result<(), _> = handle_error!(self, Err(err), chan.context.get_counterparty_node_id());
3361                                                 return Err(APIError::ChannelUnavailable {
3362                                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
3363                                                 });
3364                                         },
3365                                 }
3366                         },
3367                         None => {
3368                                 return Err(APIError::ChannelUnavailable {
3369                                         err: format!(
3370                                                 "Channel with id {} not found for the passed counterparty node_id {}",
3371                                                 log_bytes!(*temporary_channel_id), counterparty_node_id),
3372                                 })
3373                         },
3374                 };
3375
3376                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
3377                         node_id: chan.context.get_counterparty_node_id(),
3378                         msg,
3379                 });
3380                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
3381                         hash_map::Entry::Occupied(_) => {
3382                                 panic!("Generated duplicate funding txid?");
3383                         },
3384                         hash_map::Entry::Vacant(e) => {
3385                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
3386                                 if id_to_peer.insert(chan.context.channel_id(), chan.context.get_counterparty_node_id()).is_some() {
3387                                         panic!("id_to_peer map already contained funding txid, which shouldn't be possible");
3388                                 }
3389                                 e.insert(chan);
3390                         }
3391                 }
3392                 Ok(())
3393         }
3394
3395         #[cfg(test)]
3396         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> {
3397                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, |_, tx| {
3398                         Ok(OutPoint { txid: tx.txid(), index: output_index })
3399                 })
3400         }
3401
3402         /// Call this upon creation of a funding transaction for the given channel.
3403         ///
3404         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
3405         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
3406         ///
3407         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
3408         /// across the p2p network.
3409         ///
3410         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
3411         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
3412         ///
3413         /// May panic if the output found in the funding transaction is duplicative with some other
3414         /// channel (note that this should be trivially prevented by using unique funding transaction
3415         /// keys per-channel).
3416         ///
3417         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
3418         /// counterparty's signature the funding transaction will automatically be broadcast via the
3419         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
3420         ///
3421         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
3422         /// not currently support replacing a funding transaction on an existing channel. Instead,
3423         /// create a new channel with a conflicting funding transaction.
3424         ///
3425         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
3426         /// the wallet software generating the funding transaction to apply anti-fee sniping as
3427         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
3428         /// for more details.
3429         ///
3430         /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
3431         /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
3432         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
3433                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3434
3435                 for inp in funding_transaction.input.iter() {
3436                         if inp.witness.is_empty() {
3437                                 return Err(APIError::APIMisuseError {
3438                                         err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
3439                                 });
3440                         }
3441                 }
3442                 {
3443                         let height = self.best_block.read().unwrap().height();
3444                         // Transactions are evaluated as final by network mempools if their locktime is strictly
3445                         // lower than the next block height. However, the modules constituting our Lightning
3446                         // node might not have perfect sync about their blockchain views. Thus, if the wallet
3447                         // module is ahead of LDK, only allow one more block of headroom.
3448                         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 + 1 {
3449                                 return Err(APIError::APIMisuseError {
3450                                         err: "Funding transaction absolute timelock is non-final".to_owned()
3451                                 });
3452                         }
3453                 }
3454                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, |chan, tx| {
3455                         if tx.output.len() > u16::max_value() as usize {
3456                                 return Err(APIError::APIMisuseError {
3457                                         err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
3458                                 });
3459                         }
3460
3461                         let mut output_index = None;
3462                         let expected_spk = chan.context.get_funding_redeemscript().to_v0_p2wsh();
3463                         for (idx, outp) in tx.output.iter().enumerate() {
3464                                 if outp.script_pubkey == expected_spk && outp.value == chan.context.get_value_satoshis() {
3465                                         if output_index.is_some() {
3466                                                 return Err(APIError::APIMisuseError {
3467                                                         err: "Multiple outputs matched the expected script and value".to_owned()
3468                                                 });
3469                                         }
3470                                         output_index = Some(idx as u16);
3471                                 }
3472                         }
3473                         if output_index.is_none() {
3474                                 return Err(APIError::APIMisuseError {
3475                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
3476                                 });
3477                         }
3478                         Ok(OutPoint { txid: tx.txid(), index: output_index.unwrap() })
3479                 })
3480         }
3481
3482         /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
3483         ///
3484         /// Once the updates are applied, each eligible channel (advertised with a known short channel
3485         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
3486         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
3487         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
3488         ///
3489         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
3490         /// `counterparty_node_id` is provided.
3491         ///
3492         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
3493         /// below [`MIN_CLTV_EXPIRY_DELTA`].
3494         ///
3495         /// If an error is returned, none of the updates should be considered applied.
3496         ///
3497         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
3498         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
3499         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
3500         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
3501         /// [`ChannelUpdate`]: msgs::ChannelUpdate
3502         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
3503         /// [`APIMisuseError`]: APIError::APIMisuseError
3504         pub fn update_partial_channel_config(
3505                 &self, counterparty_node_id: &PublicKey, channel_ids: &[[u8; 32]], config_update: &ChannelConfigUpdate,
3506         ) -> Result<(), APIError> {
3507                 if config_update.cltv_expiry_delta.map(|delta| delta < MIN_CLTV_EXPIRY_DELTA).unwrap_or(false) {
3508                         return Err(APIError::APIMisuseError {
3509                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
3510                         });
3511                 }
3512
3513                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3514                 let per_peer_state = self.per_peer_state.read().unwrap();
3515                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3516                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3517                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3518                 let peer_state = &mut *peer_state_lock;
3519                 for channel_id in channel_ids {
3520                         if !peer_state.channel_by_id.contains_key(channel_id) {
3521                                 return Err(APIError::ChannelUnavailable {
3522                                         err: format!("Channel with ID {} was not found for the passed counterparty_node_id {}", log_bytes!(*channel_id), counterparty_node_id),
3523                                 });
3524                         }
3525                 }
3526                 for channel_id in channel_ids {
3527                         let channel = peer_state.channel_by_id.get_mut(channel_id).unwrap();
3528                         let mut config = channel.context.config();
3529                         config.apply(config_update);
3530                         if !channel.context.update_config(&config) {
3531                                 continue;
3532                         }
3533                         if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
3534                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
3535                         } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
3536                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
3537                                         node_id: channel.context.get_counterparty_node_id(),
3538                                         msg,
3539                                 });
3540                         }
3541                 }
3542                 Ok(())
3543         }
3544
3545         /// Atomically updates the [`ChannelConfig`] for the given channels.
3546         ///
3547         /// Once the updates are applied, each eligible channel (advertised with a known short channel
3548         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
3549         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
3550         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
3551         ///
3552         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
3553         /// `counterparty_node_id` is provided.
3554         ///
3555         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
3556         /// below [`MIN_CLTV_EXPIRY_DELTA`].
3557         ///
3558         /// If an error is returned, none of the updates should be considered applied.
3559         ///
3560         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
3561         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
3562         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
3563         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
3564         /// [`ChannelUpdate`]: msgs::ChannelUpdate
3565         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
3566         /// [`APIMisuseError`]: APIError::APIMisuseError
3567         pub fn update_channel_config(
3568                 &self, counterparty_node_id: &PublicKey, channel_ids: &[[u8; 32]], config: &ChannelConfig,
3569         ) -> Result<(), APIError> {
3570                 return self.update_partial_channel_config(counterparty_node_id, channel_ids, &(*config).into());
3571         }
3572
3573         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
3574         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
3575         ///
3576         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
3577         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
3578         ///
3579         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
3580         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
3581         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
3582         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
3583         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
3584         ///
3585         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
3586         /// you from forwarding more than you received. See
3587         /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
3588         /// than expected.
3589         ///
3590         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
3591         /// backwards.
3592         ///
3593         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
3594         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
3595         /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
3596         // TODO: when we move to deciding the best outbound channel at forward time, only take
3597         // `next_node_id` and not `next_hop_channel_id`
3598         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> {
3599                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3600
3601                 let next_hop_scid = {
3602                         let peer_state_lock = self.per_peer_state.read().unwrap();
3603                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
3604                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
3605                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3606                         let peer_state = &mut *peer_state_lock;
3607                         match peer_state.channel_by_id.get(next_hop_channel_id) {
3608                                 Some(chan) => {
3609                                         if !chan.context.is_usable() {
3610                                                 return Err(APIError::ChannelUnavailable {
3611                                                         err: format!("Channel with id {} not fully established", log_bytes!(*next_hop_channel_id))
3612                                                 })
3613                                         }
3614                                         chan.context.get_short_channel_id().unwrap_or(chan.context.outbound_scid_alias())
3615                                 },
3616                                 None => return Err(APIError::ChannelUnavailable {
3617                                         err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
3618                                                 log_bytes!(*next_hop_channel_id), next_node_id)
3619                                 })
3620                         }
3621                 };
3622
3623                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
3624                         .ok_or_else(|| APIError::APIMisuseError {
3625                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
3626                         })?;
3627
3628                 let routing = match payment.forward_info.routing {
3629                         PendingHTLCRouting::Forward { onion_packet, .. } => {
3630                                 PendingHTLCRouting::Forward { onion_packet, short_channel_id: next_hop_scid }
3631                         },
3632                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
3633                 };
3634                 let skimmed_fee_msat =
3635                         payment.forward_info.outgoing_amt_msat.saturating_sub(amt_to_forward_msat);
3636                 let pending_htlc_info = PendingHTLCInfo {
3637                         skimmed_fee_msat: if skimmed_fee_msat == 0 { None } else { Some(skimmed_fee_msat) },
3638                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
3639                 };
3640
3641                 let mut per_source_pending_forward = [(
3642                         payment.prev_short_channel_id,
3643                         payment.prev_funding_outpoint,
3644                         payment.prev_user_channel_id,
3645                         vec![(pending_htlc_info, payment.prev_htlc_id)]
3646                 )];
3647                 self.forward_htlcs(&mut per_source_pending_forward);
3648                 Ok(())
3649         }
3650
3651         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
3652         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
3653         ///
3654         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
3655         /// backwards.
3656         ///
3657         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
3658         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
3659                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3660
3661                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
3662                         .ok_or_else(|| APIError::APIMisuseError {
3663                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
3664                         })?;
3665
3666                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
3667                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3668                                 short_channel_id: payment.prev_short_channel_id,
3669                                 outpoint: payment.prev_funding_outpoint,
3670                                 htlc_id: payment.prev_htlc_id,
3671                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
3672                                 phantom_shared_secret: None,
3673                         });
3674
3675                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
3676                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
3677                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
3678                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
3679
3680                 Ok(())
3681         }
3682
3683         /// Processes HTLCs which are pending waiting on random forward delay.
3684         ///
3685         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
3686         /// Will likely generate further events.
3687         pub fn process_pending_htlc_forwards(&self) {
3688                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3689
3690                 let mut new_events = VecDeque::new();
3691                 let mut failed_forwards = Vec::new();
3692                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
3693                 {
3694                         let mut forward_htlcs = HashMap::new();
3695                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
3696
3697                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
3698                                 if short_chan_id != 0 {
3699                                         macro_rules! forwarding_channel_not_found {
3700                                                 () => {
3701                                                         for forward_info in pending_forwards.drain(..) {
3702                                                                 match forward_info {
3703                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
3704                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
3705                                                                                 forward_info: PendingHTLCInfo {
3706                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
3707                                                                                         outgoing_cltv_value, ..
3708                                                                                 }
3709                                                                         }) => {
3710                                                                                 macro_rules! failure_handler {
3711                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
3712                                                                                                 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3713
3714                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3715                                                                                                         short_channel_id: prev_short_channel_id,
3716                                                                                                         outpoint: prev_funding_outpoint,
3717                                                                                                         htlc_id: prev_htlc_id,
3718                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
3719                                                                                                         phantom_shared_secret: $phantom_ss,
3720                                                                                                 });
3721
3722                                                                                                 let reason = if $next_hop_unknown {
3723                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
3724                                                                                                 } else {
3725                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
3726                                                                                                 };
3727
3728                                                                                                 failed_forwards.push((htlc_source, payment_hash,
3729                                                                                                         HTLCFailReason::reason($err_code, $err_data),
3730                                                                                                         reason
3731                                                                                                 ));
3732                                                                                                 continue;
3733                                                                                         }
3734                                                                                 }
3735                                                                                 macro_rules! fail_forward {
3736                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
3737                                                                                                 {
3738                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
3739                                                                                                 }
3740                                                                                         }
3741                                                                                 }
3742                                                                                 macro_rules! failed_payment {
3743                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
3744                                                                                                 {
3745                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
3746                                                                                                 }
3747                                                                                         }
3748                                                                                 }
3749                                                                                 if let PendingHTLCRouting::Forward { onion_packet, .. } = routing {
3750                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
3751                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.genesis_hash) {
3752                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
3753                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac, payment_hash) {
3754                                                                                                         Ok(res) => res,
3755                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
3756                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();
3757                                                                                                                 // In this scenario, the phantom would have sent us an
3758                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
3759                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
3760                                                                                                                 // of the onion.
3761                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
3762                                                                                                         },
3763                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
3764                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
3765                                                                                                         },
3766                                                                                                 };
3767                                                                                                 match next_hop {
3768                                                                                                         onion_utils::Hop::Receive(hop_data) => {
3769                                                                                                                 match self.construct_recv_pending_htlc_info(hop_data,
3770                                                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat,
3771                                                                                                                         outgoing_cltv_value, Some(phantom_shared_secret), false, None)
3772                                                                                                                 {
3773                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
3774                                                                                                                         Err(ReceiveError { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
3775                                                                                                                 }
3776                                                                                                         },
3777                                                                                                         _ => panic!(),
3778                                                                                                 }
3779                                                                                         } else {
3780                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
3781                                                                                         }
3782                                                                                 } else {
3783                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
3784                                                                                 }
3785                                                                         },
3786                                                                         HTLCForwardInfo::FailHTLC { .. } => {
3787                                                                                 // Channel went away before we could fail it. This implies
3788                                                                                 // the channel is now on chain and our counterparty is
3789                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
3790                                                                                 // problem, not ours.
3791                                                                         }
3792                                                                 }
3793                                                         }
3794                                                 }
3795                                         }
3796                                         let (counterparty_node_id, forward_chan_id) = match self.short_to_chan_info.read().unwrap().get(&short_chan_id) {
3797                                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3798                                                 None => {
3799                                                         forwarding_channel_not_found!();
3800                                                         continue;
3801                                                 }
3802                                         };
3803                                         let per_peer_state = self.per_peer_state.read().unwrap();
3804                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
3805                                         if peer_state_mutex_opt.is_none() {
3806                                                 forwarding_channel_not_found!();
3807                                                 continue;
3808                                         }
3809                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3810                                         let peer_state = &mut *peer_state_lock;
3811                                         match peer_state.channel_by_id.entry(forward_chan_id) {
3812                                                 hash_map::Entry::Vacant(_) => {
3813                                                         forwarding_channel_not_found!();
3814                                                         continue;
3815                                                 },
3816                                                 hash_map::Entry::Occupied(mut chan) => {
3817                                                         for forward_info in pending_forwards.drain(..) {
3818                                                                 match forward_info {
3819                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
3820                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id: _,
3821                                                                                 forward_info: PendingHTLCInfo {
3822                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
3823                                                                                         routing: PendingHTLCRouting::Forward { onion_packet, .. }, skimmed_fee_msat, ..
3824                                                                                 },
3825                                                                         }) => {
3826                                                                                 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);
3827                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3828                                                                                         short_channel_id: prev_short_channel_id,
3829                                                                                         outpoint: prev_funding_outpoint,
3830                                                                                         htlc_id: prev_htlc_id,
3831                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
3832                                                                                         // Phantom payments are only PendingHTLCRouting::Receive.
3833                                                                                         phantom_shared_secret: None,
3834                                                                                 });
3835                                                                                 if let Err(e) = chan.get_mut().queue_add_htlc(outgoing_amt_msat,
3836                                                                                         payment_hash, outgoing_cltv_value, htlc_source.clone(),
3837                                                                                         onion_packet, skimmed_fee_msat, &self.fee_estimator,
3838                                                                                         &self.logger)
3839                                                                                 {
3840                                                                                         if let ChannelError::Ignore(msg) = e {
3841                                                                                                 log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
3842                                                                                         } else {
3843                                                                                                 panic!("Stated return value requirements in send_htlc() were not met");
3844                                                                                         }
3845                                                                                         let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan.get());
3846                                                                                         failed_forwards.push((htlc_source, payment_hash,
3847                                                                                                 HTLCFailReason::reason(failure_code, data),
3848                                                                                                 HTLCDestination::NextHopChannel { node_id: Some(chan.get().context.get_counterparty_node_id()), channel_id: forward_chan_id }
3849                                                                                         ));
3850                                                                                         continue;
3851                                                                                 }
3852                                                                         },
3853                                                                         HTLCForwardInfo::AddHTLC { .. } => {
3854                                                                                 panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
3855                                                                         },
3856                                                                         HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
3857                                                                                 log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
3858                                                                                 if let Err(e) = chan.get_mut().queue_fail_htlc(
3859                                                                                         htlc_id, err_packet, &self.logger
3860                                                                                 ) {
3861                                                                                         if let ChannelError::Ignore(msg) = e {
3862                                                                                                 log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
3863                                                                                         } else {
3864                                                                                                 panic!("Stated return value requirements in queue_fail_htlc() were not met");
3865                                                                                         }
3866                                                                                         // fail-backs are best-effort, we probably already have one
3867                                                                                         // pending, and if not that's OK, if not, the channel is on
3868                                                                                         // the chain and sending the HTLC-Timeout is their problem.
3869                                                                                         continue;
3870                                                                                 }
3871                                                                         },
3872                                                                 }
3873                                                         }
3874                                                 }
3875                                         }
3876                                 } else {
3877                                         'next_forwardable_htlc: for forward_info in pending_forwards.drain(..) {
3878                                                 match forward_info {
3879                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
3880                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
3881                                                                 forward_info: PendingHTLCInfo {
3882                                                                         routing, incoming_shared_secret, payment_hash, incoming_amt_msat, outgoing_amt_msat,
3883                                                                         skimmed_fee_msat, ..
3884                                                                 }
3885                                                         }) => {
3886                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
3887                                                                         PendingHTLCRouting::Receive { payment_data, payment_metadata, incoming_cltv_expiry, phantom_shared_secret } => {
3888                                                                                 let _legacy_hop_data = Some(payment_data.clone());
3889                                                                                 let onion_fields =
3890                                                                                         RecipientOnionFields { payment_secret: Some(payment_data.payment_secret), payment_metadata };
3891                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
3892                                                                                         Some(payment_data), phantom_shared_secret, onion_fields)
3893                                                                         },
3894                                                                         PendingHTLCRouting::ReceiveKeysend { payment_data, payment_preimage, payment_metadata, incoming_cltv_expiry } => {
3895                                                                                 let onion_fields = RecipientOnionFields {
3896                                                                                         payment_secret: payment_data.as_ref().map(|data| data.payment_secret),
3897                                                                                         payment_metadata
3898                                                                                 };
3899                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
3900                                                                                         payment_data, None, onion_fields)
3901                                                                         },
3902                                                                         _ => {
3903                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
3904                                                                         }
3905                                                                 };
3906                                                                 let claimable_htlc = ClaimableHTLC {
3907                                                                         prev_hop: HTLCPreviousHopData {
3908                                                                                 short_channel_id: prev_short_channel_id,
3909                                                                                 outpoint: prev_funding_outpoint,
3910                                                                                 htlc_id: prev_htlc_id,
3911                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
3912                                                                                 phantom_shared_secret,
3913                                                                         },
3914                                                                         // We differentiate the received value from the sender intended value
3915                                                                         // if possible so that we don't prematurely mark MPP payments complete
3916                                                                         // if routing nodes overpay
3917                                                                         value: incoming_amt_msat.unwrap_or(outgoing_amt_msat),
3918                                                                         sender_intended_value: outgoing_amt_msat,
3919                                                                         timer_ticks: 0,
3920                                                                         total_value_received: None,
3921                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
3922                                                                         cltv_expiry,
3923                                                                         onion_payload,
3924                                                                         counterparty_skimmed_fee_msat: skimmed_fee_msat,
3925                                                                 };
3926
3927                                                                 let mut committed_to_claimable = false;
3928
3929                                                                 macro_rules! fail_htlc {
3930                                                                         ($htlc: expr, $payment_hash: expr) => {
3931                                                                                 debug_assert!(!committed_to_claimable);
3932                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
3933                                                                                 htlc_msat_height_data.extend_from_slice(
3934                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
3935                                                                                 );
3936                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
3937                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
3938                                                                                                 outpoint: prev_funding_outpoint,
3939                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
3940                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
3941                                                                                                 phantom_shared_secret,
3942                                                                                         }), payment_hash,
3943                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
3944                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
3945                                                                                 ));
3946                                                                                 continue 'next_forwardable_htlc;
3947                                                                         }
3948                                                                 }
3949                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
3950                                                                 let mut receiver_node_id = self.our_network_pubkey;
3951                                                                 if phantom_shared_secret.is_some() {
3952                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
3953                                                                                 .expect("Failed to get node_id for phantom node recipient");
3954                                                                 }
3955
3956                                                                 macro_rules! check_total_value {
3957                                                                         ($purpose: expr) => {{
3958                                                                                 let mut payment_claimable_generated = false;
3959                                                                                 let is_keysend = match $purpose {
3960                                                                                         events::PaymentPurpose::SpontaneousPayment(_) => true,
3961                                                                                         events::PaymentPurpose::InvoicePayment { .. } => false,
3962                                                                                 };
3963                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
3964                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
3965                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3966                                                                                 }
3967                                                                                 let ref mut claimable_payment = claimable_payments.claimable_payments
3968                                                                                         .entry(payment_hash)
3969                                                                                         // Note that if we insert here we MUST NOT fail_htlc!()
3970                                                                                         .or_insert_with(|| {
3971                                                                                                 committed_to_claimable = true;
3972                                                                                                 ClaimablePayment {
3973                                                                                                         purpose: $purpose.clone(), htlcs: Vec::new(), onion_fields: None,
3974                                                                                                 }
3975                                                                                         });
3976                                                                                 if $purpose != claimable_payment.purpose {
3977                                                                                         let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" };
3978                                                                                         log_trace!(self.logger, "Failing new {} HTLC with payment_hash {} as we already had an existing {} HTLC with the same payment hash", log_keysend(is_keysend), log_bytes!(payment_hash.0), log_keysend(!is_keysend));
3979                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3980                                                                                 }
3981                                                                                 if !self.default_configuration.accept_mpp_keysend && is_keysend && !claimable_payment.htlcs.is_empty() {
3982                                                                                         log_trace!(self.logger, "Failing new keysend HTLC with payment_hash {} as we already had an existing keysend HTLC with the same payment hash and our config states we don't accept MPP keysend", log_bytes!(payment_hash.0));
3983                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3984                                                                                 }
3985                                                                                 if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
3986                                                                                         if earlier_fields.check_merge(&mut onion_fields).is_err() {
3987                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
3988                                                                                         }
3989                                                                                 } else {
3990                                                                                         claimable_payment.onion_fields = Some(onion_fields);
3991                                                                                 }
3992                                                                                 let ref mut htlcs = &mut claimable_payment.htlcs;
3993                                                                                 let mut total_value = claimable_htlc.sender_intended_value;
3994                                                                                 let mut earliest_expiry = claimable_htlc.cltv_expiry;
3995                                                                                 for htlc in htlcs.iter() {
3996                                                                                         total_value += htlc.sender_intended_value;
3997                                                                                         earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
3998                                                                                         if htlc.total_msat != claimable_htlc.total_msat {
3999                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
4000                                                                                                         log_bytes!(payment_hash.0), claimable_htlc.total_msat, htlc.total_msat);
4001                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
4002                                                                                         }
4003                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
4004                                                                                 }
4005                                                                                 // The condition determining whether an MPP is complete must
4006                                                                                 // match exactly the condition used in `timer_tick_occurred`
4007                                                                                 if total_value >= msgs::MAX_VALUE_MSAT {
4008                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4009                                                                                 } else if total_value - claimable_htlc.sender_intended_value >= claimable_htlc.total_msat {
4010                                                                                         log_trace!(self.logger, "Failing HTLC with payment_hash {} as payment is already claimable",
4011                                                                                                 log_bytes!(payment_hash.0));
4012                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4013                                                                                 } else if total_value >= claimable_htlc.total_msat {
4014                                                                                         #[allow(unused_assignments)] {
4015                                                                                                 committed_to_claimable = true;
4016                                                                                         }
4017                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
4018                                                                                         htlcs.push(claimable_htlc);
4019                                                                                         let amount_msat = htlcs.iter().map(|htlc| htlc.value).sum();
4020                                                                                         htlcs.iter_mut().for_each(|htlc| htlc.total_value_received = Some(amount_msat));
4021                                                                                         let counterparty_skimmed_fee_msat = htlcs.iter()
4022                                                                                                 .map(|htlc| htlc.counterparty_skimmed_fee_msat.unwrap_or(0)).sum();
4023                                                                                         debug_assert!(total_value.saturating_sub(amount_msat) <=
4024                                                                                                 counterparty_skimmed_fee_msat);
4025                                                                                         new_events.push_back((events::Event::PaymentClaimable {
4026                                                                                                 receiver_node_id: Some(receiver_node_id),
4027                                                                                                 payment_hash,
4028                                                                                                 purpose: $purpose,
4029                                                                                                 amount_msat,
4030                                                                                                 counterparty_skimmed_fee_msat,
4031                                                                                                 via_channel_id: Some(prev_channel_id),
4032                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
4033                                                                                                 claim_deadline: Some(earliest_expiry - HTLC_FAIL_BACK_BUFFER),
4034                                                                                                 onion_fields: claimable_payment.onion_fields.clone(),
4035                                                                                         }, None));
4036                                                                                         payment_claimable_generated = true;
4037                                                                                 } else {
4038                                                                                         // Nothing to do - we haven't reached the total
4039                                                                                         // payment value yet, wait until we receive more
4040                                                                                         // MPP parts.
4041                                                                                         htlcs.push(claimable_htlc);
4042                                                                                         #[allow(unused_assignments)] {
4043                                                                                                 committed_to_claimable = true;
4044                                                                                         }
4045                                                                                 }
4046                                                                                 payment_claimable_generated
4047                                                                         }}
4048                                                                 }
4049
4050                                                                 // Check that the payment hash and secret are known. Note that we
4051                                                                 // MUST take care to handle the "unknown payment hash" and
4052                                                                 // "incorrect payment secret" cases here identically or we'd expose
4053                                                                 // that we are the ultimate recipient of the given payment hash.
4054                                                                 // Further, we must not expose whether we have any other HTLCs
4055                                                                 // associated with the same payment_hash pending or not.
4056                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
4057                                                                 match payment_secrets.entry(payment_hash) {
4058                                                                         hash_map::Entry::Vacant(_) => {
4059                                                                                 match claimable_htlc.onion_payload {
4060                                                                                         OnionPayload::Invoice { .. } => {
4061                                                                                                 let payment_data = payment_data.unwrap();
4062                                                                                                 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) {
4063                                                                                                         Ok(result) => result,
4064                                                                                                         Err(()) => {
4065                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", log_bytes!(payment_hash.0));
4066                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4067                                                                                                         }
4068                                                                                                 };
4069                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
4070                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
4071                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
4072                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
4073                                                                                                                         log_bytes!(payment_hash.0), cltv_expiry, expected_min_expiry_height);
4074                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4075                                                                                                         }
4076                                                                                                 }
4077                                                                                                 let purpose = events::PaymentPurpose::InvoicePayment {
4078                                                                                                         payment_preimage: payment_preimage.clone(),
4079                                                                                                         payment_secret: payment_data.payment_secret,
4080                                                                                                 };
4081                                                                                                 check_total_value!(purpose);
4082                                                                                         },
4083                                                                                         OnionPayload::Spontaneous(preimage) => {
4084                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
4085                                                                                                 check_total_value!(purpose);
4086                                                                                         }
4087                                                                                 }
4088                                                                         },
4089                                                                         hash_map::Entry::Occupied(inbound_payment) => {
4090                                                                                 if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
4091                                                                                         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));
4092                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4093                                                                                 }
4094                                                                                 let payment_data = payment_data.unwrap();
4095                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
4096                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", log_bytes!(payment_hash.0));
4097                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4098                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
4099                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
4100                                                                                                 log_bytes!(payment_hash.0), payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
4101                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4102                                                                                 } else {
4103                                                                                         let purpose = events::PaymentPurpose::InvoicePayment {
4104                                                                                                 payment_preimage: inbound_payment.get().payment_preimage,
4105                                                                                                 payment_secret: payment_data.payment_secret,
4106                                                                                         };
4107                                                                                         let payment_claimable_generated = check_total_value!(purpose);
4108                                                                                         if payment_claimable_generated {
4109                                                                                                 inbound_payment.remove_entry();
4110                                                                                         }
4111                                                                                 }
4112                                                                         },
4113                                                                 };
4114                                                         },
4115                                                         HTLCForwardInfo::FailHTLC { .. } => {
4116                                                                 panic!("Got pending fail of our own HTLC");
4117                                                         }
4118                                                 }
4119                                         }
4120                                 }
4121                         }
4122                 }
4123
4124                 let best_block_height = self.best_block.read().unwrap().height();
4125                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
4126                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
4127                         &self.pending_events, &self.logger,
4128                         |path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv|
4129                         self.send_payment_along_path(path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, session_priv));
4130
4131                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
4132                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4133                 }
4134                 self.forward_htlcs(&mut phantom_receives);
4135
4136                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
4137                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
4138                 // nice to do the work now if we can rather than while we're trying to get messages in the
4139                 // network stack.
4140                 self.check_free_holding_cells();
4141
4142                 if new_events.is_empty() { return }
4143                 let mut events = self.pending_events.lock().unwrap();
4144                 events.append(&mut new_events);
4145         }
4146
4147         /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors.
4148         ///
4149         /// Expects the caller to have a total_consistency_lock read lock.
4150         fn process_background_events(&self) -> NotifyOption {
4151                 debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread);
4152
4153                 #[cfg(debug_assertions)]
4154                 self.background_events_processed_since_startup.store(true, Ordering::Release);
4155
4156                 let mut background_events = Vec::new();
4157                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
4158                 if background_events.is_empty() {
4159                         return NotifyOption::SkipPersist;
4160                 }
4161
4162                 for event in background_events.drain(..) {
4163                         match event {
4164                                 BackgroundEvent::ClosingMonitorUpdateRegeneratedOnStartup((funding_txo, update)) => {
4165                                         // The channel has already been closed, so no use bothering to care about the
4166                                         // monitor updating completing.
4167                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
4168                                 },
4169                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id, funding_txo, update } => {
4170                                         let mut updated_chan = false;
4171                                         let res = {
4172                                                 let per_peer_state = self.per_peer_state.read().unwrap();
4173                                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4174                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4175                                                         let peer_state = &mut *peer_state_lock;
4176                                                         match peer_state.channel_by_id.entry(funding_txo.to_channel_id()) {
4177                                                                 hash_map::Entry::Occupied(mut chan) => {
4178                                                                         updated_chan = true;
4179                                                                         handle_new_monitor_update!(self, funding_txo, update.clone(),
4180                                                                                 peer_state_lock, peer_state, per_peer_state, chan).map(|_| ())
4181                                                                 },
4182                                                                 hash_map::Entry::Vacant(_) => Ok(()),
4183                                                         }
4184                                                 } else { Ok(()) }
4185                                         };
4186                                         if !updated_chan {
4187                                                 // TODO: Track this as in-flight even though the channel is closed.
4188                                                 let _ = self.chain_monitor.update_channel(funding_txo, &update);
4189                                         }
4190                                         // TODO: If this channel has since closed, we're likely providing a payment
4191                                         // preimage update, which we must ensure is durable! We currently don't,
4192                                         // however, ensure that.
4193                                         if res.is_err() {
4194                                                 log_error!(self.logger,
4195                                                         "Failed to provide ChannelMonitorUpdate to closed channel! This likely lost us a payment preimage!");
4196                                         }
4197                                         let _ = handle_error!(self, res, counterparty_node_id);
4198                                 },
4199                         }
4200                 }
4201                 NotifyOption::DoPersist
4202         }
4203
4204         #[cfg(any(test, feature = "_test_utils"))]
4205         /// Process background events, for functional testing
4206         pub fn test_process_background_events(&self) {
4207                 let _lck = self.total_consistency_lock.read().unwrap();
4208                 let _ = self.process_background_events();
4209         }
4210
4211         fn update_channel_fee(&self, chan_id: &[u8; 32], chan: &mut Channel<<SP::Target as SignerProvider>::Signer>, new_feerate: u32) -> NotifyOption {
4212                 if !chan.context.is_outbound() { return NotifyOption::SkipPersist; }
4213                 // If the feerate has decreased by less than half, don't bother
4214                 if new_feerate <= chan.context.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.context.get_feerate_sat_per_1000_weight() {
4215                         log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {}.",
4216                                 log_bytes!(chan_id[..]), chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4217                         return NotifyOption::SkipPersist;
4218                 }
4219                 if !chan.context.is_live() {
4220                         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).",
4221                                 log_bytes!(chan_id[..]), chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4222                         return NotifyOption::SkipPersist;
4223                 }
4224                 log_trace!(self.logger, "Channel {} qualifies for a feerate change from {} to {}.",
4225                         log_bytes!(chan_id[..]), chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4226
4227                 chan.queue_update_fee(new_feerate, &self.fee_estimator, &self.logger);
4228                 NotifyOption::DoPersist
4229         }
4230
4231         #[cfg(fuzzing)]
4232         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
4233         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
4234         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
4235         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
4236         pub fn maybe_update_chan_fees(&self) {
4237                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
4238                         let mut should_persist = self.process_background_events();
4239
4240                         let new_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4241
4242                         let per_peer_state = self.per_peer_state.read().unwrap();
4243                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
4244                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4245                                 let peer_state = &mut *peer_state_lock;
4246                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut() {
4247                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4248                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4249                                 }
4250                         }
4251
4252                         should_persist
4253                 });
4254         }
4255
4256         /// Performs actions which should happen on startup and roughly once per minute thereafter.
4257         ///
4258         /// This currently includes:
4259         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
4260         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
4261         ///    than a minute, informing the network that they should no longer attempt to route over
4262         ///    the channel.
4263         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
4264         ///    with the current [`ChannelConfig`].
4265         ///  * Removing peers which have disconnected but and no longer have any channels.
4266         ///
4267         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
4268         /// estimate fetches.
4269         ///
4270         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4271         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
4272         pub fn timer_tick_occurred(&self) {
4273                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
4274                         let mut should_persist = self.process_background_events();
4275
4276                         let new_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4277
4278                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
4279                         let mut timed_out_mpp_htlcs = Vec::new();
4280                         let mut pending_peers_awaiting_removal = Vec::new();
4281                         {
4282                                 let per_peer_state = self.per_peer_state.read().unwrap();
4283                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
4284                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4285                                         let peer_state = &mut *peer_state_lock;
4286                                         let pending_msg_events = &mut peer_state.pending_msg_events;
4287                                         let counterparty_node_id = *counterparty_node_id;
4288                                         peer_state.channel_by_id.retain(|chan_id, chan| {
4289                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4290                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4291
4292                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
4293                                                         let (needs_close, err) = convert_chan_err!(self, e, chan, chan_id);
4294                                                         handle_errors.push((Err(err), counterparty_node_id));
4295                                                         if needs_close { return false; }
4296                                                 }
4297
4298                                                 match chan.channel_update_status() {
4299                                                         ChannelUpdateStatus::Enabled if !chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(0)),
4300                                                         ChannelUpdateStatus::Disabled if chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(0)),
4301                                                         ChannelUpdateStatus::DisabledStaged(_) if chan.context.is_live()
4302                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
4303                                                         ChannelUpdateStatus::EnabledStaged(_) if !chan.context.is_live()
4304                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
4305                                                         ChannelUpdateStatus::DisabledStaged(mut n) if !chan.context.is_live() => {
4306                                                                 n += 1;
4307                                                                 if n >= DISABLE_GOSSIP_TICKS {
4308                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
4309                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4310                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4311                                                                                         msg: update
4312                                                                                 });
4313                                                                         }
4314                                                                         should_persist = NotifyOption::DoPersist;
4315                                                                 } else {
4316                                                                         chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(n));
4317                                                                 }
4318                                                         },
4319                                                         ChannelUpdateStatus::EnabledStaged(mut n) if chan.context.is_live() => {
4320                                                                 n += 1;
4321                                                                 if n >= ENABLE_GOSSIP_TICKS {
4322                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
4323                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4324                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4325                                                                                         msg: update
4326                                                                                 });
4327                                                                         }
4328                                                                         should_persist = NotifyOption::DoPersist;
4329                                                                 } else {
4330                                                                         chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(n));
4331                                                                 }
4332                                                         },
4333                                                         _ => {},
4334                                                 }
4335
4336                                                 chan.context.maybe_expire_prev_config();
4337
4338                                                 if chan.should_disconnect_peer_awaiting_response() {
4339                                                         log_debug!(self.logger, "Disconnecting peer {} due to not making any progress on channel {}",
4340                                                                         counterparty_node_id, log_bytes!(*chan_id));
4341                                                         pending_msg_events.push(MessageSendEvent::HandleError {
4342                                                                 node_id: counterparty_node_id,
4343                                                                 action: msgs::ErrorAction::DisconnectPeerWithWarning {
4344                                                                         msg: msgs::WarningMessage {
4345                                                                                 channel_id: *chan_id,
4346                                                                                 data: "Disconnecting due to timeout awaiting response".to_owned(),
4347                                                                         },
4348                                                                 },
4349                                                         });
4350                                                 }
4351
4352                                                 true
4353                                         });
4354                                         if peer_state.ok_to_remove(true) {
4355                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
4356                                         }
4357                                 }
4358                         }
4359
4360                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
4361                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
4362                         // of to that peer is later closed while still being disconnected (i.e. force closed),
4363                         // we therefore need to remove the peer from `peer_state` separately.
4364                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
4365                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
4366                         // negative effects on parallelism as much as possible.
4367                         if pending_peers_awaiting_removal.len() > 0 {
4368                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
4369                                 for counterparty_node_id in pending_peers_awaiting_removal {
4370                                         match per_peer_state.entry(counterparty_node_id) {
4371                                                 hash_map::Entry::Occupied(entry) => {
4372                                                         // Remove the entry if the peer is still disconnected and we still
4373                                                         // have no channels to the peer.
4374                                                         let remove_entry = {
4375                                                                 let peer_state = entry.get().lock().unwrap();
4376                                                                 peer_state.ok_to_remove(true)
4377                                                         };
4378                                                         if remove_entry {
4379                                                                 entry.remove_entry();
4380                                                         }
4381                                                 },
4382                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
4383                                         }
4384                                 }
4385                         }
4386
4387                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
4388                                 if payment.htlcs.is_empty() {
4389                                         // This should be unreachable
4390                                         debug_assert!(false);
4391                                         return false;
4392                                 }
4393                                 if let OnionPayload::Invoice { .. } = payment.htlcs[0].onion_payload {
4394                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
4395                                         // In this case we're not going to handle any timeouts of the parts here.
4396                                         // This condition determining whether the MPP is complete here must match
4397                                         // exactly the condition used in `process_pending_htlc_forwards`.
4398                                         if payment.htlcs[0].total_msat <= payment.htlcs.iter()
4399                                                 .fold(0, |total, htlc| total + htlc.sender_intended_value)
4400                                         {
4401                                                 return true;
4402                                         } else if payment.htlcs.iter_mut().any(|htlc| {
4403                                                 htlc.timer_ticks += 1;
4404                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
4405                                         }) {
4406                                                 timed_out_mpp_htlcs.extend(payment.htlcs.drain(..)
4407                                                         .map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
4408                                                 return false;
4409                                         }
4410                                 }
4411                                 true
4412                         });
4413
4414                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
4415                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
4416                                 let reason = HTLCFailReason::from_failure_code(23);
4417                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
4418                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
4419                         }
4420
4421                         for (err, counterparty_node_id) in handle_errors.drain(..) {
4422                                 let _ = handle_error!(self, err, counterparty_node_id);
4423                         }
4424
4425                         self.pending_outbound_payments.remove_stale_resolved_payments(&self.pending_events);
4426
4427                         // Technically we don't need to do this here, but if we have holding cell entries in a
4428                         // channel that need freeing, it's better to do that here and block a background task
4429                         // than block the message queueing pipeline.
4430                         if self.check_free_holding_cells() {
4431                                 should_persist = NotifyOption::DoPersist;
4432                         }
4433
4434                         should_persist
4435                 });
4436         }
4437
4438         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
4439         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
4440         /// along the path (including in our own channel on which we received it).
4441         ///
4442         /// Note that in some cases around unclean shutdown, it is possible the payment may have
4443         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
4444         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
4445         /// may have already been failed automatically by LDK if it was nearing its expiration time.
4446         ///
4447         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
4448         /// [`ChannelManager::claim_funds`]), you should still monitor for
4449         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
4450         /// startup during which time claims that were in-progress at shutdown may be replayed.
4451         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
4452                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
4453         }
4454
4455         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
4456         /// reason for the failure.
4457         ///
4458         /// See [`FailureCode`] for valid failure codes.
4459         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
4460                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4461
4462                 let removed_source = self.claimable_payments.lock().unwrap().claimable_payments.remove(payment_hash);
4463                 if let Some(payment) = removed_source {
4464                         for htlc in payment.htlcs {
4465                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
4466                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
4467                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
4468                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
4469                         }
4470                 }
4471         }
4472
4473         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
4474         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
4475                 match failure_code {
4476                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code as u16),
4477                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code as u16),
4478                         FailureCode::IncorrectOrUnknownPaymentDetails => {
4479                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
4480                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
4481                                 HTLCFailReason::reason(failure_code as u16, htlc_msat_height_data)
4482                         }
4483                 }
4484         }
4485
4486         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
4487         /// that we want to return and a channel.
4488         ///
4489         /// This is for failures on the channel on which the HTLC was *received*, not failures
4490         /// forwarding
4491         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> (u16, Vec<u8>) {
4492                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
4493                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
4494                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
4495                 // an inbound SCID alias before the real SCID.
4496                 let scid_pref = if chan.context.should_announce() {
4497                         chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
4498                 } else {
4499                         chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
4500                 };
4501                 if let Some(scid) = scid_pref {
4502                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
4503                 } else {
4504                         (0x4000|10, Vec::new())
4505                 }
4506         }
4507
4508
4509         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
4510         /// that we want to return and a channel.
4511         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>) {
4512                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
4513                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
4514                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
4515                         if desired_err_code == 0x1000 | 20 {
4516                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
4517                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
4518                                 0u16.write(&mut enc).expect("Writes cannot fail");
4519                         }
4520                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
4521                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
4522                         upd.write(&mut enc).expect("Writes cannot fail");
4523                         (desired_err_code, enc.0)
4524                 } else {
4525                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
4526                         // which means we really shouldn't have gotten a payment to be forwarded over this
4527                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
4528                         // PERM|no_such_channel should be fine.
4529                         (0x4000|10, Vec::new())
4530                 }
4531         }
4532
4533         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
4534         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
4535         // be surfaced to the user.
4536         fn fail_holding_cell_htlcs(
4537                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: [u8; 32],
4538                 counterparty_node_id: &PublicKey
4539         ) {
4540                 let (failure_code, onion_failure_data) = {
4541                         let per_peer_state = self.per_peer_state.read().unwrap();
4542                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
4543                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4544                                 let peer_state = &mut *peer_state_lock;
4545                                 match peer_state.channel_by_id.entry(channel_id) {
4546                                         hash_map::Entry::Occupied(chan_entry) => {
4547                                                 self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan_entry.get())
4548                                         },
4549                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
4550                                 }
4551                         } else { (0x4000|10, Vec::new()) }
4552                 };
4553
4554                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
4555                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
4556                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
4557                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
4558                 }
4559         }
4560
4561         /// Fails an HTLC backwards to the sender of it to us.
4562         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
4563         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
4564                 // Ensure that no peer state channel storage lock is held when calling this function.
4565                 // This ensures that future code doesn't introduce a lock-order requirement for
4566                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
4567                 // this function with any `per_peer_state` peer lock acquired would.
4568                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
4569                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
4570                 }
4571
4572                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
4573                 //identify whether we sent it or not based on the (I presume) very different runtime
4574                 //between the branches here. We should make this async and move it into the forward HTLCs
4575                 //timer handling.
4576
4577                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
4578                 // from block_connected which may run during initialization prior to the chain_monitor
4579                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
4580                 match source {
4581                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
4582                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
4583                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
4584                                         &self.pending_events, &self.logger)
4585                                 { self.push_pending_forwards_ev(); }
4586                         },
4587                         HTLCSource::PreviousHopData(HTLCPreviousHopData { ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret, ref phantom_shared_secret, ref outpoint }) => {
4588                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with {:?}", log_bytes!(payment_hash.0), onion_error);
4589                                 let err_packet = onion_error.get_encrypted_failure_packet(incoming_packet_shared_secret, phantom_shared_secret);
4590
4591                                 let mut push_forward_ev = false;
4592                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
4593                                 if forward_htlcs.is_empty() {
4594                                         push_forward_ev = true;
4595                                 }
4596                                 match forward_htlcs.entry(*short_channel_id) {
4597                                         hash_map::Entry::Occupied(mut entry) => {
4598                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet });
4599                                         },
4600                                         hash_map::Entry::Vacant(entry) => {
4601                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }));
4602                                         }
4603                                 }
4604                                 mem::drop(forward_htlcs);
4605                                 if push_forward_ev { self.push_pending_forwards_ev(); }
4606                                 let mut pending_events = self.pending_events.lock().unwrap();
4607                                 pending_events.push_back((events::Event::HTLCHandlingFailed {
4608                                         prev_channel_id: outpoint.to_channel_id(),
4609                                         failed_next_destination: destination,
4610                                 }, None));
4611                         },
4612                 }
4613         }
4614
4615         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
4616         /// [`MessageSendEvent`]s needed to claim the payment.
4617         ///
4618         /// This method is guaranteed to ensure the payment has been claimed but only if the current
4619         /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
4620         /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
4621         /// successful. It will generally be available in the next [`process_pending_events`] call.
4622         ///
4623         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
4624         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
4625         /// event matches your expectation. If you fail to do so and call this method, you may provide
4626         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
4627         ///
4628         /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
4629         /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
4630         /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
4631         /// [`process_pending_events`]: EventsProvider::process_pending_events
4632         /// [`create_inbound_payment`]: Self::create_inbound_payment
4633         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
4634         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
4635                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
4636
4637                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4638
4639                 let mut sources = {
4640                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
4641                         if let Some(payment) = claimable_payments.claimable_payments.remove(&payment_hash) {
4642                                 let mut receiver_node_id = self.our_network_pubkey;
4643                                 for htlc in payment.htlcs.iter() {
4644                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
4645                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
4646                                                         .expect("Failed to get node_id for phantom node recipient");
4647                                                 receiver_node_id = phantom_pubkey;
4648                                                 break;
4649                                         }
4650                                 }
4651
4652                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
4653                                         ClaimingPayment { amount_msat: payment.htlcs.iter().map(|source| source.value).sum(),
4654                                         payment_purpose: payment.purpose, receiver_node_id,
4655                                 });
4656                                 if dup_purpose.is_some() {
4657                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
4658                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
4659                                                 log_bytes!(payment_hash.0));
4660                                 }
4661                                 payment.htlcs
4662                         } else { return; }
4663                 };
4664                 debug_assert!(!sources.is_empty());
4665
4666                 // Just in case one HTLC has been failed between when we generated the `PaymentClaimable`
4667                 // and when we got here we need to check that the amount we're about to claim matches the
4668                 // amount we told the user in the last `PaymentClaimable`. We also do a sanity-check that
4669                 // the MPP parts all have the same `total_msat`.
4670                 let mut claimable_amt_msat = 0;
4671                 let mut prev_total_msat = None;
4672                 let mut expected_amt_msat = None;
4673                 let mut valid_mpp = true;
4674                 let mut errs = Vec::new();
4675                 let per_peer_state = self.per_peer_state.read().unwrap();
4676                 for htlc in sources.iter() {
4677                         if prev_total_msat.is_some() && prev_total_msat != Some(htlc.total_msat) {
4678                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different expected total amounts - this should not be reachable!");
4679                                 debug_assert!(false);
4680                                 valid_mpp = false;
4681                                 break;
4682                         }
4683                         prev_total_msat = Some(htlc.total_msat);
4684
4685                         if expected_amt_msat.is_some() && expected_amt_msat != htlc.total_value_received {
4686                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!");
4687                                 debug_assert!(false);
4688                                 valid_mpp = false;
4689                                 break;
4690                         }
4691                         expected_amt_msat = htlc.total_value_received;
4692                         claimable_amt_msat += htlc.value;
4693                 }
4694                 mem::drop(per_peer_state);
4695                 if sources.is_empty() || expected_amt_msat.is_none() {
4696                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4697                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
4698                         return;
4699                 }
4700                 if claimable_amt_msat != expected_amt_msat.unwrap() {
4701                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4702                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
4703                                 expected_amt_msat.unwrap(), claimable_amt_msat);
4704                         return;
4705                 }
4706                 if valid_mpp {
4707                         for htlc in sources.drain(..) {
4708                                 if let Err((pk, err)) = self.claim_funds_from_hop(
4709                                         htlc.prev_hop, payment_preimage,
4710                                         |_| Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash }))
4711                                 {
4712                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
4713                                                 // We got a temporary failure updating monitor, but will claim the
4714                                                 // HTLC when the monitor updating is restored (or on chain).
4715                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
4716                                         } else { errs.push((pk, err)); }
4717                                 }
4718                         }
4719                 }
4720                 if !valid_mpp {
4721                         for htlc in sources.drain(..) {
4722                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
4723                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
4724                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
4725                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
4726                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
4727                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
4728                         }
4729                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4730                 }
4731
4732                 // Now we can handle any errors which were generated.
4733                 for (counterparty_node_id, err) in errs.drain(..) {
4734                         let res: Result<(), _> = Err(err);
4735                         let _ = handle_error!(self, res, counterparty_node_id);
4736                 }
4737         }
4738
4739         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>) -> Option<MonitorUpdateCompletionAction>>(&self,
4740                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
4741         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
4742                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
4743
4744                 {
4745                         let per_peer_state = self.per_peer_state.read().unwrap();
4746                         let chan_id = prev_hop.outpoint.to_channel_id();
4747                         let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
4748                                 Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
4749                                 None => None
4750                         };
4751
4752                         let peer_state_opt = counterparty_node_id_opt.as_ref().map(
4753                                 |counterparty_node_id| per_peer_state.get(counterparty_node_id)
4754                                         .map(|peer_mutex| peer_mutex.lock().unwrap())
4755                         ).unwrap_or(None);
4756
4757                         if peer_state_opt.is_some() {
4758                                 let mut peer_state_lock = peer_state_opt.unwrap();
4759                                 let peer_state = &mut *peer_state_lock;
4760                                 if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(chan_id) {
4761                                         let counterparty_node_id = chan.get().context.get_counterparty_node_id();
4762                                         let fulfill_res = chan.get_mut().get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger);
4763
4764                                         if let UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } = fulfill_res {
4765                                                 if let Some(action) = completion_action(Some(htlc_value_msat)) {
4766                                                         log_trace!(self.logger, "Tracking monitor update completion action for channel {}: {:?}",
4767                                                                 log_bytes!(chan_id), action);
4768                                                         peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
4769                                                 }
4770                                                 let res = handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
4771                                                         peer_state, per_peer_state, chan);
4772                                                 if let Err(e) = res {
4773                                                         // TODO: This is a *critical* error - we probably updated the outbound edge
4774                                                         // of the HTLC's monitor with a preimage. We should retry this monitor
4775                                                         // update over and over again until morale improves.
4776                                                         log_error!(self.logger, "Failed to update channel monitor with preimage {:?}", payment_preimage);
4777                                                         return Err((counterparty_node_id, e));
4778                                                 }
4779                                         }
4780                                         return Ok(());
4781                                 }
4782                         }
4783                 }
4784                 let preimage_update = ChannelMonitorUpdate {
4785                         update_id: CLOSED_CHANNEL_UPDATE_ID,
4786                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
4787                                 payment_preimage,
4788                         }],
4789                 };
4790                 // We update the ChannelMonitor on the backward link, after
4791                 // receiving an `update_fulfill_htlc` from the forward link.
4792                 let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
4793                 if update_res != ChannelMonitorUpdateStatus::Completed {
4794                         // TODO: This needs to be handled somehow - if we receive a monitor update
4795                         // with a preimage we *must* somehow manage to propagate it to the upstream
4796                         // channel, or we must have an ability to receive the same event and try
4797                         // again on restart.
4798                         log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
4799                                 payment_preimage, update_res);
4800                 }
4801                 // Note that we do process the completion action here. This totally could be a
4802                 // duplicate claim, but we have no way of knowing without interrogating the
4803                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
4804                 // generally always allowed to be duplicative (and it's specifically noted in
4805                 // `PaymentForwarded`).
4806                 self.handle_monitor_update_completion_actions(completion_action(None));
4807                 Ok(())
4808         }
4809
4810         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
4811                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
4812         }
4813
4814         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage, forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, next_channel_id: [u8; 32]) {
4815                 match source {
4816                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
4817                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage, session_priv, path, from_onchain, &self.pending_events, &self.logger);
4818                         },
4819                         HTLCSource::PreviousHopData(hop_data) => {
4820                                 let prev_outpoint = hop_data.outpoint;
4821                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
4822                                         |htlc_claim_value_msat| {
4823                                                 if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
4824                                                         let fee_earned_msat = if let Some(claimed_htlc_value) = htlc_claim_value_msat {
4825                                                                 Some(claimed_htlc_value - forwarded_htlc_value)
4826                                                         } else { None };
4827
4828                                                         Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
4829                                                                 event: events::Event::PaymentForwarded {
4830                                                                         fee_earned_msat,
4831                                                                         claim_from_onchain_tx: from_onchain,
4832                                                                         prev_channel_id: Some(prev_outpoint.to_channel_id()),
4833                                                                         next_channel_id: Some(next_channel_id),
4834                                                                         outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
4835                                                                 },
4836                                                                 downstream_counterparty_and_funding_outpoint: None,
4837                                                         })
4838                                                 } else { None }
4839                                         });
4840                                 if let Err((pk, err)) = res {
4841                                         let result: Result<(), _> = Err(err);
4842                                         let _ = handle_error!(self, result, pk);
4843                                 }
4844                         },
4845                 }
4846         }
4847
4848         /// Gets the node_id held by this ChannelManager
4849         pub fn get_our_node_id(&self) -> PublicKey {
4850                 self.our_network_pubkey.clone()
4851         }
4852
4853         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
4854                 for action in actions.into_iter() {
4855                         match action {
4856                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
4857                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4858                                         if let Some(ClaimingPayment { amount_msat, payment_purpose: purpose, receiver_node_id }) = payment {
4859                                                 self.pending_events.lock().unwrap().push_back((events::Event::PaymentClaimed {
4860                                                         payment_hash, purpose, amount_msat, receiver_node_id: Some(receiver_node_id),
4861                                                 }, None));
4862                                         }
4863                                 },
4864                                 MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
4865                                         event, downstream_counterparty_and_funding_outpoint
4866                                 } => {
4867                                         self.pending_events.lock().unwrap().push_back((event, None));
4868                                         if let Some((node_id, funding_outpoint, blocker)) = downstream_counterparty_and_funding_outpoint {
4869                                                 self.handle_monitor_update_release(node_id, funding_outpoint, Some(blocker));
4870                                         }
4871                                 },
4872                         }
4873                 }
4874         }
4875
4876         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
4877         /// update completion.
4878         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
4879                 channel: &mut Channel<<SP::Target as SignerProvider>::Signer>, raa: Option<msgs::RevokeAndACK>,
4880                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
4881                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
4882                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
4883         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
4884                 log_trace!(self.logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
4885                         log_bytes!(channel.context.channel_id()),
4886                         if raa.is_some() { "an" } else { "no" },
4887                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
4888                         if funding_broadcastable.is_some() { "" } else { "not " },
4889                         if channel_ready.is_some() { "sending" } else { "without" },
4890                         if announcement_sigs.is_some() { "sending" } else { "without" });
4891
4892                 let mut htlc_forwards = None;
4893
4894                 let counterparty_node_id = channel.context.get_counterparty_node_id();
4895                 if !pending_forwards.is_empty() {
4896                         htlc_forwards = Some((channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias()),
4897                                 channel.context.get_funding_txo().unwrap(), channel.context.get_user_id(), pending_forwards));
4898                 }
4899
4900                 if let Some(msg) = channel_ready {
4901                         send_channel_ready!(self, pending_msg_events, channel, msg);
4902                 }
4903                 if let Some(msg) = announcement_sigs {
4904                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
4905                                 node_id: counterparty_node_id,
4906                                 msg,
4907                         });
4908                 }
4909
4910                 macro_rules! handle_cs { () => {
4911                         if let Some(update) = commitment_update {
4912                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
4913                                         node_id: counterparty_node_id,
4914                                         updates: update,
4915                                 });
4916                         }
4917                 } }
4918                 macro_rules! handle_raa { () => {
4919                         if let Some(revoke_and_ack) = raa {
4920                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
4921                                         node_id: counterparty_node_id,
4922                                         msg: revoke_and_ack,
4923                                 });
4924                         }
4925                 } }
4926                 match order {
4927                         RAACommitmentOrder::CommitmentFirst => {
4928                                 handle_cs!();
4929                                 handle_raa!();
4930                         },
4931                         RAACommitmentOrder::RevokeAndACKFirst => {
4932                                 handle_raa!();
4933                                 handle_cs!();
4934                         },
4935                 }
4936
4937                 if let Some(tx) = funding_broadcastable {
4938                         log_info!(self.logger, "Broadcasting funding transaction with txid {}", tx.txid());
4939                         self.tx_broadcaster.broadcast_transactions(&[&tx]);
4940                 }
4941
4942                 {
4943                         let mut pending_events = self.pending_events.lock().unwrap();
4944                         emit_channel_pending_event!(pending_events, channel);
4945                         emit_channel_ready_event!(pending_events, channel);
4946                 }
4947
4948                 htlc_forwards
4949         }
4950
4951         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
4952                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
4953
4954                 let counterparty_node_id = match counterparty_node_id {
4955                         Some(cp_id) => cp_id.clone(),
4956                         None => {
4957                                 // TODO: Once we can rely on the counterparty_node_id from the
4958                                 // monitor event, this and the id_to_peer map should be removed.
4959                                 let id_to_peer = self.id_to_peer.lock().unwrap();
4960                                 match id_to_peer.get(&funding_txo.to_channel_id()) {
4961                                         Some(cp_id) => cp_id.clone(),
4962                                         None => return,
4963                                 }
4964                         }
4965                 };
4966                 let per_peer_state = self.per_peer_state.read().unwrap();
4967                 let mut peer_state_lock;
4968                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
4969                 if peer_state_mutex_opt.is_none() { return }
4970                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4971                 let peer_state = &mut *peer_state_lock;
4972                 let mut channel = {
4973                         match peer_state.channel_by_id.entry(funding_txo.to_channel_id()){
4974                                 hash_map::Entry::Occupied(chan) => chan,
4975                                 hash_map::Entry::Vacant(_) => return,
4976                         }
4977                 };
4978                 let remaining_in_flight =
4979                         if let Some(pending) = peer_state.in_flight_monitor_updates.get_mut(funding_txo) {
4980                                 pending.retain(|upd| upd.update_id > highest_applied_update_id);
4981                                 pending.len()
4982                         } else { 0 };
4983                 log_trace!(self.logger, "ChannelMonitor updated to {}. Current highest is {}. {} pending in-flight updates.",
4984                         highest_applied_update_id, channel.get().context.get_latest_monitor_update_id(),
4985                         remaining_in_flight);
4986                 if !channel.get().is_awaiting_monitor_update() || channel.get().context.get_latest_monitor_update_id() != highest_applied_update_id {
4987                         return;
4988                 }
4989                 handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, channel.get_mut());
4990         }
4991
4992         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
4993         ///
4994         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
4995         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
4996         /// the channel.
4997         ///
4998         /// The `user_channel_id` parameter will be provided back in
4999         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5000         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5001         ///
5002         /// Note that this method will return an error and reject the channel, if it requires support
5003         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
5004         /// used to accept such channels.
5005         ///
5006         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5007         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5008         pub fn accept_inbound_channel(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5009                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
5010         }
5011
5012         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
5013         /// it as confirmed immediately.
5014         ///
5015         /// The `user_channel_id` parameter will be provided back in
5016         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5017         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5018         ///
5019         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
5020         /// and (if the counterparty agrees), enables forwarding of payments immediately.
5021         ///
5022         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
5023         /// transaction and blindly assumes that it will eventually confirm.
5024         ///
5025         /// If it does not confirm before we decide to close the channel, or if the funding transaction
5026         /// does not pay to the correct script the correct amount, *you will lose funds*.
5027         ///
5028         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5029         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5030         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> {
5031                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
5032         }
5033
5034         fn do_accept_inbound_channel(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
5035                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5036
5037                 let peers_without_funded_channels =
5038                         self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 });
5039                 let per_peer_state = self.per_peer_state.read().unwrap();
5040                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5041                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
5042                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5043                 let peer_state = &mut *peer_state_lock;
5044                 let is_only_peer_channel = peer_state.total_channel_count() == 1;
5045                 match peer_state.inbound_v1_channel_by_id.entry(temporary_channel_id.clone()) {
5046                         hash_map::Entry::Occupied(mut channel) => {
5047                                 if !channel.get().is_awaiting_accept() {
5048                                         return Err(APIError::APIMisuseError { err: "The channel isn't currently awaiting to be accepted.".to_owned() });
5049                                 }
5050                                 if accept_0conf {
5051                                         channel.get_mut().set_0conf();
5052                                 } else if channel.get().context.get_channel_type().requires_zero_conf() {
5053                                         let send_msg_err_event = events::MessageSendEvent::HandleError {
5054                                                 node_id: channel.get().context.get_counterparty_node_id(),
5055                                                 action: msgs::ErrorAction::SendErrorMessage{
5056                                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
5057                                                 }
5058                                         };
5059                                         peer_state.pending_msg_events.push(send_msg_err_event);
5060                                         let _ = remove_channel!(self, channel);
5061                                         return Err(APIError::APIMisuseError { err: "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned() });
5062                                 } else {
5063                                         // If this peer already has some channels, a new channel won't increase our number of peers
5064                                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5065                                         // channels per-peer we can accept channels from a peer with existing ones.
5066                                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
5067                                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
5068                                                         node_id: channel.get().context.get_counterparty_node_id(),
5069                                                         action: msgs::ErrorAction::SendErrorMessage{
5070                                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
5071                                                         }
5072                                                 };
5073                                                 peer_state.pending_msg_events.push(send_msg_err_event);
5074                                                 let _ = remove_channel!(self, channel);
5075                                                 return Err(APIError::APIMisuseError { err: "Too many peers with unfunded channels, refusing to accept new ones".to_owned() });
5076                                         }
5077                                 }
5078
5079                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5080                                         node_id: channel.get().context.get_counterparty_node_id(),
5081                                         msg: channel.get_mut().accept_inbound_channel(user_channel_id),
5082                                 });
5083                         }
5084                         hash_map::Entry::Vacant(_) => {
5085                                 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) });
5086                         }
5087                 }
5088                 Ok(())
5089         }
5090
5091         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
5092         /// or 0-conf channels.
5093         ///
5094         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
5095         /// non-0-conf channels we have with the peer.
5096         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
5097         where Filter: Fn(&PeerState<<SP::Target as SignerProvider>::Signer>) -> bool {
5098                 let mut peers_without_funded_channels = 0;
5099                 let best_block_height = self.best_block.read().unwrap().height();
5100                 {
5101                         let peer_state_lock = self.per_peer_state.read().unwrap();
5102                         for (_, peer_mtx) in peer_state_lock.iter() {
5103                                 let peer = peer_mtx.lock().unwrap();
5104                                 if !maybe_count_peer(&*peer) { continue; }
5105                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
5106                                 if num_unfunded_channels == peer.total_channel_count() {
5107                                         peers_without_funded_channels += 1;
5108                                 }
5109                         }
5110                 }
5111                 return peers_without_funded_channels;
5112         }
5113
5114         fn unfunded_channel_count(
5115                 peer: &PeerState<<SP::Target as SignerProvider>::Signer>, best_block_height: u32
5116         ) -> usize {
5117                 let mut num_unfunded_channels = 0;
5118                 for (_, chan) in peer.channel_by_id.iter() {
5119                         // This covers non-zero-conf inbound `Channel`s that we are currently monitoring, but those
5120                         // which have not yet had any confirmations on-chain.
5121                         if !chan.context.is_outbound() && chan.context.minimum_depth().unwrap_or(1) != 0 &&
5122                                 chan.context.get_funding_tx_confirmations(best_block_height) == 0
5123                         {
5124                                 num_unfunded_channels += 1;
5125                         }
5126                 }
5127                 for (_, chan) in peer.inbound_v1_channel_by_id.iter() {
5128                         if chan.context.minimum_depth().unwrap_or(1) != 0 {
5129                                 num_unfunded_channels += 1;
5130                         }
5131                 }
5132                 num_unfunded_channels
5133         }
5134
5135         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
5136                 if msg.chain_hash != self.genesis_hash {
5137                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
5138                 }
5139
5140                 if !self.default_configuration.accept_inbound_channels {
5141                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
5142                 }
5143
5144                 let mut random_bytes = [0u8; 16];
5145                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
5146                 let user_channel_id = u128::from_be_bytes(random_bytes);
5147                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5148
5149                 // Get the number of peers with channels, but without funded ones. We don't care too much
5150                 // about peers that never open a channel, so we filter by peers that have at least one
5151                 // channel, and then limit the number of those with unfunded channels.
5152                 let channeled_peers_without_funding =
5153                         self.peers_without_funded_channels(|node| node.total_channel_count() > 0);
5154
5155                 let per_peer_state = self.per_peer_state.read().unwrap();
5156                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5157                     .ok_or_else(|| {
5158                                 debug_assert!(false);
5159                                 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())
5160                         })?;
5161                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5162                 let peer_state = &mut *peer_state_lock;
5163
5164                 // If this peer already has some channels, a new channel won't increase our number of peers
5165                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5166                 // channels per-peer we can accept channels from a peer with existing ones.
5167                 if peer_state.total_channel_count() == 0 &&
5168                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
5169                         !self.default_configuration.manually_accept_inbound_channels
5170                 {
5171                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
5172                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
5173                                 msg.temporary_channel_id.clone()));
5174                 }
5175
5176                 let best_block_height = self.best_block.read().unwrap().height();
5177                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
5178                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
5179                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
5180                                 msg.temporary_channel_id.clone()));
5181                 }
5182
5183                 let mut channel = match InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5184                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
5185                         &self.default_configuration, best_block_height, &self.logger, outbound_scid_alias)
5186                 {
5187                         Err(e) => {
5188                                 self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
5189                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
5190                         },
5191                         Ok(res) => res
5192                 };
5193                 let channel_id = channel.context.channel_id();
5194                 let channel_exists = peer_state.has_channel(&channel_id);
5195                 if channel_exists {
5196                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
5197                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()))
5198                 } else {
5199                         if !self.default_configuration.manually_accept_inbound_channels {
5200                                 let channel_type = channel.context.get_channel_type();
5201                                 if channel_type.requires_zero_conf() {
5202                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
5203                                 }
5204                                 if channel_type.requires_anchors_zero_fee_htlc_tx() {
5205                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No channels with anchor outputs accepted".to_owned(), msg.temporary_channel_id.clone()));
5206                                 }
5207                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5208                                         node_id: counterparty_node_id.clone(),
5209                                         msg: channel.accept_inbound_channel(user_channel_id),
5210                                 });
5211                         } else {
5212                                 let mut pending_events = self.pending_events.lock().unwrap();
5213                                 pending_events.push_back((events::Event::OpenChannelRequest {
5214                                         temporary_channel_id: msg.temporary_channel_id.clone(),
5215                                         counterparty_node_id: counterparty_node_id.clone(),
5216                                         funding_satoshis: msg.funding_satoshis,
5217                                         push_msat: msg.push_msat,
5218                                         channel_type: channel.context.get_channel_type().clone(),
5219                                 }, None));
5220                         }
5221                         peer_state.inbound_v1_channel_by_id.insert(channel_id, channel);
5222                 }
5223                 Ok(())
5224         }
5225
5226         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
5227                 let (value, output_script, user_id) = {
5228                         let per_peer_state = self.per_peer_state.read().unwrap();
5229                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5230                                 .ok_or_else(|| {
5231                                         debug_assert!(false);
5232                                         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)
5233                                 })?;
5234                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5235                         let peer_state = &mut *peer_state_lock;
5236                         match peer_state.outbound_v1_channel_by_id.entry(msg.temporary_channel_id) {
5237                                 hash_map::Entry::Occupied(mut chan) => {
5238                                         try_v1_outbound_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), chan);
5239                                         (chan.get().context.get_value_satoshis(), chan.get().context.get_funding_redeemscript().to_v0_p2wsh(), chan.get().context.get_user_id())
5240                                 },
5241                                 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))
5242                         }
5243                 };
5244                 let mut pending_events = self.pending_events.lock().unwrap();
5245                 pending_events.push_back((events::Event::FundingGenerationReady {
5246                         temporary_channel_id: msg.temporary_channel_id,
5247                         counterparty_node_id: *counterparty_node_id,
5248                         channel_value_satoshis: value,
5249                         output_script,
5250                         user_channel_id: user_id,
5251                 }, None));
5252                 Ok(())
5253         }
5254
5255         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
5256                 let best_block = *self.best_block.read().unwrap();
5257
5258                 let per_peer_state = self.per_peer_state.read().unwrap();
5259                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5260                         .ok_or_else(|| {
5261                                 debug_assert!(false);
5262                                 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)
5263                         })?;
5264
5265                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5266                 let peer_state = &mut *peer_state_lock;
5267                 let (chan, funding_msg, monitor) =
5268                         match peer_state.inbound_v1_channel_by_id.remove(&msg.temporary_channel_id) {
5269                                 Some(inbound_chan) => {
5270                                         match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &self.logger) {
5271                                                 Ok(res) => res,
5272                                                 Err((mut inbound_chan, err)) => {
5273                                                         // We've already removed this inbound channel from the map in `PeerState`
5274                                                         // above so at this point we just need to clean up any lingering entries
5275                                                         // concerning this channel as it is safe to do so.
5276                                                         update_maps_on_chan_removal!(self, &inbound_chan.context);
5277                                                         let user_id = inbound_chan.context.get_user_id();
5278                                                         let shutdown_res = inbound_chan.context.force_shutdown(false);
5279                                                         return Err(MsgHandleErrInternal::from_finish_shutdown(format!("{}", err),
5280                                                                 msg.temporary_channel_id, user_id, shutdown_res, None));
5281                                                 },
5282                                         }
5283                                 },
5284                                 None => 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))
5285                         };
5286
5287                 match peer_state.channel_by_id.entry(funding_msg.channel_id) {
5288                         hash_map::Entry::Occupied(_) => {
5289                                 Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
5290                         },
5291                         hash_map::Entry::Vacant(e) => {
5292                                 match self.id_to_peer.lock().unwrap().entry(chan.context.channel_id()) {
5293                                         hash_map::Entry::Occupied(_) => {
5294                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(
5295                                                         "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
5296                                                         funding_msg.channel_id))
5297                                         },
5298                                         hash_map::Entry::Vacant(i_e) => {
5299                                                 i_e.insert(chan.context.get_counterparty_node_id());
5300                                         }
5301                                 }
5302
5303                                 // There's no problem signing a counterparty's funding transaction if our monitor
5304                                 // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
5305                                 // accepted payment from yet. We do, however, need to wait to send our channel_ready
5306                                 // until we have persisted our monitor.
5307                                 let new_channel_id = funding_msg.channel_id;
5308                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
5309                                         node_id: counterparty_node_id.clone(),
5310                                         msg: funding_msg,
5311                                 });
5312
5313                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
5314
5315                                 let chan = e.insert(chan);
5316                                 let mut res = handle_new_monitor_update!(self, monitor_res, peer_state_lock, peer_state,
5317                                         per_peer_state, chan, MANUALLY_REMOVING_INITIAL_MONITOR,
5318                                         { peer_state.channel_by_id.remove(&new_channel_id) });
5319
5320                                 // Note that we reply with the new channel_id in error messages if we gave up on the
5321                                 // channel, not the temporary_channel_id. This is compatible with ourselves, but the
5322                                 // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
5323                                 // any messages referencing a previously-closed channel anyway.
5324                                 // We do not propagate the monitor update to the user as it would be for a monitor
5325                                 // that we didn't manage to store (and that we don't care about - we don't respond
5326                                 // with the funding_signed so the channel can never go on chain).
5327                                 if let Err(MsgHandleErrInternal { shutdown_finish: Some((res, _)), .. }) = &mut res {
5328                                         res.0 = None;
5329                                 }
5330                                 res.map(|_| ())
5331                         }
5332                 }
5333         }
5334
5335         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
5336                 let best_block = *self.best_block.read().unwrap();
5337                 let per_peer_state = self.per_peer_state.read().unwrap();
5338                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5339                         .ok_or_else(|| {
5340                                 debug_assert!(false);
5341                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5342                         })?;
5343
5344                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5345                 let peer_state = &mut *peer_state_lock;
5346                 match peer_state.channel_by_id.entry(msg.channel_id) {
5347                         hash_map::Entry::Occupied(mut chan) => {
5348                                 let monitor = try_chan_entry!(self,
5349                                         chan.get_mut().funding_signed(&msg, best_block, &self.signer_provider, &self.logger), chan);
5350                                 let update_res = self.chain_monitor.watch_channel(chan.get().context.get_funding_txo().unwrap(), monitor);
5351                                 let mut res = handle_new_monitor_update!(self, update_res, peer_state_lock, peer_state, per_peer_state, chan, INITIAL_MONITOR);
5352                                 if let Err(MsgHandleErrInternal { ref mut shutdown_finish, .. }) = res {
5353                                         // We weren't able to watch the channel to begin with, so no updates should be made on
5354                                         // it. Previously, full_stack_target found an (unreachable) panic when the
5355                                         // monitor update contained within `shutdown_finish` was applied.
5356                                         if let Some((ref mut shutdown_finish, _)) = shutdown_finish {
5357                                                 shutdown_finish.0.take();
5358                                         }
5359                                 }
5360                                 res.map(|_| ())
5361                         },
5362                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
5363                 }
5364         }
5365
5366         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
5367                 let per_peer_state = self.per_peer_state.read().unwrap();
5368                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5369                         .ok_or_else(|| {
5370                                 debug_assert!(false);
5371                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5372                         })?;
5373                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5374                 let peer_state = &mut *peer_state_lock;
5375                 match peer_state.channel_by_id.entry(msg.channel_id) {
5376                         hash_map::Entry::Occupied(mut chan) => {
5377                                 let announcement_sigs_opt = try_chan_entry!(self, chan.get_mut().channel_ready(&msg, &self.node_signer,
5378                                         self.genesis_hash.clone(), &self.default_configuration, &self.best_block.read().unwrap(), &self.logger), chan);
5379                                 if let Some(announcement_sigs) = announcement_sigs_opt {
5380                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", log_bytes!(chan.get().context.channel_id()));
5381                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5382                                                 node_id: counterparty_node_id.clone(),
5383                                                 msg: announcement_sigs,
5384                                         });
5385                                 } else if chan.get().context.is_usable() {
5386                                         // If we're sending an announcement_signatures, we'll send the (public)
5387                                         // channel_update after sending a channel_announcement when we receive our
5388                                         // counterparty's announcement_signatures. Thus, we only bother to send a
5389                                         // channel_update here if the channel is not public, i.e. we're not sending an
5390                                         // announcement_signatures.
5391                                         log_trace!(self.logger, "Sending private initial channel_update for our counterparty on channel {}", log_bytes!(chan.get().context.channel_id()));
5392                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan.get()) {
5393                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
5394                                                         node_id: counterparty_node_id.clone(),
5395                                                         msg,
5396                                                 });
5397                                         }
5398                                 }
5399
5400                                 {
5401                                         let mut pending_events = self.pending_events.lock().unwrap();
5402                                         emit_channel_ready_event!(pending_events, chan.get_mut());
5403                                 }
5404
5405                                 Ok(())
5406                         },
5407                         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))
5408                 }
5409         }
5410
5411         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
5412                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)>;
5413                 let result: Result<(), _> = loop {
5414                         let per_peer_state = self.per_peer_state.read().unwrap();
5415                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5416                                 .ok_or_else(|| {
5417                                         debug_assert!(false);
5418                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5419                                 })?;
5420                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5421                         let peer_state = &mut *peer_state_lock;
5422                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
5423                                 hash_map::Entry::Occupied(mut chan_entry) => {
5424
5425                                         if !chan_entry.get().received_shutdown() {
5426                                                 log_info!(self.logger, "Received a shutdown message from our counterparty for channel {}{}.",
5427                                                         log_bytes!(msg.channel_id),
5428                                                         if chan_entry.get().sent_shutdown() { " after we initiated shutdown" } else { "" });
5429                                         }
5430
5431                                         let funding_txo_opt = chan_entry.get().context.get_funding_txo();
5432                                         let (shutdown, monitor_update_opt, htlcs) = try_chan_entry!(self,
5433                                                 chan_entry.get_mut().shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_entry);
5434                                         dropped_htlcs = htlcs;
5435
5436                                         if let Some(msg) = shutdown {
5437                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
5438                                                 // here as we don't need the monitor update to complete until we send a
5439                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
5440                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
5441                                                         node_id: *counterparty_node_id,
5442                                                         msg,
5443                                                 });
5444                                         }
5445
5446                                         // Update the monitor with the shutdown script if necessary.
5447                                         if let Some(monitor_update) = monitor_update_opt {
5448                                                 break handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
5449                                                         peer_state_lock, peer_state, per_peer_state, chan_entry).map(|_| ());
5450                                         }
5451                                         break Ok(());
5452                                 },
5453                                 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))
5454                         }
5455                 };
5456                 for htlc_source in dropped_htlcs.drain(..) {
5457                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
5458                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
5459                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
5460                 }
5461
5462                 result
5463         }
5464
5465         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
5466                 let per_peer_state = self.per_peer_state.read().unwrap();
5467                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5468                         .ok_or_else(|| {
5469                                 debug_assert!(false);
5470                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5471                         })?;
5472                 let (tx, chan_option) = {
5473                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5474                         let peer_state = &mut *peer_state_lock;
5475                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
5476                                 hash_map::Entry::Occupied(mut chan_entry) => {
5477                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&self.fee_estimator, &msg), chan_entry);
5478                                         if let Some(msg) = closing_signed {
5479                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
5480                                                         node_id: counterparty_node_id.clone(),
5481                                                         msg,
5482                                                 });
5483                                         }
5484                                         if tx.is_some() {
5485                                                 // We're done with this channel, we've got a signed closing transaction and
5486                                                 // will send the closing_signed back to the remote peer upon return. This
5487                                                 // also implies there are no pending HTLCs left on the channel, so we can
5488                                                 // fully delete it from tracking (the channel monitor is still around to
5489                                                 // watch for old state broadcasts)!
5490                                                 (tx, Some(remove_channel!(self, chan_entry)))
5491                                         } else { (tx, None) }
5492                                 },
5493                                 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))
5494                         }
5495                 };
5496                 if let Some(broadcast_tx) = tx {
5497                         log_info!(self.logger, "Broadcasting {}", log_tx!(broadcast_tx));
5498                         self.tx_broadcaster.broadcast_transactions(&[&broadcast_tx]);
5499                 }
5500                 if let Some(chan) = chan_option {
5501                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
5502                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5503                                 let peer_state = &mut *peer_state_lock;
5504                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
5505                                         msg: update
5506                                 });
5507                         }
5508                         self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
5509                 }
5510                 Ok(())
5511         }
5512
5513         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
5514                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
5515                 //determine the state of the payment based on our response/if we forward anything/the time
5516                 //we take to respond. We should take care to avoid allowing such an attack.
5517                 //
5518                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
5519                 //us repeatedly garbled in different ways, and compare our error messages, which are
5520                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
5521                 //but we should prevent it anyway.
5522
5523                 let decoded_hop_res = self.decode_update_add_htlc_onion(msg);
5524                 let per_peer_state = self.per_peer_state.read().unwrap();
5525                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5526                         .ok_or_else(|| {
5527                                 debug_assert!(false);
5528                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5529                         })?;
5530                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5531                 let peer_state = &mut *peer_state_lock;
5532                 match peer_state.channel_by_id.entry(msg.channel_id) {
5533                         hash_map::Entry::Occupied(mut chan) => {
5534
5535                                 let pending_forward_info = match decoded_hop_res {
5536                                         Ok((next_hop, shared_secret, next_packet_pk_opt)) =>
5537                                                 self.construct_pending_htlc_status(msg, shared_secret, next_hop,
5538                                                         chan.get().context.config().accept_underpaying_htlcs, next_packet_pk_opt),
5539                                         Err(e) => PendingHTLCStatus::Fail(e)
5540                                 };
5541                                 let create_pending_htlc_status = |chan: &Channel<<SP::Target as SignerProvider>::Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
5542                                         // If the update_add is completely bogus, the call will Err and we will close,
5543                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
5544                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
5545                                         match pending_forward_info {
5546                                                 PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
5547                                                         let reason = if (error_code & 0x1000) != 0 {
5548                                                                 let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
5549                                                                 HTLCFailReason::reason(real_code, error_data)
5550                                                         } else {
5551                                                                 HTLCFailReason::from_failure_code(error_code)
5552                                                         }.get_encrypted_failure_packet(incoming_shared_secret, &None);
5553                                                         let msg = msgs::UpdateFailHTLC {
5554                                                                 channel_id: msg.channel_id,
5555                                                                 htlc_id: msg.htlc_id,
5556                                                                 reason
5557                                                         };
5558                                                         PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
5559                                                 },
5560                                                 _ => pending_forward_info
5561                                         }
5562                                 };
5563                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.fee_estimator, &self.logger), chan);
5564                         },
5565                         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))
5566                 }
5567                 Ok(())
5568         }
5569
5570         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
5571                 let (htlc_source, forwarded_htlc_value) = {
5572                         let per_peer_state = self.per_peer_state.read().unwrap();
5573                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5574                                 .ok_or_else(|| {
5575                                         debug_assert!(false);
5576                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5577                                 })?;
5578                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5579                         let peer_state = &mut *peer_state_lock;
5580                         match peer_state.channel_by_id.entry(msg.channel_id) {
5581                                 hash_map::Entry::Occupied(mut chan) => {
5582                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), chan)
5583                                 },
5584                                 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))
5585                         }
5586                 };
5587                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, msg.channel_id);
5588                 Ok(())
5589         }
5590
5591         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
5592                 let per_peer_state = self.per_peer_state.read().unwrap();
5593                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5594                         .ok_or_else(|| {
5595                                 debug_assert!(false);
5596                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5597                         })?;
5598                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5599                 let peer_state = &mut *peer_state_lock;
5600                 match peer_state.channel_by_id.entry(msg.channel_id) {
5601                         hash_map::Entry::Occupied(mut chan) => {
5602                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan);
5603                         },
5604                         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))
5605                 }
5606                 Ok(())
5607         }
5608
5609         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
5610                 let per_peer_state = self.per_peer_state.read().unwrap();
5611                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5612                         .ok_or_else(|| {
5613                                 debug_assert!(false);
5614                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5615                         })?;
5616                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5617                 let peer_state = &mut *peer_state_lock;
5618                 match peer_state.channel_by_id.entry(msg.channel_id) {
5619                         hash_map::Entry::Occupied(mut chan) => {
5620                                 if (msg.failure_code & 0x8000) == 0 {
5621                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
5622                                         try_chan_entry!(self, Err(chan_err), chan);
5623                                 }
5624                                 try_chan_entry!(self, chan.get_mut().update_fail_malformed_htlc(&msg, HTLCFailReason::reason(msg.failure_code, msg.sha256_of_onion.to_vec())), chan);
5625                                 Ok(())
5626                         },
5627                         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))
5628                 }
5629         }
5630
5631         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
5632                 let per_peer_state = self.per_peer_state.read().unwrap();
5633                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5634                         .ok_or_else(|| {
5635                                 debug_assert!(false);
5636                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5637                         })?;
5638                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5639                 let peer_state = &mut *peer_state_lock;
5640                 match peer_state.channel_by_id.entry(msg.channel_id) {
5641                         hash_map::Entry::Occupied(mut chan) => {
5642                                 let funding_txo = chan.get().context.get_funding_txo();
5643                                 let monitor_update_opt = try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &self.logger), chan);
5644                                 if let Some(monitor_update) = monitor_update_opt {
5645                                         handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update, peer_state_lock,
5646                                                 peer_state, per_peer_state, chan).map(|_| ())
5647                                 } else { Ok(()) }
5648                         },
5649                         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))
5650                 }
5651         }
5652
5653         #[inline]
5654         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
5655                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
5656                         let mut push_forward_event = false;
5657                         let mut new_intercept_events = VecDeque::new();
5658                         let mut failed_intercept_forwards = Vec::new();
5659                         if !pending_forwards.is_empty() {
5660                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
5661                                         let scid = match forward_info.routing {
5662                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
5663                                                 PendingHTLCRouting::Receive { .. } => 0,
5664                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
5665                                         };
5666                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
5667                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
5668
5669                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
5670                                         let forward_htlcs_empty = forward_htlcs.is_empty();
5671                                         match forward_htlcs.entry(scid) {
5672                                                 hash_map::Entry::Occupied(mut entry) => {
5673                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
5674                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
5675                                                 },
5676                                                 hash_map::Entry::Vacant(entry) => {
5677                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
5678                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.genesis_hash)
5679                                                         {
5680                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).into_inner());
5681                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
5682                                                                 match pending_intercepts.entry(intercept_id) {
5683                                                                         hash_map::Entry::Vacant(entry) => {
5684                                                                                 new_intercept_events.push_back((events::Event::HTLCIntercepted {
5685                                                                                         requested_next_hop_scid: scid,
5686                                                                                         payment_hash: forward_info.payment_hash,
5687                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
5688                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
5689                                                                                         intercept_id
5690                                                                                 }, None));
5691                                                                                 entry.insert(PendingAddHTLCInfo {
5692                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
5693                                                                         },
5694                                                                         hash_map::Entry::Occupied(_) => {
5695                                                                                 log_info!(self.logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
5696                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
5697                                                                                         short_channel_id: prev_short_channel_id,
5698                                                                                         outpoint: prev_funding_outpoint,
5699                                                                                         htlc_id: prev_htlc_id,
5700                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
5701                                                                                         phantom_shared_secret: None,
5702                                                                                 });
5703
5704                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
5705                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
5706                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
5707                                                                                 ));
5708                                                                         }
5709                                                                 }
5710                                                         } else {
5711                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
5712                                                                 // payments are being processed.
5713                                                                 if forward_htlcs_empty {
5714                                                                         push_forward_event = true;
5715                                                                 }
5716                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
5717                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
5718                                                         }
5719                                                 }
5720                                         }
5721                                 }
5722                         }
5723
5724                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
5725                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
5726                         }
5727
5728                         if !new_intercept_events.is_empty() {
5729                                 let mut events = self.pending_events.lock().unwrap();
5730                                 events.append(&mut new_intercept_events);
5731                         }
5732                         if push_forward_event { self.push_pending_forwards_ev() }
5733                 }
5734         }
5735
5736         // We only want to push a PendingHTLCsForwardable event if no others are queued.
5737         fn push_pending_forwards_ev(&self) {
5738                 let mut pending_events = self.pending_events.lock().unwrap();
5739                 let forward_ev_exists = pending_events.iter()
5740                         .find(|(ev, _)| if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false })
5741                         .is_some();
5742                 if !forward_ev_exists {
5743                         pending_events.push_back((events::Event::PendingHTLCsForwardable {
5744                                 time_forwardable:
5745                                         Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
5746                         }, None));
5747                 }
5748         }
5749
5750         /// Checks whether [`ChannelMonitorUpdate`]s generated by the receipt of a remote
5751         /// [`msgs::RevokeAndACK`] should be held for the given channel until some other event
5752         /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of
5753         /// the [`ChannelMonitorUpdate`] in question.
5754         fn raa_monitor_updates_held(&self,
5755                 actions_blocking_raa_monitor_updates: &BTreeMap<[u8; 32], Vec<RAAMonitorUpdateBlockingAction>>,
5756                 channel_funding_outpoint: OutPoint, counterparty_node_id: PublicKey
5757         ) -> bool {
5758                 actions_blocking_raa_monitor_updates
5759                         .get(&channel_funding_outpoint.to_channel_id()).map(|v| !v.is_empty()).unwrap_or(false)
5760                 || self.pending_events.lock().unwrap().iter().any(|(_, action)| {
5761                         action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5762                                 channel_funding_outpoint,
5763                                 counterparty_node_id,
5764                         })
5765                 })
5766         }
5767
5768         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
5769                 let (htlcs_to_fail, res) = {
5770                         let per_peer_state = self.per_peer_state.read().unwrap();
5771                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
5772                                 .ok_or_else(|| {
5773                                         debug_assert!(false);
5774                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5775                                 }).map(|mtx| mtx.lock().unwrap())?;
5776                         let peer_state = &mut *peer_state_lock;
5777                         match peer_state.channel_by_id.entry(msg.channel_id) {
5778                                 hash_map::Entry::Occupied(mut chan) => {
5779                                         let funding_txo = chan.get().context.get_funding_txo();
5780                                         let (htlcs_to_fail, monitor_update_opt) = try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &self.fee_estimator, &self.logger), chan);
5781                                         let res = if let Some(monitor_update) = monitor_update_opt {
5782                                                 handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
5783                                                         peer_state_lock, peer_state, per_peer_state, chan).map(|_| ())
5784                                         } else { Ok(()) };
5785                                         (htlcs_to_fail, res)
5786                                 },
5787                                 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))
5788                         }
5789                 };
5790                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
5791                 res
5792         }
5793
5794         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
5795                 let per_peer_state = self.per_peer_state.read().unwrap();
5796                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5797                         .ok_or_else(|| {
5798                                 debug_assert!(false);
5799                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5800                         })?;
5801                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5802                 let peer_state = &mut *peer_state_lock;
5803                 match peer_state.channel_by_id.entry(msg.channel_id) {
5804                         hash_map::Entry::Occupied(mut chan) => {
5805                                 try_chan_entry!(self, chan.get_mut().update_fee(&self.fee_estimator, &msg, &self.logger), chan);
5806                         },
5807                         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))
5808                 }
5809                 Ok(())
5810         }
5811
5812         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
5813                 let per_peer_state = self.per_peer_state.read().unwrap();
5814                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5815                         .ok_or_else(|| {
5816                                 debug_assert!(false);
5817                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5818                         })?;
5819                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5820                 let peer_state = &mut *peer_state_lock;
5821                 match peer_state.channel_by_id.entry(msg.channel_id) {
5822                         hash_map::Entry::Occupied(mut chan) => {
5823                                 if !chan.get().context.is_usable() {
5824                                         return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
5825                                 }
5826
5827                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
5828                                         msg: try_chan_entry!(self, chan.get_mut().announcement_signatures(
5829                                                 &self.node_signer, self.genesis_hash.clone(), self.best_block.read().unwrap().height(),
5830                                                 msg, &self.default_configuration
5831                                         ), chan),
5832                                         // Note that announcement_signatures fails if the channel cannot be announced,
5833                                         // so get_channel_update_for_broadcast will never fail by the time we get here.
5834                                         update_msg: Some(self.get_channel_update_for_broadcast(chan.get()).unwrap()),
5835                                 });
5836                         },
5837                         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))
5838                 }
5839                 Ok(())
5840         }
5841
5842         /// Returns ShouldPersist if anything changed, otherwise either SkipPersist or an Err.
5843         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
5844                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
5845                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
5846                         None => {
5847                                 // It's not a local channel
5848                                 return Ok(NotifyOption::SkipPersist)
5849                         }
5850                 };
5851                 let per_peer_state = self.per_peer_state.read().unwrap();
5852                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
5853                 if peer_state_mutex_opt.is_none() {
5854                         return Ok(NotifyOption::SkipPersist)
5855                 }
5856                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
5857                 let peer_state = &mut *peer_state_lock;
5858                 match peer_state.channel_by_id.entry(chan_id) {
5859                         hash_map::Entry::Occupied(mut chan) => {
5860                                 if chan.get().context.get_counterparty_node_id() != *counterparty_node_id {
5861                                         if chan.get().context.should_announce() {
5862                                                 // If the announcement is about a channel of ours which is public, some
5863                                                 // other peer may simply be forwarding all its gossip to us. Don't provide
5864                                                 // a scary-looking error message and return Ok instead.
5865                                                 return Ok(NotifyOption::SkipPersist);
5866                                         }
5867                                         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));
5868                                 }
5869                                 let were_node_one = self.get_our_node_id().serialize()[..] < chan.get().context.get_counterparty_node_id().serialize()[..];
5870                                 let msg_from_node_one = msg.contents.flags & 1 == 0;
5871                                 if were_node_one == msg_from_node_one {
5872                                         return Ok(NotifyOption::SkipPersist);
5873                                 } else {
5874                                         log_debug!(self.logger, "Received channel_update for channel {}.", log_bytes!(chan_id));
5875                                         try_chan_entry!(self, chan.get_mut().channel_update(&msg), chan);
5876                                 }
5877                         },
5878                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersist)
5879                 }
5880                 Ok(NotifyOption::DoPersist)
5881         }
5882
5883         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
5884                 let htlc_forwards;
5885                 let need_lnd_workaround = {
5886                         let per_peer_state = self.per_peer_state.read().unwrap();
5887
5888                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5889                                 .ok_or_else(|| {
5890                                         debug_assert!(false);
5891                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5892                                 })?;
5893                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5894                         let peer_state = &mut *peer_state_lock;
5895                         match peer_state.channel_by_id.entry(msg.channel_id) {
5896                                 hash_map::Entry::Occupied(mut chan) => {
5897                                         // Currently, we expect all holding cell update_adds to be dropped on peer
5898                                         // disconnect, so Channel's reestablish will never hand us any holding cell
5899                                         // freed HTLCs to fail backwards. If in the future we no longer drop pending
5900                                         // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
5901                                         let responses = try_chan_entry!(self, chan.get_mut().channel_reestablish(
5902                                                 msg, &self.logger, &self.node_signer, self.genesis_hash,
5903                                                 &self.default_configuration, &*self.best_block.read().unwrap()), chan);
5904                                         let mut channel_update = None;
5905                                         if let Some(msg) = responses.shutdown_msg {
5906                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
5907                                                         node_id: counterparty_node_id.clone(),
5908                                                         msg,
5909                                                 });
5910                                         } else if chan.get().context.is_usable() {
5911                                                 // If the channel is in a usable state (ie the channel is not being shut
5912                                                 // down), send a unicast channel_update to our counterparty to make sure
5913                                                 // they have the latest channel parameters.
5914                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan.get()) {
5915                                                         channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
5916                                                                 node_id: chan.get().context.get_counterparty_node_id(),
5917                                                                 msg,
5918                                                         });
5919                                                 }
5920                                         }
5921                                         let need_lnd_workaround = chan.get_mut().context.workaround_lnd_bug_4006.take();
5922                                         htlc_forwards = self.handle_channel_resumption(
5923                                                 &mut peer_state.pending_msg_events, chan.get_mut(), responses.raa, responses.commitment_update, responses.order,
5924                                                 Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
5925                                         if let Some(upd) = channel_update {
5926                                                 peer_state.pending_msg_events.push(upd);
5927                                         }
5928                                         need_lnd_workaround
5929                                 },
5930                                 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))
5931                         }
5932                 };
5933
5934                 if let Some(forwards) = htlc_forwards {
5935                         self.forward_htlcs(&mut [forwards][..]);
5936                 }
5937
5938                 if let Some(channel_ready_msg) = need_lnd_workaround {
5939                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
5940                 }
5941                 Ok(())
5942         }
5943
5944         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
5945         fn process_pending_monitor_events(&self) -> bool {
5946                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5947
5948                 let mut failed_channels = Vec::new();
5949                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
5950                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
5951                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
5952                         for monitor_event in monitor_events.drain(..) {
5953                                 match monitor_event {
5954                                         MonitorEvent::HTLCEvent(htlc_update) => {
5955                                                 if let Some(preimage) = htlc_update.payment_preimage {
5956                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
5957                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, funding_outpoint.to_channel_id());
5958                                                 } else {
5959                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
5960                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
5961                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
5962                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
5963                                                 }
5964                                         },
5965                                         MonitorEvent::CommitmentTxConfirmed(funding_outpoint) |
5966                                         MonitorEvent::UpdateFailed(funding_outpoint) => {
5967                                                 let counterparty_node_id_opt = match counterparty_node_id {
5968                                                         Some(cp_id) => Some(cp_id),
5969                                                         None => {
5970                                                                 // TODO: Once we can rely on the counterparty_node_id from the
5971                                                                 // monitor event, this and the id_to_peer map should be removed.
5972                                                                 let id_to_peer = self.id_to_peer.lock().unwrap();
5973                                                                 id_to_peer.get(&funding_outpoint.to_channel_id()).cloned()
5974                                                         }
5975                                                 };
5976                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
5977                                                         let per_peer_state = self.per_peer_state.read().unwrap();
5978                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
5979                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5980                                                                 let peer_state = &mut *peer_state_lock;
5981                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
5982                                                                 if let hash_map::Entry::Occupied(chan_entry) = peer_state.channel_by_id.entry(funding_outpoint.to_channel_id()) {
5983                                                                         let mut chan = remove_channel!(self, chan_entry);
5984                                                                         failed_channels.push(chan.context.force_shutdown(false));
5985                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
5986                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
5987                                                                                         msg: update
5988                                                                                 });
5989                                                                         }
5990                                                                         let reason = if let MonitorEvent::UpdateFailed(_) = monitor_event {
5991                                                                                 ClosureReason::ProcessingError { err: "Failed to persist ChannelMonitor update during chain sync".to_string() }
5992                                                                         } else {
5993                                                                                 ClosureReason::CommitmentTxConfirmed
5994                                                                         };
5995                                                                         self.issue_channel_close_events(&chan.context, reason);
5996                                                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
5997                                                                                 node_id: chan.context.get_counterparty_node_id(),
5998                                                                                 action: msgs::ErrorAction::SendErrorMessage {
5999                                                                                         msg: msgs::ErrorMessage { channel_id: chan.context.channel_id(), data: "Channel force-closed".to_owned() }
6000                                                                                 },
6001                                                                         });
6002                                                                 }
6003                                                         }
6004                                                 }
6005                                         },
6006                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
6007                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id, counterparty_node_id.as_ref());
6008                                         },
6009                                 }
6010                         }
6011                 }
6012
6013                 for failure in failed_channels.drain(..) {
6014                         self.finish_force_close_channel(failure);
6015                 }
6016
6017                 has_pending_monitor_events
6018         }
6019
6020         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
6021         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
6022         /// update events as a separate process method here.
6023         #[cfg(fuzzing)]
6024         pub fn process_monitor_events(&self) {
6025                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6026                 self.process_pending_monitor_events();
6027         }
6028
6029         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
6030         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
6031         /// update was applied.
6032         fn check_free_holding_cells(&self) -> bool {
6033                 let mut has_monitor_update = false;
6034                 let mut failed_htlcs = Vec::new();
6035                 let mut handle_errors = Vec::new();
6036
6037                 // Walk our list of channels and find any that need to update. Note that when we do find an
6038                 // update, if it includes actions that must be taken afterwards, we have to drop the
6039                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
6040                 // manage to go through all our peers without finding a single channel to update.
6041                 'peer_loop: loop {
6042                         let per_peer_state = self.per_peer_state.read().unwrap();
6043                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6044                                 'chan_loop: loop {
6045                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6046                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
6047                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut() {
6048                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
6049                                                 let funding_txo = chan.context.get_funding_txo();
6050                                                 let (monitor_opt, holding_cell_failed_htlcs) =
6051                                                         chan.maybe_free_holding_cell_htlcs(&self.fee_estimator, &self.logger);
6052                                                 if !holding_cell_failed_htlcs.is_empty() {
6053                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
6054                                                 }
6055                                                 if let Some(monitor_update) = monitor_opt {
6056                                                         has_monitor_update = true;
6057
6058                                                         let channel_id: [u8; 32] = *channel_id;
6059                                                         let res = handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
6060                                                                 peer_state_lock, peer_state, per_peer_state, chan, MANUALLY_REMOVING,
6061                                                                 peer_state.channel_by_id.remove(&channel_id));
6062                                                         if res.is_err() {
6063                                                                 handle_errors.push((counterparty_node_id, res));
6064                                                         }
6065                                                         continue 'peer_loop;
6066                                                 }
6067                                         }
6068                                         break 'chan_loop;
6069                                 }
6070                         }
6071                         break 'peer_loop;
6072                 }
6073
6074                 let has_update = has_monitor_update || !failed_htlcs.is_empty() || !handle_errors.is_empty();
6075                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
6076                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
6077                 }
6078
6079                 for (counterparty_node_id, err) in handle_errors.drain(..) {
6080                         let _ = handle_error!(self, err, counterparty_node_id);
6081                 }
6082
6083                 has_update
6084         }
6085
6086         /// Check whether any channels have finished removing all pending updates after a shutdown
6087         /// exchange and can now send a closing_signed.
6088         /// Returns whether any closing_signed messages were generated.
6089         fn maybe_generate_initial_closing_signed(&self) -> bool {
6090                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
6091                 let mut has_update = false;
6092                 {
6093                         let per_peer_state = self.per_peer_state.read().unwrap();
6094
6095                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6096                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6097                                 let peer_state = &mut *peer_state_lock;
6098                                 let pending_msg_events = &mut peer_state.pending_msg_events;
6099                                 peer_state.channel_by_id.retain(|channel_id, chan| {
6100                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &self.logger) {
6101                                                 Ok((msg_opt, tx_opt)) => {
6102                                                         if let Some(msg) = msg_opt {
6103                                                                 has_update = true;
6104                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
6105                                                                         node_id: chan.context.get_counterparty_node_id(), msg,
6106                                                                 });
6107                                                         }
6108                                                         if let Some(tx) = tx_opt {
6109                                                                 // We're done with this channel. We got a closing_signed and sent back
6110                                                                 // a closing_signed with a closing transaction to broadcast.
6111                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6112                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6113                                                                                 msg: update
6114                                                                         });
6115                                                                 }
6116
6117                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
6118
6119                                                                 log_info!(self.logger, "Broadcasting {}", log_tx!(tx));
6120                                                                 self.tx_broadcaster.broadcast_transactions(&[&tx]);
6121                                                                 update_maps_on_chan_removal!(self, &chan.context);
6122                                                                 false
6123                                                         } else { true }
6124                                                 },
6125                                                 Err(e) => {
6126                                                         has_update = true;
6127                                                         let (close_channel, res) = convert_chan_err!(self, e, chan, channel_id);
6128                                                         handle_errors.push((chan.context.get_counterparty_node_id(), Err(res)));
6129                                                         !close_channel
6130                                                 }
6131                                         }
6132                                 });
6133                         }
6134                 }
6135
6136                 for (counterparty_node_id, err) in handle_errors.drain(..) {
6137                         let _ = handle_error!(self, err, counterparty_node_id);
6138                 }
6139
6140                 has_update
6141         }
6142
6143         /// Handle a list of channel failures during a block_connected or block_disconnected call,
6144         /// pushing the channel monitor update (if any) to the background events queue and removing the
6145         /// Channel object.
6146         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
6147                 for mut failure in failed_channels.drain(..) {
6148                         // Either a commitment transactions has been confirmed on-chain or
6149                         // Channel::block_disconnected detected that the funding transaction has been
6150                         // reorganized out of the main chain.
6151                         // We cannot broadcast our latest local state via monitor update (as
6152                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
6153                         // so we track the update internally and handle it when the user next calls
6154                         // timer_tick_occurred, guaranteeing we're running normally.
6155                         if let Some((counterparty_node_id, funding_txo, update)) = failure.0.take() {
6156                                 assert_eq!(update.updates.len(), 1);
6157                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
6158                                         assert!(should_broadcast);
6159                                 } else { unreachable!(); }
6160                                 self.pending_background_events.lock().unwrap().push(
6161                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
6162                                                 counterparty_node_id, funding_txo, update
6163                                         });
6164                         }
6165                         self.finish_force_close_channel(failure);
6166                 }
6167         }
6168
6169         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
6170         /// to pay us.
6171         ///
6172         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
6173         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
6174         ///
6175         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
6176         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
6177         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
6178         /// passed directly to [`claim_funds`].
6179         ///
6180         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
6181         ///
6182         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
6183         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
6184         ///
6185         /// # Note
6186         ///
6187         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
6188         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
6189         ///
6190         /// Errors if `min_value_msat` is greater than total bitcoin supply.
6191         ///
6192         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
6193         /// on versions of LDK prior to 0.0.114.
6194         ///
6195         /// [`claim_funds`]: Self::claim_funds
6196         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
6197         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
6198         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
6199         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
6200         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
6201         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
6202                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
6203                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
6204                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
6205                         min_final_cltv_expiry_delta)
6206         }
6207
6208         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
6209         /// stored external to LDK.
6210         ///
6211         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
6212         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
6213         /// the `min_value_msat` provided here, if one is provided.
6214         ///
6215         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
6216         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
6217         /// payments.
6218         ///
6219         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
6220         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
6221         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
6222         /// sender "proof-of-payment" unless they have paid the required amount.
6223         ///
6224         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
6225         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
6226         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
6227         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
6228         /// invoices when no timeout is set.
6229         ///
6230         /// Note that we use block header time to time-out pending inbound payments (with some margin
6231         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
6232         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
6233         /// If you need exact expiry semantics, you should enforce them upon receipt of
6234         /// [`PaymentClaimable`].
6235         ///
6236         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
6237         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
6238         ///
6239         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
6240         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
6241         ///
6242         /// # Note
6243         ///
6244         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
6245         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
6246         ///
6247         /// Errors if `min_value_msat` is greater than total bitcoin supply.
6248         ///
6249         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
6250         /// on versions of LDK prior to 0.0.114.
6251         ///
6252         /// [`create_inbound_payment`]: Self::create_inbound_payment
6253         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
6254         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
6255                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
6256                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
6257                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
6258                         min_final_cltv_expiry)
6259         }
6260
6261         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
6262         /// previously returned from [`create_inbound_payment`].
6263         ///
6264         /// [`create_inbound_payment`]: Self::create_inbound_payment
6265         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
6266                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
6267         }
6268
6269         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
6270         /// are used when constructing the phantom invoice's route hints.
6271         ///
6272         /// [phantom node payments]: crate::sign::PhantomKeysManager
6273         pub fn get_phantom_scid(&self) -> u64 {
6274                 let best_block_height = self.best_block.read().unwrap().height();
6275                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
6276                 loop {
6277                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
6278                         // Ensure the generated scid doesn't conflict with a real channel.
6279                         match short_to_chan_info.get(&scid_candidate) {
6280                                 Some(_) => continue,
6281                                 None => return scid_candidate
6282                         }
6283                 }
6284         }
6285
6286         /// Gets route hints for use in receiving [phantom node payments].
6287         ///
6288         /// [phantom node payments]: crate::sign::PhantomKeysManager
6289         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
6290                 PhantomRouteHints {
6291                         channels: self.list_usable_channels(),
6292                         phantom_scid: self.get_phantom_scid(),
6293                         real_node_pubkey: self.get_our_node_id(),
6294                 }
6295         }
6296
6297         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
6298         /// used when constructing the route hints for HTLCs intended to be intercepted. See
6299         /// [`ChannelManager::forward_intercepted_htlc`].
6300         ///
6301         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
6302         /// times to get a unique scid.
6303         pub fn get_intercept_scid(&self) -> u64 {
6304                 let best_block_height = self.best_block.read().unwrap().height();
6305                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
6306                 loop {
6307                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
6308                         // Ensure the generated scid doesn't conflict with a real channel.
6309                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
6310                         return scid_candidate
6311                 }
6312         }
6313
6314         /// Gets inflight HTLC information by processing pending outbound payments that are in
6315         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
6316         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
6317                 let mut inflight_htlcs = InFlightHtlcs::new();
6318
6319                 let per_peer_state = self.per_peer_state.read().unwrap();
6320                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6321                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6322                         let peer_state = &mut *peer_state_lock;
6323                         for chan in peer_state.channel_by_id.values() {
6324                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
6325                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
6326                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
6327                                         }
6328                                 }
6329                         }
6330                 }
6331
6332                 inflight_htlcs
6333         }
6334
6335         #[cfg(any(test, feature = "_test_utils"))]
6336         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
6337                 let events = core::cell::RefCell::new(Vec::new());
6338                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
6339                 self.process_pending_events(&event_handler);
6340                 events.into_inner()
6341         }
6342
6343         #[cfg(feature = "_test_utils")]
6344         pub fn push_pending_event(&self, event: events::Event) {
6345                 let mut events = self.pending_events.lock().unwrap();
6346                 events.push_back((event, None));
6347         }
6348
6349         #[cfg(test)]
6350         pub fn pop_pending_event(&self) -> Option<events::Event> {
6351                 let mut events = self.pending_events.lock().unwrap();
6352                 events.pop_front().map(|(e, _)| e)
6353         }
6354
6355         #[cfg(test)]
6356         pub fn has_pending_payments(&self) -> bool {
6357                 self.pending_outbound_payments.has_pending_payments()
6358         }
6359
6360         #[cfg(test)]
6361         pub fn clear_pending_payments(&self) {
6362                 self.pending_outbound_payments.clear_pending_payments()
6363         }
6364
6365         /// When something which was blocking a channel from updating its [`ChannelMonitor`] (e.g. an
6366         /// [`Event`] being handled) completes, this should be called to restore the channel to normal
6367         /// operation. It will double-check that nothing *else* is also blocking the same channel from
6368         /// making progress and then any blocked [`ChannelMonitorUpdate`]s fly.
6369         fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, mut completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
6370                 let mut errors = Vec::new();
6371                 loop {
6372                         let per_peer_state = self.per_peer_state.read().unwrap();
6373                         if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
6374                                 let mut peer_state_lck = peer_state_mtx.lock().unwrap();
6375                                 let peer_state = &mut *peer_state_lck;
6376
6377                                 if let Some(blocker) = completed_blocker.take() {
6378                                         // Only do this on the first iteration of the loop.
6379                                         if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
6380                                                 .get_mut(&channel_funding_outpoint.to_channel_id())
6381                                         {
6382                                                 blockers.retain(|iter| iter != &blocker);
6383                                         }
6384                                 }
6385
6386                                 if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
6387                                         channel_funding_outpoint, counterparty_node_id) {
6388                                         // Check that, while holding the peer lock, we don't have anything else
6389                                         // blocking monitor updates for this channel. If we do, release the monitor
6390                                         // update(s) when those blockers complete.
6391                                         log_trace!(self.logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
6392                                                 log_bytes!(&channel_funding_outpoint.to_channel_id()[..]));
6393                                         break;
6394                                 }
6395
6396                                 if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(channel_funding_outpoint.to_channel_id()) {
6397                                         debug_assert_eq!(chan.get().context.get_funding_txo().unwrap(), channel_funding_outpoint);
6398                                         if let Some((monitor_update, further_update_exists)) = chan.get_mut().unblock_next_blocked_monitor_update() {
6399                                                 log_debug!(self.logger, "Unlocking monitor updating for channel {} and updating monitor",
6400                                                         log_bytes!(&channel_funding_outpoint.to_channel_id()[..]));
6401                                                 if let Err(e) = handle_new_monitor_update!(self, channel_funding_outpoint, monitor_update,
6402                                                         peer_state_lck, peer_state, per_peer_state, chan)
6403                                                 {
6404                                                         errors.push((e, counterparty_node_id));
6405                                                 }
6406                                                 if further_update_exists {
6407                                                         // If there are more `ChannelMonitorUpdate`s to process, restart at the
6408                                                         // top of the loop.
6409                                                         continue;
6410                                                 }
6411                                         } else {
6412                                                 log_trace!(self.logger, "Unlocked monitor updating for channel {} without monitors to update",
6413                                                         log_bytes!(&channel_funding_outpoint.to_channel_id()[..]));
6414                                         }
6415                                 }
6416                         } else {
6417                                 log_debug!(self.logger,
6418                                         "Got a release post-RAA monitor update for peer {} but the channel is gone",
6419                                         log_pubkey!(counterparty_node_id));
6420                         }
6421                         break;
6422                 }
6423                 for (err, counterparty_node_id) in errors {
6424                         let res = Err::<(), _>(err);
6425                         let _ = handle_error!(self, res, counterparty_node_id);
6426                 }
6427         }
6428
6429         fn handle_post_event_actions(&self, actions: Vec<EventCompletionAction>) {
6430                 for action in actions {
6431                         match action {
6432                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6433                                         channel_funding_outpoint, counterparty_node_id
6434                                 } => {
6435                                         self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, None);
6436                                 }
6437                         }
6438                 }
6439         }
6440
6441         /// Processes any events asynchronously in the order they were generated since the last call
6442         /// using the given event handler.
6443         ///
6444         /// See the trait-level documentation of [`EventsProvider`] for requirements.
6445         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
6446                 &self, handler: H
6447         ) {
6448                 let mut ev;
6449                 process_events_body!(self, ev, { handler(ev).await });
6450         }
6451 }
6452
6453 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>
6454 where
6455         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6456         T::Target: BroadcasterInterface,
6457         ES::Target: EntropySource,
6458         NS::Target: NodeSigner,
6459         SP::Target: SignerProvider,
6460         F::Target: FeeEstimator,
6461         R::Target: Router,
6462         L::Target: Logger,
6463 {
6464         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
6465         /// The returned array will contain `MessageSendEvent`s for different peers if
6466         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
6467         /// is always placed next to each other.
6468         ///
6469         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
6470         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
6471         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
6472         /// will randomly be placed first or last in the returned array.
6473         ///
6474         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
6475         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
6476         /// the `MessageSendEvent`s to the specific peer they were generated under.
6477         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
6478                 let events = RefCell::new(Vec::new());
6479                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
6480                         let mut result = self.process_background_events();
6481
6482                         // TODO: This behavior should be documented. It's unintuitive that we query
6483                         // ChannelMonitors when clearing other events.
6484                         if self.process_pending_monitor_events() {
6485                                 result = NotifyOption::DoPersist;
6486                         }
6487
6488                         if self.check_free_holding_cells() {
6489                                 result = NotifyOption::DoPersist;
6490                         }
6491                         if self.maybe_generate_initial_closing_signed() {
6492                                 result = NotifyOption::DoPersist;
6493                         }
6494
6495                         let mut pending_events = Vec::new();
6496                         let per_peer_state = self.per_peer_state.read().unwrap();
6497                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6498                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6499                                 let peer_state = &mut *peer_state_lock;
6500                                 if peer_state.pending_msg_events.len() > 0 {
6501                                         pending_events.append(&mut peer_state.pending_msg_events);
6502                                 }
6503                         }
6504
6505                         if !pending_events.is_empty() {
6506                                 events.replace(pending_events);
6507                         }
6508
6509                         result
6510                 });
6511                 events.into_inner()
6512         }
6513 }
6514
6515 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>
6516 where
6517         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6518         T::Target: BroadcasterInterface,
6519         ES::Target: EntropySource,
6520         NS::Target: NodeSigner,
6521         SP::Target: SignerProvider,
6522         F::Target: FeeEstimator,
6523         R::Target: Router,
6524         L::Target: Logger,
6525 {
6526         /// Processes events that must be periodically handled.
6527         ///
6528         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
6529         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
6530         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
6531                 let mut ev;
6532                 process_events_body!(self, ev, handler.handle_event(ev));
6533         }
6534 }
6535
6536 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>
6537 where
6538         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6539         T::Target: BroadcasterInterface,
6540         ES::Target: EntropySource,
6541         NS::Target: NodeSigner,
6542         SP::Target: SignerProvider,
6543         F::Target: FeeEstimator,
6544         R::Target: Router,
6545         L::Target: Logger,
6546 {
6547         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
6548                 {
6549                         let best_block = self.best_block.read().unwrap();
6550                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
6551                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
6552                         assert_eq!(best_block.height(), height - 1,
6553                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
6554                 }
6555
6556                 self.transactions_confirmed(header, txdata, height);
6557                 self.best_block_updated(header, height);
6558         }
6559
6560         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
6561                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock,
6562                         &self.persistence_notifier, || -> NotifyOption { NotifyOption::DoPersist });
6563                 let new_height = height - 1;
6564                 {
6565                         let mut best_block = self.best_block.write().unwrap();
6566                         assert_eq!(best_block.block_hash(), header.block_hash(),
6567                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
6568                         assert_eq!(best_block.height(), height,
6569                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
6570                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
6571                 }
6572
6573                 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));
6574         }
6575 }
6576
6577 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>
6578 where
6579         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6580         T::Target: BroadcasterInterface,
6581         ES::Target: EntropySource,
6582         NS::Target: NodeSigner,
6583         SP::Target: SignerProvider,
6584         F::Target: FeeEstimator,
6585         R::Target: Router,
6586         L::Target: Logger,
6587 {
6588         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
6589                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
6590                 // during initialization prior to the chain_monitor being fully configured in some cases.
6591                 // See the docs for `ChannelManagerReadArgs` for more.
6592
6593                 let block_hash = header.block_hash();
6594                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
6595
6596                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock,
6597                         &self.persistence_notifier, || -> NotifyOption { NotifyOption::DoPersist });
6598                 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)
6599                         .map(|(a, b)| (a, Vec::new(), b)));
6600
6601                 let last_best_block_height = self.best_block.read().unwrap().height();
6602                 if height < last_best_block_height {
6603                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
6604                         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));
6605                 }
6606         }
6607
6608         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
6609                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
6610                 // during initialization prior to the chain_monitor being fully configured in some cases.
6611                 // See the docs for `ChannelManagerReadArgs` for more.
6612
6613                 let block_hash = header.block_hash();
6614                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
6615
6616                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock,
6617                         &self.persistence_notifier, || -> NotifyOption { NotifyOption::DoPersist });
6618                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
6619
6620                 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));
6621
6622                 macro_rules! max_time {
6623                         ($timestamp: expr) => {
6624                                 loop {
6625                                         // Update $timestamp to be the max of its current value and the block
6626                                         // timestamp. This should keep us close to the current time without relying on
6627                                         // having an explicit local time source.
6628                                         // Just in case we end up in a race, we loop until we either successfully
6629                                         // update $timestamp or decide we don't need to.
6630                                         let old_serial = $timestamp.load(Ordering::Acquire);
6631                                         if old_serial >= header.time as usize { break; }
6632                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
6633                                                 break;
6634                                         }
6635                                 }
6636                         }
6637                 }
6638                 max_time!(self.highest_seen_timestamp);
6639                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
6640                 payment_secrets.retain(|_, inbound_payment| {
6641                         inbound_payment.expiry_time > header.time as u64
6642                 });
6643         }
6644
6645         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
6646                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
6647                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
6648                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6649                         let peer_state = &mut *peer_state_lock;
6650                         for chan in peer_state.channel_by_id.values() {
6651                                 if let (Some(funding_txo), Some(block_hash)) = (chan.context.get_funding_txo(), chan.context.get_funding_tx_confirmed_in()) {
6652                                         res.push((funding_txo.txid, Some(block_hash)));
6653                                 }
6654                         }
6655                 }
6656                 res
6657         }
6658
6659         fn transaction_unconfirmed(&self, txid: &Txid) {
6660                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock,
6661                         &self.persistence_notifier, || -> NotifyOption { NotifyOption::DoPersist });
6662                 self.do_chain_event(None, |channel| {
6663                         if let Some(funding_txo) = channel.context.get_funding_txo() {
6664                                 if funding_txo.txid == *txid {
6665                                         channel.funding_transaction_unconfirmed(&self.logger).map(|()| (None, Vec::new(), None))
6666                                 } else { Ok((None, Vec::new(), None)) }
6667                         } else { Ok((None, Vec::new(), None)) }
6668                 });
6669         }
6670 }
6671
6672 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>
6673 where
6674         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6675         T::Target: BroadcasterInterface,
6676         ES::Target: EntropySource,
6677         NS::Target: NodeSigner,
6678         SP::Target: SignerProvider,
6679         F::Target: FeeEstimator,
6680         R::Target: Router,
6681         L::Target: Logger,
6682 {
6683         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
6684         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
6685         /// the function.
6686         fn do_chain_event<FN: Fn(&mut Channel<<SP::Target as SignerProvider>::Signer>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
6687                         (&self, height_opt: Option<u32>, f: FN) {
6688                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
6689                 // during initialization prior to the chain_monitor being fully configured in some cases.
6690                 // See the docs for `ChannelManagerReadArgs` for more.
6691
6692                 let mut failed_channels = Vec::new();
6693                 let mut timed_out_htlcs = Vec::new();
6694                 {
6695                         let per_peer_state = self.per_peer_state.read().unwrap();
6696                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6697                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6698                                 let peer_state = &mut *peer_state_lock;
6699                                 let pending_msg_events = &mut peer_state.pending_msg_events;
6700                                 peer_state.channel_by_id.retain(|_, channel| {
6701                                         let res = f(channel);
6702                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
6703                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
6704                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
6705                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
6706                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
6707                                                 }
6708                                                 if let Some(channel_ready) = channel_ready_opt {
6709                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
6710                                                         if channel.context.is_usable() {
6711                                                                 log_trace!(self.logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", log_bytes!(channel.context.channel_id()));
6712                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
6713                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
6714                                                                                 node_id: channel.context.get_counterparty_node_id(),
6715                                                                                 msg,
6716                                                                         });
6717                                                                 }
6718                                                         } else {
6719                                                                 log_trace!(self.logger, "Sending channel_ready WITHOUT channel_update for {}", log_bytes!(channel.context.channel_id()));
6720                                                         }
6721                                                 }
6722
6723                                                 {
6724                                                         let mut pending_events = self.pending_events.lock().unwrap();
6725                                                         emit_channel_ready_event!(pending_events, channel);
6726                                                 }
6727
6728                                                 if let Some(announcement_sigs) = announcement_sigs {
6729                                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", log_bytes!(channel.context.channel_id()));
6730                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
6731                                                                 node_id: channel.context.get_counterparty_node_id(),
6732                                                                 msg: announcement_sigs,
6733                                                         });
6734                                                         if let Some(height) = height_opt {
6735                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.genesis_hash, height, &self.default_configuration) {
6736                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
6737                                                                                 msg: announcement,
6738                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
6739                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
6740                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
6741                                                                         });
6742                                                                 }
6743                                                         }
6744                                                 }
6745                                                 if channel.is_our_channel_ready() {
6746                                                         if let Some(real_scid) = channel.context.get_short_channel_id() {
6747                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
6748                                                                 // to the short_to_chan_info map here. Note that we check whether we
6749                                                                 // can relay using the real SCID at relay-time (i.e.
6750                                                                 // enforce option_scid_alias then), and if the funding tx is ever
6751                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
6752                                                                 // is always consistent.
6753                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
6754                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
6755                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.context.get_counterparty_node_id(), channel.context.channel_id()),
6756                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
6757                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
6758                                                         }
6759                                                 }
6760                                         } else if let Err(reason) = res {
6761                                                 update_maps_on_chan_removal!(self, &channel.context);
6762                                                 // It looks like our counterparty went on-chain or funding transaction was
6763                                                 // reorged out of the main chain. Close the channel.
6764                                                 failed_channels.push(channel.context.force_shutdown(true));
6765                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
6766                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6767                                                                 msg: update
6768                                                         });
6769                                                 }
6770                                                 let reason_message = format!("{}", reason);
6771                                                 self.issue_channel_close_events(&channel.context, reason);
6772                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
6773                                                         node_id: channel.context.get_counterparty_node_id(),
6774                                                         action: msgs::ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage {
6775                                                                 channel_id: channel.context.channel_id(),
6776                                                                 data: reason_message,
6777                                                         } },
6778                                                 });
6779                                                 return false;
6780                                         }
6781                                         true
6782                                 });
6783                         }
6784                 }
6785
6786                 if let Some(height) = height_opt {
6787                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
6788                                 payment.htlcs.retain(|htlc| {
6789                                         // If height is approaching the number of blocks we think it takes us to get
6790                                         // our commitment transaction confirmed before the HTLC expires, plus the
6791                                         // number of blocks we generally consider it to take to do a commitment update,
6792                                         // just give up on it and fail the HTLC.
6793                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
6794                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
6795                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
6796
6797                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
6798                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
6799                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
6800                                                 false
6801                                         } else { true }
6802                                 });
6803                                 !payment.htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
6804                         });
6805
6806                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
6807                         intercepted_htlcs.retain(|_, htlc| {
6808                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
6809                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6810                                                 short_channel_id: htlc.prev_short_channel_id,
6811                                                 htlc_id: htlc.prev_htlc_id,
6812                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
6813                                                 phantom_shared_secret: None,
6814                                                 outpoint: htlc.prev_funding_outpoint,
6815                                         });
6816
6817                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
6818                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6819                                                 _ => unreachable!(),
6820                                         };
6821                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
6822                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
6823                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
6824                                         log_trace!(self.logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
6825                                         false
6826                                 } else { true }
6827                         });
6828                 }
6829
6830                 self.handle_init_event_channel_failures(failed_channels);
6831
6832                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
6833                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
6834                 }
6835         }
6836
6837         /// Gets a [`Future`] that completes when this [`ChannelManager`] needs to be persisted.
6838         ///
6839         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
6840         /// [`ChannelManager`] and should instead register actions to be taken later.
6841         ///
6842         pub fn get_persistable_update_future(&self) -> Future {
6843                 self.persistence_notifier.get_future()
6844         }
6845
6846         #[cfg(any(test, feature = "_test_utils"))]
6847         pub fn get_persistence_condvar_value(&self) -> bool {
6848                 self.persistence_notifier.notify_pending()
6849         }
6850
6851         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
6852         /// [`chain::Confirm`] interfaces.
6853         pub fn current_best_block(&self) -> BestBlock {
6854                 self.best_block.read().unwrap().clone()
6855         }
6856
6857         /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
6858         /// [`ChannelManager`].
6859         pub fn node_features(&self) -> NodeFeatures {
6860                 provided_node_features(&self.default_configuration)
6861         }
6862
6863         /// Fetches the set of [`InvoiceFeatures`] flags which are provided by or required by
6864         /// [`ChannelManager`].
6865         ///
6866         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
6867         /// or not. Thus, this method is not public.
6868         #[cfg(any(feature = "_test_utils", test))]
6869         pub fn invoice_features(&self) -> InvoiceFeatures {
6870                 provided_invoice_features(&self.default_configuration)
6871         }
6872
6873         /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
6874         /// [`ChannelManager`].
6875         pub fn channel_features(&self) -> ChannelFeatures {
6876                 provided_channel_features(&self.default_configuration)
6877         }
6878
6879         /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
6880         /// [`ChannelManager`].
6881         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
6882                 provided_channel_type_features(&self.default_configuration)
6883         }
6884
6885         /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
6886         /// [`ChannelManager`].
6887         pub fn init_features(&self) -> InitFeatures {
6888                 provided_init_features(&self.default_configuration)
6889         }
6890 }
6891
6892 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
6893         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
6894 where
6895         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6896         T::Target: BroadcasterInterface,
6897         ES::Target: EntropySource,
6898         NS::Target: NodeSigner,
6899         SP::Target: SignerProvider,
6900         F::Target: FeeEstimator,
6901         R::Target: Router,
6902         L::Target: Logger,
6903 {
6904         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
6905                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6906                 let _ = handle_error!(self, self.internal_open_channel(counterparty_node_id, msg), *counterparty_node_id);
6907         }
6908
6909         fn handle_open_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
6910                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
6911                         "Dual-funded channels not supported".to_owned(),
6912                          msg.temporary_channel_id.clone())), *counterparty_node_id);
6913         }
6914
6915         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
6916                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6917                 let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
6918         }
6919
6920         fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
6921                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
6922                         "Dual-funded channels not supported".to_owned(),
6923                          msg.temporary_channel_id.clone())), *counterparty_node_id);
6924         }
6925
6926         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
6927                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6928                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
6929         }
6930
6931         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
6932                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6933                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
6934         }
6935
6936         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
6937                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6938                 let _ = handle_error!(self, self.internal_channel_ready(counterparty_node_id, msg), *counterparty_node_id);
6939         }
6940
6941         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
6942                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6943                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
6944         }
6945
6946         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
6947                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6948                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
6949         }
6950
6951         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
6952                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6953                 let _ = handle_error!(self, self.internal_update_add_htlc(counterparty_node_id, msg), *counterparty_node_id);
6954         }
6955
6956         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
6957                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6958                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
6959         }
6960
6961         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
6962                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6963                 let _ = handle_error!(self, self.internal_update_fail_htlc(counterparty_node_id, msg), *counterparty_node_id);
6964         }
6965
6966         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
6967                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6968                 let _ = handle_error!(self, self.internal_update_fail_malformed_htlc(counterparty_node_id, msg), *counterparty_node_id);
6969         }
6970
6971         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
6972                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6973                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
6974         }
6975
6976         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
6977                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6978                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
6979         }
6980
6981         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
6982                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6983                 let _ = handle_error!(self, self.internal_update_fee(counterparty_node_id, msg), *counterparty_node_id);
6984         }
6985
6986         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
6987                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6988                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
6989         }
6990
6991         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
6992                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
6993                         let force_persist = self.process_background_events();
6994                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
6995                                 if force_persist == NotifyOption::DoPersist { NotifyOption::DoPersist } else { persist }
6996                         } else {
6997                                 NotifyOption::SkipPersist
6998                         }
6999                 });
7000         }
7001
7002         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
7003                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7004                 let _ = handle_error!(self, self.internal_channel_reestablish(counterparty_node_id, msg), *counterparty_node_id);
7005         }
7006
7007         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
7008                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7009                 let mut failed_channels = Vec::new();
7010                 let mut per_peer_state = self.per_peer_state.write().unwrap();
7011                 let remove_peer = {
7012                         log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates.",
7013                                 log_pubkey!(counterparty_node_id));
7014                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
7015                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7016                                 let peer_state = &mut *peer_state_lock;
7017                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7018                                 peer_state.channel_by_id.retain(|_, chan| {
7019                                         chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger);
7020                                         if chan.is_shutdown() {
7021                                                 update_maps_on_chan_removal!(self, &chan.context);
7022                                                 self.issue_channel_close_events(&chan.context, ClosureReason::DisconnectedPeer);
7023                                                 return false;
7024                                         }
7025                                         true
7026                                 });
7027                                 peer_state.inbound_v1_channel_by_id.retain(|_, chan| {
7028                                         update_maps_on_chan_removal!(self, &chan.context);
7029                                         self.issue_channel_close_events(&chan.context, ClosureReason::DisconnectedPeer);
7030                                         false
7031                                 });
7032                                 peer_state.outbound_v1_channel_by_id.retain(|_, chan| {
7033                                         update_maps_on_chan_removal!(self, &chan.context);
7034                                         self.issue_channel_close_events(&chan.context, ClosureReason::DisconnectedPeer);
7035                                         false
7036                                 });
7037                                 pending_msg_events.retain(|msg| {
7038                                         match msg {
7039                                                 // V1 Channel Establishment
7040                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
7041                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
7042                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
7043                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
7044                                                 // V2 Channel Establishment
7045                                                 &events::MessageSendEvent::SendAcceptChannelV2 { .. } => false,
7046                                                 &events::MessageSendEvent::SendOpenChannelV2 { .. } => false,
7047                                                 // Common Channel Establishment
7048                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
7049                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
7050                                                 // Interactive Transaction Construction
7051                                                 &events::MessageSendEvent::SendTxAddInput { .. } => false,
7052                                                 &events::MessageSendEvent::SendTxAddOutput { .. } => false,
7053                                                 &events::MessageSendEvent::SendTxRemoveInput { .. } => false,
7054                                                 &events::MessageSendEvent::SendTxRemoveOutput { .. } => false,
7055                                                 &events::MessageSendEvent::SendTxComplete { .. } => false,
7056                                                 &events::MessageSendEvent::SendTxSignatures { .. } => false,
7057                                                 &events::MessageSendEvent::SendTxInitRbf { .. } => false,
7058                                                 &events::MessageSendEvent::SendTxAckRbf { .. } => false,
7059                                                 &events::MessageSendEvent::SendTxAbort { .. } => false,
7060                                                 // Channel Operations
7061                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
7062                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
7063                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
7064                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
7065                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
7066                                                 &events::MessageSendEvent::HandleError { .. } => false,
7067                                                 // Gossip
7068                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
7069                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
7070                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
7071                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
7072                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
7073                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
7074                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
7075                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
7076                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
7077                                         }
7078                                 });
7079                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
7080                                 peer_state.is_connected = false;
7081                                 peer_state.ok_to_remove(true)
7082                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
7083                 };
7084                 if remove_peer {
7085                         per_peer_state.remove(counterparty_node_id);
7086                 }
7087                 mem::drop(per_peer_state);
7088
7089                 for failure in failed_channels.drain(..) {
7090                         self.finish_force_close_channel(failure);
7091                 }
7092         }
7093
7094         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
7095                 if !init_msg.features.supports_static_remote_key() {
7096                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
7097                         return Err(());
7098                 }
7099
7100                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7101
7102                 // If we have too many peers connected which don't have funded channels, disconnect the
7103                 // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
7104                 // unfunded channels taking up space in memory for disconnected peers, we still let new
7105                 // peers connect, but we'll reject new channels from them.
7106                 let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
7107                 let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
7108
7109                 {
7110                         let mut peer_state_lock = self.per_peer_state.write().unwrap();
7111                         match peer_state_lock.entry(counterparty_node_id.clone()) {
7112                                 hash_map::Entry::Vacant(e) => {
7113                                         if inbound_peer_limited {
7114                                                 return Err(());
7115                                         }
7116                                         e.insert(Mutex::new(PeerState {
7117                                                 channel_by_id: HashMap::new(),
7118                                                 outbound_v1_channel_by_id: HashMap::new(),
7119                                                 inbound_v1_channel_by_id: HashMap::new(),
7120                                                 latest_features: init_msg.features.clone(),
7121                                                 pending_msg_events: Vec::new(),
7122                                                 in_flight_monitor_updates: BTreeMap::new(),
7123                                                 monitor_update_blocked_actions: BTreeMap::new(),
7124                                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
7125                                                 is_connected: true,
7126                                         }));
7127                                 },
7128                                 hash_map::Entry::Occupied(e) => {
7129                                         let mut peer_state = e.get().lock().unwrap();
7130                                         peer_state.latest_features = init_msg.features.clone();
7131
7132                                         let best_block_height = self.best_block.read().unwrap().height();
7133                                         if inbound_peer_limited &&
7134                                                 Self::unfunded_channel_count(&*peer_state, best_block_height) ==
7135                                                 peer_state.channel_by_id.len()
7136                                         {
7137                                                 return Err(());
7138                                         }
7139
7140                                         debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
7141                                         peer_state.is_connected = true;
7142                                 },
7143                         }
7144                 }
7145
7146                 log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
7147
7148                 let per_peer_state = self.per_peer_state.read().unwrap();
7149                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7150                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7151                         let peer_state = &mut *peer_state_lock;
7152                         let pending_msg_events = &mut peer_state.pending_msg_events;
7153                         peer_state.channel_by_id.retain(|_, chan| {
7154                                 let retain = if chan.context.get_counterparty_node_id() == *counterparty_node_id {
7155                                         if !chan.context.have_received_message() {
7156                                                 // If we created this (outbound) channel while we were disconnected from the
7157                                                 // peer we probably failed to send the open_channel message, which is now
7158                                                 // lost. We can't have had anything pending related to this channel, so we just
7159                                                 // drop it.
7160                                                 false
7161                                         } else {
7162                                                 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
7163                                                         node_id: chan.context.get_counterparty_node_id(),
7164                                                         msg: chan.get_channel_reestablish(&self.logger),
7165                                                 });
7166                                                 true
7167                                         }
7168                                 } else { true };
7169                                 if retain && chan.context.get_counterparty_node_id() != *counterparty_node_id {
7170                                         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) {
7171                                                 if let Ok(update_msg) = self.get_channel_update_for_broadcast(chan) {
7172                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelAnnouncement {
7173                                                                 node_id: *counterparty_node_id,
7174                                                                 msg, update_msg,
7175                                                         });
7176                                                 }
7177                                         }
7178                                 }
7179                                 retain
7180                         });
7181                 }
7182                 //TODO: Also re-broadcast announcement_signatures
7183                 Ok(())
7184         }
7185
7186         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
7187                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7188
7189                 if msg.channel_id == [0; 32] {
7190                         let channel_ids: Vec<[u8; 32]> = {
7191                                 let per_peer_state = self.per_peer_state.read().unwrap();
7192                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
7193                                 if peer_state_mutex_opt.is_none() { return; }
7194                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
7195                                 let peer_state = &mut *peer_state_lock;
7196                                 peer_state.channel_by_id.keys().cloned()
7197                                         .chain(peer_state.outbound_v1_channel_by_id.keys().cloned())
7198                                         .chain(peer_state.inbound_v1_channel_by_id.keys().cloned()).collect()
7199                         };
7200                         for channel_id in channel_ids {
7201                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
7202                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
7203                         }
7204                 } else {
7205                         {
7206                                 // First check if we can advance the channel type and try again.
7207                                 let per_peer_state = self.per_peer_state.read().unwrap();
7208                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
7209                                 if peer_state_mutex_opt.is_none() { return; }
7210                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
7211                                 let peer_state = &mut *peer_state_lock;
7212                                 if let Some(chan) = peer_state.outbound_v1_channel_by_id.get_mut(&msg.channel_id) {
7213                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.genesis_hash) {
7214                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
7215                                                         node_id: *counterparty_node_id,
7216                                                         msg,
7217                                                 });
7218                                                 return;
7219                                         }
7220                                 }
7221                         }
7222
7223                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
7224                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
7225                 }
7226         }
7227
7228         fn provided_node_features(&self) -> NodeFeatures {
7229                 provided_node_features(&self.default_configuration)
7230         }
7231
7232         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
7233                 provided_init_features(&self.default_configuration)
7234         }
7235
7236         fn get_genesis_hashes(&self) -> Option<Vec<ChainHash>> {
7237                 Some(vec![ChainHash::from(&self.genesis_hash[..])])
7238         }
7239
7240         fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
7241                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7242                         "Dual-funded channels not supported".to_owned(),
7243                          msg.channel_id.clone())), *counterparty_node_id);
7244         }
7245
7246         fn handle_tx_add_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
7247                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7248                         "Dual-funded channels not supported".to_owned(),
7249                          msg.channel_id.clone())), *counterparty_node_id);
7250         }
7251
7252         fn handle_tx_remove_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
7253                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7254                         "Dual-funded channels not supported".to_owned(),
7255                          msg.channel_id.clone())), *counterparty_node_id);
7256         }
7257
7258         fn handle_tx_remove_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
7259                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7260                         "Dual-funded channels not supported".to_owned(),
7261                          msg.channel_id.clone())), *counterparty_node_id);
7262         }
7263
7264         fn handle_tx_complete(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxComplete) {
7265                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7266                         "Dual-funded channels not supported".to_owned(),
7267                          msg.channel_id.clone())), *counterparty_node_id);
7268         }
7269
7270         fn handle_tx_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) {
7271                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7272                         "Dual-funded channels not supported".to_owned(),
7273                          msg.channel_id.clone())), *counterparty_node_id);
7274         }
7275
7276         fn handle_tx_init_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
7277                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7278                         "Dual-funded channels not supported".to_owned(),
7279                          msg.channel_id.clone())), *counterparty_node_id);
7280         }
7281
7282         fn handle_tx_ack_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
7283                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7284                         "Dual-funded channels not supported".to_owned(),
7285                          msg.channel_id.clone())), *counterparty_node_id);
7286         }
7287
7288         fn handle_tx_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) {
7289                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7290                         "Dual-funded channels not supported".to_owned(),
7291                          msg.channel_id.clone())), *counterparty_node_id);
7292         }
7293 }
7294
7295 /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
7296 /// [`ChannelManager`].
7297 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
7298         provided_init_features(config).to_context()
7299 }
7300
7301 /// Fetches the set of [`InvoiceFeatures`] flags which are provided by or required by
7302 /// [`ChannelManager`].
7303 ///
7304 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
7305 /// or not. Thus, this method is not public.
7306 #[cfg(any(feature = "_test_utils", test))]
7307 pub(crate) fn provided_invoice_features(config: &UserConfig) -> InvoiceFeatures {
7308         provided_init_features(config).to_context()
7309 }
7310
7311 /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
7312 /// [`ChannelManager`].
7313 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
7314         provided_init_features(config).to_context()
7315 }
7316
7317 /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
7318 /// [`ChannelManager`].
7319 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
7320         ChannelTypeFeatures::from_init(&provided_init_features(config))
7321 }
7322
7323 /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
7324 /// [`ChannelManager`].
7325 pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
7326         // Note that if new features are added here which other peers may (eventually) require, we
7327         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
7328         // [`ErroringMessageHandler`].
7329         let mut features = InitFeatures::empty();
7330         features.set_data_loss_protect_required();
7331         features.set_upfront_shutdown_script_optional();
7332         features.set_variable_length_onion_required();
7333         features.set_static_remote_key_required();
7334         features.set_payment_secret_required();
7335         features.set_basic_mpp_optional();
7336         features.set_wumbo_optional();
7337         features.set_shutdown_any_segwit_optional();
7338         features.set_channel_type_optional();
7339         features.set_scid_privacy_optional();
7340         features.set_zero_conf_optional();
7341         if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
7342                 features.set_anchors_zero_fee_htlc_tx_optional();
7343         }
7344         features
7345 }
7346
7347 const SERIALIZATION_VERSION: u8 = 1;
7348 const MIN_SERIALIZATION_VERSION: u8 = 1;
7349
7350 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
7351         (2, fee_base_msat, required),
7352         (4, fee_proportional_millionths, required),
7353         (6, cltv_expiry_delta, required),
7354 });
7355
7356 impl_writeable_tlv_based!(ChannelCounterparty, {
7357         (2, node_id, required),
7358         (4, features, required),
7359         (6, unspendable_punishment_reserve, required),
7360         (8, forwarding_info, option),
7361         (9, outbound_htlc_minimum_msat, option),
7362         (11, outbound_htlc_maximum_msat, option),
7363 });
7364
7365 impl Writeable for ChannelDetails {
7366         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
7367                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
7368                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
7369                 let user_channel_id_low = self.user_channel_id as u64;
7370                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
7371                 write_tlv_fields!(writer, {
7372                         (1, self.inbound_scid_alias, option),
7373                         (2, self.channel_id, required),
7374                         (3, self.channel_type, option),
7375                         (4, self.counterparty, required),
7376                         (5, self.outbound_scid_alias, option),
7377                         (6, self.funding_txo, option),
7378                         (7, self.config, option),
7379                         (8, self.short_channel_id, option),
7380                         (9, self.confirmations, option),
7381                         (10, self.channel_value_satoshis, required),
7382                         (12, self.unspendable_punishment_reserve, option),
7383                         (14, user_channel_id_low, required),
7384                         (16, self.balance_msat, required),
7385                         (18, self.outbound_capacity_msat, required),
7386                         (19, self.next_outbound_htlc_limit_msat, required),
7387                         (20, self.inbound_capacity_msat, required),
7388                         (21, self.next_outbound_htlc_minimum_msat, required),
7389                         (22, self.confirmations_required, option),
7390                         (24, self.force_close_spend_delay, option),
7391                         (26, self.is_outbound, required),
7392                         (28, self.is_channel_ready, required),
7393                         (30, self.is_usable, required),
7394                         (32, self.is_public, required),
7395                         (33, self.inbound_htlc_minimum_msat, option),
7396                         (35, self.inbound_htlc_maximum_msat, option),
7397                         (37, user_channel_id_high_opt, option),
7398                         (39, self.feerate_sat_per_1000_weight, option),
7399                         (41, self.channel_shutdown_state, option),
7400                 });
7401                 Ok(())
7402         }
7403 }
7404
7405 impl Readable for ChannelDetails {
7406         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
7407                 _init_and_read_tlv_fields!(reader, {
7408                         (1, inbound_scid_alias, option),
7409                         (2, channel_id, required),
7410                         (3, channel_type, option),
7411                         (4, counterparty, required),
7412                         (5, outbound_scid_alias, option),
7413                         (6, funding_txo, option),
7414                         (7, config, option),
7415                         (8, short_channel_id, option),
7416                         (9, confirmations, option),
7417                         (10, channel_value_satoshis, required),
7418                         (12, unspendable_punishment_reserve, option),
7419                         (14, user_channel_id_low, required),
7420                         (16, balance_msat, required),
7421                         (18, outbound_capacity_msat, required),
7422                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
7423                         // filled in, so we can safely unwrap it here.
7424                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
7425                         (20, inbound_capacity_msat, required),
7426                         (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
7427                         (22, confirmations_required, option),
7428                         (24, force_close_spend_delay, option),
7429                         (26, is_outbound, required),
7430                         (28, is_channel_ready, required),
7431                         (30, is_usable, required),
7432                         (32, is_public, required),
7433                         (33, inbound_htlc_minimum_msat, option),
7434                         (35, inbound_htlc_maximum_msat, option),
7435                         (37, user_channel_id_high_opt, option),
7436                         (39, feerate_sat_per_1000_weight, option),
7437                         (41, channel_shutdown_state, option),
7438                 });
7439
7440                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
7441                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
7442                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
7443                 let user_channel_id = user_channel_id_low as u128 +
7444                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
7445
7446                 Ok(Self {
7447                         inbound_scid_alias,
7448                         channel_id: channel_id.0.unwrap(),
7449                         channel_type,
7450                         counterparty: counterparty.0.unwrap(),
7451                         outbound_scid_alias,
7452                         funding_txo,
7453                         config,
7454                         short_channel_id,
7455                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
7456                         unspendable_punishment_reserve,
7457                         user_channel_id,
7458                         balance_msat: balance_msat.0.unwrap(),
7459                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
7460                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
7461                         next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat.0.unwrap(),
7462                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
7463                         confirmations_required,
7464                         confirmations,
7465                         force_close_spend_delay,
7466                         is_outbound: is_outbound.0.unwrap(),
7467                         is_channel_ready: is_channel_ready.0.unwrap(),
7468                         is_usable: is_usable.0.unwrap(),
7469                         is_public: is_public.0.unwrap(),
7470                         inbound_htlc_minimum_msat,
7471                         inbound_htlc_maximum_msat,
7472                         feerate_sat_per_1000_weight,
7473                         channel_shutdown_state,
7474                 })
7475         }
7476 }
7477
7478 impl_writeable_tlv_based!(PhantomRouteHints, {
7479         (2, channels, vec_type),
7480         (4, phantom_scid, required),
7481         (6, real_node_pubkey, required),
7482 });
7483
7484 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
7485         (0, Forward) => {
7486                 (0, onion_packet, required),
7487                 (2, short_channel_id, required),
7488         },
7489         (1, Receive) => {
7490                 (0, payment_data, required),
7491                 (1, phantom_shared_secret, option),
7492                 (2, incoming_cltv_expiry, required),
7493                 (3, payment_metadata, option),
7494         },
7495         (2, ReceiveKeysend) => {
7496                 (0, payment_preimage, required),
7497                 (2, incoming_cltv_expiry, required),
7498                 (3, payment_metadata, option),
7499                 (4, payment_data, option), // Added in 0.0.116
7500         },
7501 ;);
7502
7503 impl_writeable_tlv_based!(PendingHTLCInfo, {
7504         (0, routing, required),
7505         (2, incoming_shared_secret, required),
7506         (4, payment_hash, required),
7507         (6, outgoing_amt_msat, required),
7508         (8, outgoing_cltv_value, required),
7509         (9, incoming_amt_msat, option),
7510         (10, skimmed_fee_msat, option),
7511 });
7512
7513
7514 impl Writeable for HTLCFailureMsg {
7515         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
7516                 match self {
7517                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
7518                                 0u8.write(writer)?;
7519                                 channel_id.write(writer)?;
7520                                 htlc_id.write(writer)?;
7521                                 reason.write(writer)?;
7522                         },
7523                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
7524                                 channel_id, htlc_id, sha256_of_onion, failure_code
7525                         }) => {
7526                                 1u8.write(writer)?;
7527                                 channel_id.write(writer)?;
7528                                 htlc_id.write(writer)?;
7529                                 sha256_of_onion.write(writer)?;
7530                                 failure_code.write(writer)?;
7531                         },
7532                 }
7533                 Ok(())
7534         }
7535 }
7536
7537 impl Readable for HTLCFailureMsg {
7538         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
7539                 let id: u8 = Readable::read(reader)?;
7540                 match id {
7541                         0 => {
7542                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
7543                                         channel_id: Readable::read(reader)?,
7544                                         htlc_id: Readable::read(reader)?,
7545                                         reason: Readable::read(reader)?,
7546                                 }))
7547                         },
7548                         1 => {
7549                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
7550                                         channel_id: Readable::read(reader)?,
7551                                         htlc_id: Readable::read(reader)?,
7552                                         sha256_of_onion: Readable::read(reader)?,
7553                                         failure_code: Readable::read(reader)?,
7554                                 }))
7555                         },
7556                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
7557                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
7558                         // messages contained in the variants.
7559                         // In version 0.0.101, support for reading the variants with these types was added, and
7560                         // we should migrate to writing these variants when UpdateFailHTLC or
7561                         // UpdateFailMalformedHTLC get TLV fields.
7562                         2 => {
7563                                 let length: BigSize = Readable::read(reader)?;
7564                                 let mut s = FixedLengthReader::new(reader, length.0);
7565                                 let res = Readable::read(&mut s)?;
7566                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
7567                                 Ok(HTLCFailureMsg::Relay(res))
7568                         },
7569                         3 => {
7570                                 let length: BigSize = Readable::read(reader)?;
7571                                 let mut s = FixedLengthReader::new(reader, length.0);
7572                                 let res = Readable::read(&mut s)?;
7573                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
7574                                 Ok(HTLCFailureMsg::Malformed(res))
7575                         },
7576                         _ => Err(DecodeError::UnknownRequiredFeature),
7577                 }
7578         }
7579 }
7580
7581 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
7582         (0, Forward),
7583         (1, Fail),
7584 );
7585
7586 impl_writeable_tlv_based!(HTLCPreviousHopData, {
7587         (0, short_channel_id, required),
7588         (1, phantom_shared_secret, option),
7589         (2, outpoint, required),
7590         (4, htlc_id, required),
7591         (6, incoming_packet_shared_secret, required)
7592 });
7593
7594 impl Writeable for ClaimableHTLC {
7595         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
7596                 let (payment_data, keysend_preimage) = match &self.onion_payload {
7597                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
7598                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
7599                 };
7600                 write_tlv_fields!(writer, {
7601                         (0, self.prev_hop, required),
7602                         (1, self.total_msat, required),
7603                         (2, self.value, required),
7604                         (3, self.sender_intended_value, required),
7605                         (4, payment_data, option),
7606                         (5, self.total_value_received, option),
7607                         (6, self.cltv_expiry, required),
7608                         (8, keysend_preimage, option),
7609                         (10, self.counterparty_skimmed_fee_msat, option),
7610                 });
7611                 Ok(())
7612         }
7613 }
7614
7615 impl Readable for ClaimableHTLC {
7616         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
7617                 _init_and_read_tlv_fields!(reader, {
7618                         (0, prev_hop, required),
7619                         (1, total_msat, option),
7620                         (2, value_ser, required),
7621                         (3, sender_intended_value, option),
7622                         (4, payment_data_opt, option),
7623                         (5, total_value_received, option),
7624                         (6, cltv_expiry, required),
7625                         (8, keysend_preimage, option),
7626                         (10, counterparty_skimmed_fee_msat, option),
7627                 });
7628                 let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
7629                 let value = value_ser.0.unwrap();
7630                 let onion_payload = match keysend_preimage {
7631                         Some(p) => {
7632                                 if payment_data.is_some() {
7633                                         return Err(DecodeError::InvalidValue)
7634                                 }
7635                                 if total_msat.is_none() {
7636                                         total_msat = Some(value);
7637                                 }
7638                                 OnionPayload::Spontaneous(p)
7639                         },
7640                         None => {
7641                                 if total_msat.is_none() {
7642                                         if payment_data.is_none() {
7643                                                 return Err(DecodeError::InvalidValue)
7644                                         }
7645                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
7646                                 }
7647                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
7648                         },
7649                 };
7650                 Ok(Self {
7651                         prev_hop: prev_hop.0.unwrap(),
7652                         timer_ticks: 0,
7653                         value,
7654                         sender_intended_value: sender_intended_value.unwrap_or(value),
7655                         total_value_received,
7656                         total_msat: total_msat.unwrap(),
7657                         onion_payload,
7658                         cltv_expiry: cltv_expiry.0.unwrap(),
7659                         counterparty_skimmed_fee_msat,
7660                 })
7661         }
7662 }
7663
7664 impl Readable for HTLCSource {
7665         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
7666                 let id: u8 = Readable::read(reader)?;
7667                 match id {
7668                         0 => {
7669                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
7670                                 let mut first_hop_htlc_msat: u64 = 0;
7671                                 let mut path_hops: Option<Vec<RouteHop>> = Some(Vec::new());
7672                                 let mut payment_id = None;
7673                                 let mut payment_params: Option<PaymentParameters> = None;
7674                                 let mut blinded_tail: Option<BlindedTail> = None;
7675                                 read_tlv_fields!(reader, {
7676                                         (0, session_priv, required),
7677                                         (1, payment_id, option),
7678                                         (2, first_hop_htlc_msat, required),
7679                                         (4, path_hops, vec_type),
7680                                         (5, payment_params, (option: ReadableArgs, 0)),
7681                                         (6, blinded_tail, option),
7682                                 });
7683                                 if payment_id.is_none() {
7684                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
7685                                         // instead.
7686                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
7687                                 }
7688                                 let path = Path { hops: path_hops.ok_or(DecodeError::InvalidValue)?, blinded_tail };
7689                                 if path.hops.len() == 0 {
7690                                         return Err(DecodeError::InvalidValue);
7691                                 }
7692                                 if let Some(params) = payment_params.as_mut() {
7693                                         if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = params.payee {
7694                                                 if final_cltv_expiry_delta == &0 {
7695                                                         *final_cltv_expiry_delta = path.final_cltv_expiry_delta().ok_or(DecodeError::InvalidValue)?;
7696                                                 }
7697                                         }
7698                                 }
7699                                 Ok(HTLCSource::OutboundRoute {
7700                                         session_priv: session_priv.0.unwrap(),
7701                                         first_hop_htlc_msat,
7702                                         path,
7703                                         payment_id: payment_id.unwrap(),
7704                                 })
7705                         }
7706                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
7707                         _ => Err(DecodeError::UnknownRequiredFeature),
7708                 }
7709         }
7710 }
7711
7712 impl Writeable for HTLCSource {
7713         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
7714                 match self {
7715                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id } => {
7716                                 0u8.write(writer)?;
7717                                 let payment_id_opt = Some(payment_id);
7718                                 write_tlv_fields!(writer, {
7719                                         (0, session_priv, required),
7720                                         (1, payment_id_opt, option),
7721                                         (2, first_hop_htlc_msat, required),
7722                                         // 3 was previously used to write a PaymentSecret for the payment.
7723                                         (4, path.hops, vec_type),
7724                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
7725                                         (6, path.blinded_tail, option),
7726                                  });
7727                         }
7728                         HTLCSource::PreviousHopData(ref field) => {
7729                                 1u8.write(writer)?;
7730                                 field.write(writer)?;
7731                         }
7732                 }
7733                 Ok(())
7734         }
7735 }
7736
7737 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
7738         (0, forward_info, required),
7739         (1, prev_user_channel_id, (default_value, 0)),
7740         (2, prev_short_channel_id, required),
7741         (4, prev_htlc_id, required),
7742         (6, prev_funding_outpoint, required),
7743 });
7744
7745 impl_writeable_tlv_based_enum!(HTLCForwardInfo,
7746         (1, FailHTLC) => {
7747                 (0, htlc_id, required),
7748                 (2, err_packet, required),
7749         };
7750         (0, AddHTLC)
7751 );
7752
7753 impl_writeable_tlv_based!(PendingInboundPayment, {
7754         (0, payment_secret, required),
7755         (2, expiry_time, required),
7756         (4, user_payment_id, required),
7757         (6, payment_preimage, required),
7758         (8, min_value_msat, required),
7759 });
7760
7761 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>
7762 where
7763         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7764         T::Target: BroadcasterInterface,
7765         ES::Target: EntropySource,
7766         NS::Target: NodeSigner,
7767         SP::Target: SignerProvider,
7768         F::Target: FeeEstimator,
7769         R::Target: Router,
7770         L::Target: Logger,
7771 {
7772         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
7773                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
7774
7775                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
7776
7777                 self.genesis_hash.write(writer)?;
7778                 {
7779                         let best_block = self.best_block.read().unwrap();
7780                         best_block.height().write(writer)?;
7781                         best_block.block_hash().write(writer)?;
7782                 }
7783
7784                 let mut serializable_peer_count: u64 = 0;
7785                 {
7786                         let per_peer_state = self.per_peer_state.read().unwrap();
7787                         let mut unfunded_channels = 0;
7788                         let mut number_of_channels = 0;
7789                         for (_, peer_state_mutex) in per_peer_state.iter() {
7790                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7791                                 let peer_state = &mut *peer_state_lock;
7792                                 if !peer_state.ok_to_remove(false) {
7793                                         serializable_peer_count += 1;
7794                                 }
7795                                 number_of_channels += peer_state.channel_by_id.len();
7796                                 for (_, channel) in peer_state.channel_by_id.iter() {
7797                                         if !channel.context.is_funding_initiated() {
7798                                                 unfunded_channels += 1;
7799                                         }
7800                                 }
7801                         }
7802
7803                         ((number_of_channels - unfunded_channels) as u64).write(writer)?;
7804
7805                         for (_, peer_state_mutex) in per_peer_state.iter() {
7806                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7807                                 let peer_state = &mut *peer_state_lock;
7808                                 for (_, channel) in peer_state.channel_by_id.iter() {
7809                                         if channel.context.is_funding_initiated() {
7810                                                 channel.write(writer)?;
7811                                         }
7812                                 }
7813                         }
7814                 }
7815
7816                 {
7817                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
7818                         (forward_htlcs.len() as u64).write(writer)?;
7819                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
7820                                 short_channel_id.write(writer)?;
7821                                 (pending_forwards.len() as u64).write(writer)?;
7822                                 for forward in pending_forwards {
7823                                         forward.write(writer)?;
7824                                 }
7825                         }
7826                 }
7827
7828                 let per_peer_state = self.per_peer_state.write().unwrap();
7829
7830                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
7831                 let claimable_payments = self.claimable_payments.lock().unwrap();
7832                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
7833
7834                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
7835                 let mut htlc_onion_fields: Vec<&_> = Vec::new();
7836                 (claimable_payments.claimable_payments.len() as u64).write(writer)?;
7837                 for (payment_hash, payment) in claimable_payments.claimable_payments.iter() {
7838                         payment_hash.write(writer)?;
7839                         (payment.htlcs.len() as u64).write(writer)?;
7840                         for htlc in payment.htlcs.iter() {
7841                                 htlc.write(writer)?;
7842                         }
7843                         htlc_purposes.push(&payment.purpose);
7844                         htlc_onion_fields.push(&payment.onion_fields);
7845                 }
7846
7847                 let mut monitor_update_blocked_actions_per_peer = None;
7848                 let mut peer_states = Vec::new();
7849                 for (_, peer_state_mutex) in per_peer_state.iter() {
7850                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
7851                         // of a lockorder violation deadlock - no other thread can be holding any
7852                         // per_peer_state lock at all.
7853                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
7854                 }
7855
7856                 (serializable_peer_count).write(writer)?;
7857                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
7858                         // Peers which we have no channels to should be dropped once disconnected. As we
7859                         // disconnect all peers when shutting down and serializing the ChannelManager, we
7860                         // consider all peers as disconnected here. There's therefore no need write peers with
7861                         // no channels.
7862                         if !peer_state.ok_to_remove(false) {
7863                                 peer_pubkey.write(writer)?;
7864                                 peer_state.latest_features.write(writer)?;
7865                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
7866                                         monitor_update_blocked_actions_per_peer
7867                                                 .get_or_insert_with(Vec::new)
7868                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
7869                                 }
7870                         }
7871                 }
7872
7873                 let events = self.pending_events.lock().unwrap();
7874                 // LDK versions prior to 0.0.115 don't support post-event actions, thus if there's no
7875                 // actions at all, skip writing the required TLV. Otherwise, pre-0.0.115 versions will
7876                 // refuse to read the new ChannelManager.
7877                 let events_not_backwards_compatible = events.iter().any(|(_, action)| action.is_some());
7878                 if events_not_backwards_compatible {
7879                         // If we're gonna write a even TLV that will overwrite our events anyway we might as
7880                         // well save the space and not write any events here.
7881                         0u64.write(writer)?;
7882                 } else {
7883                         (events.len() as u64).write(writer)?;
7884                         for (event, _) in events.iter() {
7885                                 event.write(writer)?;
7886                         }
7887                 }
7888
7889                 // LDK versions prior to 0.0.116 wrote the `pending_background_events`
7890                 // `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
7891                 // the closing monitor updates were always effectively replayed on startup (either directly
7892                 // by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
7893                 // deserialization or, in 0.0.115, by regenerating the monitor update itself).
7894                 0u64.write(writer)?;
7895
7896                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
7897                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
7898                 // likely to be identical.
7899                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
7900                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
7901
7902                 (pending_inbound_payments.len() as u64).write(writer)?;
7903                 for (hash, pending_payment) in pending_inbound_payments.iter() {
7904                         hash.write(writer)?;
7905                         pending_payment.write(writer)?;
7906                 }
7907
7908                 // For backwards compat, write the session privs and their total length.
7909                 let mut num_pending_outbounds_compat: u64 = 0;
7910                 for (_, outbound) in pending_outbound_payments.iter() {
7911                         if !outbound.is_fulfilled() && !outbound.abandoned() {
7912                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
7913                         }
7914                 }
7915                 num_pending_outbounds_compat.write(writer)?;
7916                 for (_, outbound) in pending_outbound_payments.iter() {
7917                         match outbound {
7918                                 PendingOutboundPayment::Legacy { session_privs } |
7919                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
7920                                         for session_priv in session_privs.iter() {
7921                                                 session_priv.write(writer)?;
7922                                         }
7923                                 }
7924                                 PendingOutboundPayment::Fulfilled { .. } => {},
7925                                 PendingOutboundPayment::Abandoned { .. } => {},
7926                         }
7927                 }
7928
7929                 // Encode without retry info for 0.0.101 compatibility.
7930                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
7931                 for (id, outbound) in pending_outbound_payments.iter() {
7932                         match outbound {
7933                                 PendingOutboundPayment::Legacy { session_privs } |
7934                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
7935                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
7936                                 },
7937                                 _ => {},
7938                         }
7939                 }
7940
7941                 let mut pending_intercepted_htlcs = None;
7942                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
7943                 if our_pending_intercepts.len() != 0 {
7944                         pending_intercepted_htlcs = Some(our_pending_intercepts);
7945                 }
7946
7947                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
7948                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
7949                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
7950                         // map. Thus, if there are no entries we skip writing a TLV for it.
7951                         pending_claiming_payments = None;
7952                 }
7953
7954                 let mut in_flight_monitor_updates: Option<HashMap<(&PublicKey, &OutPoint), &Vec<ChannelMonitorUpdate>>> = None;
7955                 for ((counterparty_id, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
7956                         for (funding_outpoint, updates) in peer_state.in_flight_monitor_updates.iter() {
7957                                 if !updates.is_empty() {
7958                                         if in_flight_monitor_updates.is_none() { in_flight_monitor_updates = Some(HashMap::new()); }
7959                                         in_flight_monitor_updates.as_mut().unwrap().insert((counterparty_id, funding_outpoint), updates);
7960                                 }
7961                         }
7962                 }
7963
7964                 write_tlv_fields!(writer, {
7965                         (1, pending_outbound_payments_no_retry, required),
7966                         (2, pending_intercepted_htlcs, option),
7967                         (3, pending_outbound_payments, required),
7968                         (4, pending_claiming_payments, option),
7969                         (5, self.our_network_pubkey, required),
7970                         (6, monitor_update_blocked_actions_per_peer, option),
7971                         (7, self.fake_scid_rand_bytes, required),
7972                         (8, if events_not_backwards_compatible { Some(&*events) } else { None }, option),
7973                         (9, htlc_purposes, vec_type),
7974                         (10, in_flight_monitor_updates, option),
7975                         (11, self.probing_cookie_secret, required),
7976                         (13, htlc_onion_fields, optional_vec),
7977                 });
7978
7979                 Ok(())
7980         }
7981 }
7982
7983 impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
7984         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
7985                 (self.len() as u64).write(w)?;
7986                 for (event, action) in self.iter() {
7987                         event.write(w)?;
7988                         action.write(w)?;
7989                         #[cfg(debug_assertions)] {
7990                                 // Events are MaybeReadable, in some cases indicating that they shouldn't actually
7991                                 // be persisted and are regenerated on restart. However, if such an event has a
7992                                 // post-event-handling action we'll write nothing for the event and would have to
7993                                 // either forget the action or fail on deserialization (which we do below). Thus,
7994                                 // check that the event is sane here.
7995                                 let event_encoded = event.encode();
7996                                 let event_read: Option<Event> =
7997                                         MaybeReadable::read(&mut &event_encoded[..]).unwrap();
7998                                 if action.is_some() { assert!(event_read.is_some()); }
7999                         }
8000                 }
8001                 Ok(())
8002         }
8003 }
8004 impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
8005         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8006                 let len: u64 = Readable::read(reader)?;
8007                 const MAX_ALLOC_SIZE: u64 = 1024 * 16;
8008                 let mut events: Self = VecDeque::with_capacity(cmp::min(
8009                         MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
8010                         len) as usize);
8011                 for _ in 0..len {
8012                         let ev_opt = MaybeReadable::read(reader)?;
8013                         let action = Readable::read(reader)?;
8014                         if let Some(ev) = ev_opt {
8015                                 events.push_back((ev, action));
8016                         } else if action.is_some() {
8017                                 return Err(DecodeError::InvalidValue);
8018                         }
8019                 }
8020                 Ok(events)
8021         }
8022 }
8023
8024 impl_writeable_tlv_based_enum!(ChannelShutdownState,
8025         (0, NotShuttingDown) => {},
8026         (2, ShutdownInitiated) => {},
8027         (4, ResolvingHTLCs) => {},
8028         (6, NegotiatingClosingFee) => {},
8029         (8, ShutdownComplete) => {}, ;
8030 );
8031
8032 /// Arguments for the creation of a ChannelManager that are not deserialized.
8033 ///
8034 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
8035 /// is:
8036 /// 1) Deserialize all stored [`ChannelMonitor`]s.
8037 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
8038 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
8039 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
8040 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
8041 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
8042 ///    same way you would handle a [`chain::Filter`] call using
8043 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
8044 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
8045 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
8046 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
8047 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
8048 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
8049 ///    the next step.
8050 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
8051 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
8052 ///
8053 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
8054 /// call any other methods on the newly-deserialized [`ChannelManager`].
8055 ///
8056 /// Note that because some channels may be closed during deserialization, it is critical that you
8057 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
8058 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
8059 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
8060 /// not force-close the same channels but consider them live), you may end up revoking a state for
8061 /// which you've already broadcasted the transaction.
8062 ///
8063 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
8064 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8065 where
8066         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8067         T::Target: BroadcasterInterface,
8068         ES::Target: EntropySource,
8069         NS::Target: NodeSigner,
8070         SP::Target: SignerProvider,
8071         F::Target: FeeEstimator,
8072         R::Target: Router,
8073         L::Target: Logger,
8074 {
8075         /// A cryptographically secure source of entropy.
8076         pub entropy_source: ES,
8077
8078         /// A signer that is able to perform node-scoped cryptographic operations.
8079         pub node_signer: NS,
8080
8081         /// The keys provider which will give us relevant keys. Some keys will be loaded during
8082         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
8083         /// signing data.
8084         pub signer_provider: SP,
8085
8086         /// The fee_estimator for use in the ChannelManager in the future.
8087         ///
8088         /// No calls to the FeeEstimator will be made during deserialization.
8089         pub fee_estimator: F,
8090         /// The chain::Watch for use in the ChannelManager in the future.
8091         ///
8092         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
8093         /// you have deserialized ChannelMonitors separately and will add them to your
8094         /// chain::Watch after deserializing this ChannelManager.
8095         pub chain_monitor: M,
8096
8097         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
8098         /// used to broadcast the latest local commitment transactions of channels which must be
8099         /// force-closed during deserialization.
8100         pub tx_broadcaster: T,
8101         /// The router which will be used in the ChannelManager in the future for finding routes
8102         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
8103         ///
8104         /// No calls to the router will be made during deserialization.
8105         pub router: R,
8106         /// The Logger for use in the ChannelManager and which may be used to log information during
8107         /// deserialization.
8108         pub logger: L,
8109         /// Default settings used for new channels. Any existing channels will continue to use the
8110         /// runtime settings which were stored when the ChannelManager was serialized.
8111         pub default_config: UserConfig,
8112
8113         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
8114         /// value.context.get_funding_txo() should be the key).
8115         ///
8116         /// If a monitor is inconsistent with the channel state during deserialization the channel will
8117         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
8118         /// is true for missing channels as well. If there is a monitor missing for which we find
8119         /// channel data Err(DecodeError::InvalidValue) will be returned.
8120         ///
8121         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
8122         /// this struct.
8123         ///
8124         /// This is not exported to bindings users because we have no HashMap bindings
8125         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>,
8126 }
8127
8128 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8129                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
8130 where
8131         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8132         T::Target: BroadcasterInterface,
8133         ES::Target: EntropySource,
8134         NS::Target: NodeSigner,
8135         SP::Target: SignerProvider,
8136         F::Target: FeeEstimator,
8137         R::Target: Router,
8138         L::Target: Logger,
8139 {
8140         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
8141         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
8142         /// populate a HashMap directly from C.
8143         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,
8144                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>) -> Self {
8145                 Self {
8146                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
8147                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
8148                 }
8149         }
8150 }
8151
8152 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
8153 // SipmleArcChannelManager type:
8154 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8155         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
8156 where
8157         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8158         T::Target: BroadcasterInterface,
8159         ES::Target: EntropySource,
8160         NS::Target: NodeSigner,
8161         SP::Target: SignerProvider,
8162         F::Target: FeeEstimator,
8163         R::Target: Router,
8164         L::Target: Logger,
8165 {
8166         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
8167                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
8168                 Ok((blockhash, Arc::new(chan_manager)))
8169         }
8170 }
8171
8172 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8173         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
8174 where
8175         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8176         T::Target: BroadcasterInterface,
8177         ES::Target: EntropySource,
8178         NS::Target: NodeSigner,
8179         SP::Target: SignerProvider,
8180         F::Target: FeeEstimator,
8181         R::Target: Router,
8182         L::Target: Logger,
8183 {
8184         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
8185                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
8186
8187                 let genesis_hash: BlockHash = Readable::read(reader)?;
8188                 let best_block_height: u32 = Readable::read(reader)?;
8189                 let best_block_hash: BlockHash = Readable::read(reader)?;
8190
8191                 let mut failed_htlcs = Vec::new();
8192
8193                 let channel_count: u64 = Readable::read(reader)?;
8194                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
8195                 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));
8196                 let mut id_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
8197                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
8198                 let mut channel_closures = VecDeque::new();
8199                 let mut close_background_events = Vec::new();
8200                 for _ in 0..channel_count {
8201                         let mut channel: Channel<<SP::Target as SignerProvider>::Signer> = Channel::read(reader, (
8202                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
8203                         ))?;
8204                         let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
8205                         funding_txo_set.insert(funding_txo.clone());
8206                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
8207                                 if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
8208                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
8209                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
8210                                                 channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
8211                                         // But if the channel is behind of the monitor, close the channel:
8212                                         log_error!(args.logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
8213                                         log_error!(args.logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
8214                                         log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
8215                                                 log_bytes!(channel.context.channel_id()), monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id());
8216                                         let (monitor_update, mut new_failed_htlcs) = channel.context.force_shutdown(true);
8217                                         if let Some((counterparty_node_id, funding_txo, update)) = monitor_update {
8218                                                 close_background_events.push(BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
8219                                                         counterparty_node_id, funding_txo, update
8220                                                 });
8221                                         }
8222                                         failed_htlcs.append(&mut new_failed_htlcs);
8223                                         channel_closures.push_back((events::Event::ChannelClosed {
8224                                                 channel_id: channel.context.channel_id(),
8225                                                 user_channel_id: channel.context.get_user_id(),
8226                                                 reason: ClosureReason::OutdatedChannelManager
8227                                         }, None));
8228                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
8229                                                 let mut found_htlc = false;
8230                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
8231                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
8232                                                 }
8233                                                 if !found_htlc {
8234                                                         // If we have some HTLCs in the channel which are not present in the newer
8235                                                         // ChannelMonitor, they have been removed and should be failed back to
8236                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
8237                                                         // were actually claimed we'd have generated and ensured the previous-hop
8238                                                         // claim update ChannelMonitor updates were persisted prior to persising
8239                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
8240                                                         // backwards leg of the HTLC will simply be rejected.
8241                                                         log_info!(args.logger,
8242                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
8243                                                                 log_bytes!(channel.context.channel_id()), log_bytes!(payment_hash.0));
8244                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.context.get_counterparty_node_id(), channel.context.channel_id()));
8245                                                 }
8246                                         }
8247                                 } else {
8248                                         log_info!(args.logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
8249                                                 log_bytes!(channel.context.channel_id()), channel.context.get_latest_monitor_update_id(),
8250                                                 monitor.get_latest_update_id());
8251                                         if let Some(short_channel_id) = channel.context.get_short_channel_id() {
8252                                                 short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
8253                                         }
8254                                         if channel.context.is_funding_initiated() {
8255                                                 id_to_peer.insert(channel.context.channel_id(), channel.context.get_counterparty_node_id());
8256                                         }
8257                                         match peer_channels.entry(channel.context.get_counterparty_node_id()) {
8258                                                 hash_map::Entry::Occupied(mut entry) => {
8259                                                         let by_id_map = entry.get_mut();
8260                                                         by_id_map.insert(channel.context.channel_id(), channel);
8261                                                 },
8262                                                 hash_map::Entry::Vacant(entry) => {
8263                                                         let mut by_id_map = HashMap::new();
8264                                                         by_id_map.insert(channel.context.channel_id(), channel);
8265                                                         entry.insert(by_id_map);
8266                                                 }
8267                                         }
8268                                 }
8269                         } else if channel.is_awaiting_initial_mon_persist() {
8270                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
8271                                 // was in-progress, we never broadcasted the funding transaction and can still
8272                                 // safely discard the channel.
8273                                 let _ = channel.context.force_shutdown(false);
8274                                 channel_closures.push_back((events::Event::ChannelClosed {
8275                                         channel_id: channel.context.channel_id(),
8276                                         user_channel_id: channel.context.get_user_id(),
8277                                         reason: ClosureReason::DisconnectedPeer,
8278                                 }, None));
8279                         } else {
8280                                 log_error!(args.logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", log_bytes!(channel.context.channel_id()));
8281                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
8282                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
8283                                 log_error!(args.logger, " Without the ChannelMonitor we cannot continue without risking funds.");
8284                                 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");
8285                                 return Err(DecodeError::InvalidValue);
8286                         }
8287                 }
8288
8289                 for (funding_txo, _) in args.channel_monitors.iter() {
8290                         if !funding_txo_set.contains(funding_txo) {
8291                                 log_info!(args.logger, "Queueing monitor update to ensure missing channel {} is force closed",
8292                                         log_bytes!(funding_txo.to_channel_id()));
8293                                 let monitor_update = ChannelMonitorUpdate {
8294                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
8295                                         updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast: true }],
8296                                 };
8297                                 close_background_events.push(BackgroundEvent::ClosingMonitorUpdateRegeneratedOnStartup((*funding_txo, monitor_update)));
8298                         }
8299                 }
8300
8301                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
8302                 let forward_htlcs_count: u64 = Readable::read(reader)?;
8303                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
8304                 for _ in 0..forward_htlcs_count {
8305                         let short_channel_id = Readable::read(reader)?;
8306                         let pending_forwards_count: u64 = Readable::read(reader)?;
8307                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
8308                         for _ in 0..pending_forwards_count {
8309                                 pending_forwards.push(Readable::read(reader)?);
8310                         }
8311                         forward_htlcs.insert(short_channel_id, pending_forwards);
8312                 }
8313
8314                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
8315                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
8316                 for _ in 0..claimable_htlcs_count {
8317                         let payment_hash = Readable::read(reader)?;
8318                         let previous_hops_len: u64 = Readable::read(reader)?;
8319                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
8320                         for _ in 0..previous_hops_len {
8321                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
8322                         }
8323                         claimable_htlcs_list.push((payment_hash, previous_hops));
8324                 }
8325
8326                 let peer_state_from_chans = |channel_by_id| {
8327                         PeerState {
8328                                 channel_by_id,
8329                                 outbound_v1_channel_by_id: HashMap::new(),
8330                                 inbound_v1_channel_by_id: HashMap::new(),
8331                                 latest_features: InitFeatures::empty(),
8332                                 pending_msg_events: Vec::new(),
8333                                 in_flight_monitor_updates: BTreeMap::new(),
8334                                 monitor_update_blocked_actions: BTreeMap::new(),
8335                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
8336                                 is_connected: false,
8337                         }
8338                 };
8339
8340                 let peer_count: u64 = Readable::read(reader)?;
8341                 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>>)>()));
8342                 for _ in 0..peer_count {
8343                         let peer_pubkey = Readable::read(reader)?;
8344                         let peer_chans = peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new());
8345                         let mut peer_state = peer_state_from_chans(peer_chans);
8346                         peer_state.latest_features = Readable::read(reader)?;
8347                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
8348                 }
8349
8350                 let event_count: u64 = Readable::read(reader)?;
8351                 let mut pending_events_read: VecDeque<(events::Event, Option<EventCompletionAction>)> =
8352                         VecDeque::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>()));
8353                 for _ in 0..event_count {
8354                         match MaybeReadable::read(reader)? {
8355                                 Some(event) => pending_events_read.push_back((event, None)),
8356                                 None => continue,
8357                         }
8358                 }
8359
8360                 let background_event_count: u64 = Readable::read(reader)?;
8361                 for _ in 0..background_event_count {
8362                         match <u8 as Readable>::read(reader)? {
8363                                 0 => {
8364                                         // LDK versions prior to 0.0.116 wrote pending `MonitorUpdateRegeneratedOnStartup`s here,
8365                                         // however we really don't (and never did) need them - we regenerate all
8366                                         // on-startup monitor updates.
8367                                         let _: OutPoint = Readable::read(reader)?;
8368                                         let _: ChannelMonitorUpdate = Readable::read(reader)?;
8369                                 }
8370                                 _ => return Err(DecodeError::InvalidValue),
8371                         }
8372                 }
8373
8374                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
8375                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
8376
8377                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
8378                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
8379                 for _ in 0..pending_inbound_payment_count {
8380                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
8381                                 return Err(DecodeError::InvalidValue);
8382                         }
8383                 }
8384
8385                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
8386                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
8387                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
8388                 for _ in 0..pending_outbound_payments_count_compat {
8389                         let session_priv = Readable::read(reader)?;
8390                         let payment = PendingOutboundPayment::Legacy {
8391                                 session_privs: [session_priv].iter().cloned().collect()
8392                         };
8393                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
8394                                 return Err(DecodeError::InvalidValue)
8395                         };
8396                 }
8397
8398                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
8399                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
8400                 let mut pending_outbound_payments = None;
8401                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
8402                 let mut received_network_pubkey: Option<PublicKey> = None;
8403                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
8404                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
8405                 let mut claimable_htlc_purposes = None;
8406                 let mut claimable_htlc_onion_fields = None;
8407                 let mut pending_claiming_payments = Some(HashMap::new());
8408                 let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
8409                 let mut events_override = None;
8410                 let mut in_flight_monitor_updates: Option<HashMap<(PublicKey, OutPoint), Vec<ChannelMonitorUpdate>>> = None;
8411                 read_tlv_fields!(reader, {
8412                         (1, pending_outbound_payments_no_retry, option),
8413                         (2, pending_intercepted_htlcs, option),
8414                         (3, pending_outbound_payments, option),
8415                         (4, pending_claiming_payments, option),
8416                         (5, received_network_pubkey, option),
8417                         (6, monitor_update_blocked_actions_per_peer, option),
8418                         (7, fake_scid_rand_bytes, option),
8419                         (8, events_override, option),
8420                         (9, claimable_htlc_purposes, vec_type),
8421                         (10, in_flight_monitor_updates, option),
8422                         (11, probing_cookie_secret, option),
8423                         (13, claimable_htlc_onion_fields, optional_vec),
8424                 });
8425                 if fake_scid_rand_bytes.is_none() {
8426                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
8427                 }
8428
8429                 if probing_cookie_secret.is_none() {
8430                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
8431                 }
8432
8433                 if let Some(events) = events_override {
8434                         pending_events_read = events;
8435                 }
8436
8437                 if !channel_closures.is_empty() {
8438                         pending_events_read.append(&mut channel_closures);
8439                 }
8440
8441                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
8442                         pending_outbound_payments = Some(pending_outbound_payments_compat);
8443                 } else if pending_outbound_payments.is_none() {
8444                         let mut outbounds = HashMap::new();
8445                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
8446                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
8447                         }
8448                         pending_outbound_payments = Some(outbounds);
8449                 }
8450                 let pending_outbounds = OutboundPayments {
8451                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
8452                         retry_lock: Mutex::new(())
8453                 };
8454
8455                 // We have to replay (or skip, if they were completed after we wrote the `ChannelManager`)
8456                 // each `ChannelMonitorUpdate` in `in_flight_monitor_updates`. After doing so, we have to
8457                 // check that each channel we have isn't newer than the latest `ChannelMonitorUpdate`(s) we
8458                 // replayed, and for each monitor update we have to replay we have to ensure there's a
8459                 // `ChannelMonitor` for it.
8460                 //
8461                 // In order to do so we first walk all of our live channels (so that we can check their
8462                 // state immediately after doing the update replays, when we have the `update_id`s
8463                 // available) and then walk any remaining in-flight updates.
8464                 //
8465                 // Because the actual handling of the in-flight updates is the same, it's macro'ized here:
8466                 let mut pending_background_events = Vec::new();
8467                 macro_rules! handle_in_flight_updates {
8468                         ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $funding_txo: expr,
8469                          $monitor: expr, $peer_state: expr, $channel_info_log: expr
8470                         ) => { {
8471                                 let mut max_in_flight_update_id = 0;
8472                                 $chan_in_flight_upds.retain(|upd| upd.update_id > $monitor.get_latest_update_id());
8473                                 for update in $chan_in_flight_upds.iter() {
8474                                         log_trace!(args.logger, "Replaying ChannelMonitorUpdate {} for {}channel {}",
8475                                                 update.update_id, $channel_info_log, log_bytes!($funding_txo.to_channel_id()));
8476                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id);
8477                                         pending_background_events.push(
8478                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
8479                                                         counterparty_node_id: $counterparty_node_id,
8480                                                         funding_txo: $funding_txo,
8481                                                         update: update.clone(),
8482                                                 });
8483                                 }
8484                                 if $peer_state.in_flight_monitor_updates.insert($funding_txo, $chan_in_flight_upds).is_some() {
8485                                         log_error!(args.logger, "Duplicate in-flight monitor update set for the same channel!");
8486                                         return Err(DecodeError::InvalidValue);
8487                                 }
8488                                 max_in_flight_update_id
8489                         } }
8490                 }
8491
8492                 for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() {
8493                         let mut peer_state_lock = peer_state_mtx.lock().unwrap();
8494                         let peer_state = &mut *peer_state_lock;
8495                         for (_, chan) in peer_state.channel_by_id.iter() {
8496                                 // Channels that were persisted have to be funded, otherwise they should have been
8497                                 // discarded.
8498                                 let funding_txo = chan.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
8499                                 let monitor = args.channel_monitors.get(&funding_txo)
8500                                         .expect("We already checked for monitor presence when loading channels");
8501                                 let mut max_in_flight_update_id = monitor.get_latest_update_id();
8502                                 if let Some(in_flight_upds) = &mut in_flight_monitor_updates {
8503                                         if let Some(mut chan_in_flight_upds) = in_flight_upds.remove(&(*counterparty_id, funding_txo)) {
8504                                                 max_in_flight_update_id = cmp::max(max_in_flight_update_id,
8505                                                         handle_in_flight_updates!(*counterparty_id, chan_in_flight_upds,
8506                                                                 funding_txo, monitor, peer_state, ""));
8507                                         }
8508                                 }
8509                                 if chan.get_latest_unblocked_monitor_update_id() > max_in_flight_update_id {
8510                                         // If the channel is ahead of the monitor, return InvalidValue:
8511                                         log_error!(args.logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
8512                                         log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} with update_id through {} in-flight",
8513                                                 log_bytes!(chan.context.channel_id()), monitor.get_latest_update_id(), max_in_flight_update_id);
8514                                         log_error!(args.logger, " but the ChannelManager is at update_id {}.", chan.get_latest_unblocked_monitor_update_id());
8515                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
8516                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
8517                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
8518                                         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");
8519                                         return Err(DecodeError::InvalidValue);
8520                                 }
8521                         }
8522                 }
8523
8524                 if let Some(in_flight_upds) = in_flight_monitor_updates {
8525                         for ((counterparty_id, funding_txo), mut chan_in_flight_updates) in in_flight_upds {
8526                                 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
8527                                         // Now that we've removed all the in-flight monitor updates for channels that are
8528                                         // still open, we need to replay any monitor updates that are for closed channels,
8529                                         // creating the neccessary peer_state entries as we go.
8530                                         let peer_state_mutex = per_peer_state.entry(counterparty_id).or_insert_with(|| {
8531                                                 Mutex::new(peer_state_from_chans(HashMap::new()))
8532                                         });
8533                                         let mut peer_state = peer_state_mutex.lock().unwrap();
8534                                         handle_in_flight_updates!(counterparty_id, chan_in_flight_updates,
8535                                                 funding_txo, monitor, peer_state, "closed ");
8536                                 } else {
8537                                         log_error!(args.logger, "A ChannelMonitor is missing even though we have in-flight updates for it! This indicates a potentially-critical violation of the chain::Watch API!");
8538                                         log_error!(args.logger, " The ChannelMonitor for channel {} is missing.",
8539                                                 log_bytes!(funding_txo.to_channel_id()));
8540                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
8541                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
8542                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
8543                                         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");
8544                                         return Err(DecodeError::InvalidValue);
8545                                 }
8546                         }
8547                 }
8548
8549                 // Note that we have to do the above replays before we push new monitor updates.
8550                 pending_background_events.append(&mut close_background_events);
8551
8552                 {
8553                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
8554                         // ChannelMonitor data for any channels for which we do not have authorative state
8555                         // (i.e. those for which we just force-closed above or we otherwise don't have a
8556                         // corresponding `Channel` at all).
8557                         // This avoids several edge-cases where we would otherwise "forget" about pending
8558                         // payments which are still in-flight via their on-chain state.
8559                         // We only rebuild the pending payments map if we were most recently serialized by
8560                         // 0.0.102+
8561                         for (_, monitor) in args.channel_monitors.iter() {
8562                                 if id_to_peer.get(&monitor.get_funding_txo().0.to_channel_id()).is_none() {
8563                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
8564                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } = htlc_source {
8565                                                         if path.hops.is_empty() {
8566                                                                 log_error!(args.logger, "Got an empty path for a pending payment");
8567                                                                 return Err(DecodeError::InvalidValue);
8568                                                         }
8569
8570                                                         let path_amt = path.final_value_msat();
8571                                                         let mut session_priv_bytes = [0; 32];
8572                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
8573                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
8574                                                                 hash_map::Entry::Occupied(mut entry) => {
8575                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
8576                                                                         log_info!(args.logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
8577                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), log_bytes!(htlc.payment_hash.0));
8578                                                                 },
8579                                                                 hash_map::Entry::Vacant(entry) => {
8580                                                                         let path_fee = path.fee_msat();
8581                                                                         entry.insert(PendingOutboundPayment::Retryable {
8582                                                                                 retry_strategy: None,
8583                                                                                 attempts: PaymentAttempts::new(),
8584                                                                                 payment_params: None,
8585                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
8586                                                                                 payment_hash: htlc.payment_hash,
8587                                                                                 payment_secret: None, // only used for retries, and we'll never retry on startup
8588                                                                                 payment_metadata: None, // only used for retries, and we'll never retry on startup
8589                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
8590                                                                                 pending_amt_msat: path_amt,
8591                                                                                 pending_fee_msat: Some(path_fee),
8592                                                                                 total_msat: path_amt,
8593                                                                                 starting_block_height: best_block_height,
8594                                                                         });
8595                                                                         log_info!(args.logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
8596                                                                                 path_amt, log_bytes!(htlc.payment_hash.0),  log_bytes!(session_priv_bytes));
8597                                                                 }
8598                                                         }
8599                                                 }
8600                                         }
8601                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
8602                                                 match htlc_source {
8603                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
8604                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
8605                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
8606                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
8607                                                                 };
8608                                                                 // The ChannelMonitor is now responsible for this HTLC's
8609                                                                 // failure/success and will let us know what its outcome is. If we
8610                                                                 // still have an entry for this HTLC in `forward_htlcs` or
8611                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
8612                                                                 // the monitor was when forwarding the payment.
8613                                                                 forward_htlcs.retain(|_, forwards| {
8614                                                                         forwards.retain(|forward| {
8615                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
8616                                                                                         if pending_forward_matches_htlc(&htlc_info) {
8617                                                                                                 log_info!(args.logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
8618                                                                                                         log_bytes!(htlc.payment_hash.0), log_bytes!(monitor.get_funding_txo().0.to_channel_id()));
8619                                                                                                 false
8620                                                                                         } else { true }
8621                                                                                 } else { true }
8622                                                                         });
8623                                                                         !forwards.is_empty()
8624                                                                 });
8625                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
8626                                                                         if pending_forward_matches_htlc(&htlc_info) {
8627                                                                                 log_info!(args.logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
8628                                                                                         log_bytes!(htlc.payment_hash.0), log_bytes!(monitor.get_funding_txo().0.to_channel_id()));
8629                                                                                 pending_events_read.retain(|(event, _)| {
8630                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
8631                                                                                                 intercepted_id != ev_id
8632                                                                                         } else { true }
8633                                                                                 });
8634                                                                                 false
8635                                                                         } else { true }
8636                                                                 });
8637                                                         },
8638                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
8639                                                                 if let Some(preimage) = preimage_opt {
8640                                                                         let pending_events = Mutex::new(pending_events_read);
8641                                                                         // Note that we set `from_onchain` to "false" here,
8642                                                                         // deliberately keeping the pending payment around forever.
8643                                                                         // Given it should only occur when we have a channel we're
8644                                                                         // force-closing for being stale that's okay.
8645                                                                         // The alternative would be to wipe the state when claiming,
8646                                                                         // generating a `PaymentPathSuccessful` event but regenerating
8647                                                                         // it and the `PaymentSent` on every restart until the
8648                                                                         // `ChannelMonitor` is removed.
8649                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv, path, false, &pending_events, &args.logger);
8650                                                                         pending_events_read = pending_events.into_inner().unwrap();
8651                                                                 }
8652                                                         },
8653                                                 }
8654                                         }
8655                                 }
8656                         }
8657                 }
8658
8659                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
8660                         // If we have pending HTLCs to forward, assume we either dropped a
8661                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
8662                         // shut down before the timer hit. Either way, set the time_forwardable to a small
8663                         // constant as enough time has likely passed that we should simply handle the forwards
8664                         // now, or at least after the user gets a chance to reconnect to our peers.
8665                         pending_events_read.push_back((events::Event::PendingHTLCsForwardable {
8666                                 time_forwardable: Duration::from_secs(2),
8667                         }, None));
8668                 }
8669
8670                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
8671                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
8672
8673                 let mut claimable_payments = HashMap::with_capacity(claimable_htlcs_list.len());
8674                 if let Some(purposes) = claimable_htlc_purposes {
8675                         if purposes.len() != claimable_htlcs_list.len() {
8676                                 return Err(DecodeError::InvalidValue);
8677                         }
8678                         if let Some(onion_fields) = claimable_htlc_onion_fields {
8679                                 if onion_fields.len() != claimable_htlcs_list.len() {
8680                                         return Err(DecodeError::InvalidValue);
8681                                 }
8682                                 for (purpose, (onion, (payment_hash, htlcs))) in
8683                                         purposes.into_iter().zip(onion_fields.into_iter().zip(claimable_htlcs_list.into_iter()))
8684                                 {
8685                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
8686                                                 purpose, htlcs, onion_fields: onion,
8687                                         });
8688                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
8689                                 }
8690                         } else {
8691                                 for (purpose, (payment_hash, htlcs)) in purposes.into_iter().zip(claimable_htlcs_list.into_iter()) {
8692                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
8693                                                 purpose, htlcs, onion_fields: None,
8694                                         });
8695                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
8696                                 }
8697                         }
8698                 } else {
8699                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
8700                         // include a `_legacy_hop_data` in the `OnionPayload`.
8701                         for (payment_hash, htlcs) in claimable_htlcs_list.drain(..) {
8702                                 if htlcs.is_empty() {
8703                                         return Err(DecodeError::InvalidValue);
8704                                 }
8705                                 let purpose = match &htlcs[0].onion_payload {
8706                                         OnionPayload::Invoice { _legacy_hop_data } => {
8707                                                 if let Some(hop_data) = _legacy_hop_data {
8708                                                         events::PaymentPurpose::InvoicePayment {
8709                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
8710                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
8711                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
8712                                                                                 Ok((payment_preimage, _)) => payment_preimage,
8713                                                                                 Err(()) => {
8714                                                                                         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));
8715                                                                                         return Err(DecodeError::InvalidValue);
8716                                                                                 }
8717                                                                         }
8718                                                                 },
8719                                                                 payment_secret: hop_data.payment_secret,
8720                                                         }
8721                                                 } else { return Err(DecodeError::InvalidValue); }
8722                                         },
8723                                         OnionPayload::Spontaneous(payment_preimage) =>
8724                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
8725                                 };
8726                                 claimable_payments.insert(payment_hash, ClaimablePayment {
8727                                         purpose, htlcs, onion_fields: None,
8728                                 });
8729                         }
8730                 }
8731
8732                 let mut secp_ctx = Secp256k1::new();
8733                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
8734
8735                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
8736                         Ok(key) => key,
8737                         Err(()) => return Err(DecodeError::InvalidValue)
8738                 };
8739                 if let Some(network_pubkey) = received_network_pubkey {
8740                         if network_pubkey != our_network_pubkey {
8741                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
8742                                 return Err(DecodeError::InvalidValue);
8743                         }
8744                 }
8745
8746                 let mut outbound_scid_aliases = HashSet::new();
8747                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
8748                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8749                         let peer_state = &mut *peer_state_lock;
8750                         for (chan_id, chan) in peer_state.channel_by_id.iter_mut() {
8751                                 if chan.context.outbound_scid_alias() == 0 {
8752                                         let mut outbound_scid_alias;
8753                                         loop {
8754                                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias
8755                                                         .get_fake_scid(best_block_height, &genesis_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
8756                                                 if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
8757                                         }
8758                                         chan.context.set_outbound_scid_alias(outbound_scid_alias);
8759                                 } else if !outbound_scid_aliases.insert(chan.context.outbound_scid_alias()) {
8760                                         // Note that in rare cases its possible to hit this while reading an older
8761                                         // channel if we just happened to pick a colliding outbound alias above.
8762                                         log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
8763                                         return Err(DecodeError::InvalidValue);
8764                                 }
8765                                 if chan.context.is_usable() {
8766                                         if short_to_chan_info.insert(chan.context.outbound_scid_alias(), (chan.context.get_counterparty_node_id(), *chan_id)).is_some() {
8767                                                 // Note that in rare cases its possible to hit this while reading an older
8768                                                 // channel if we just happened to pick a colliding outbound alias above.
8769                                                 log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
8770                                                 return Err(DecodeError::InvalidValue);
8771                                         }
8772                                 }
8773                         }
8774                 }
8775
8776                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
8777
8778                 for (_, monitor) in args.channel_monitors.iter() {
8779                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
8780                                 if let Some(payment) = claimable_payments.remove(&payment_hash) {
8781                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", log_bytes!(payment_hash.0));
8782                                         let mut claimable_amt_msat = 0;
8783                                         let mut receiver_node_id = Some(our_network_pubkey);
8784                                         let phantom_shared_secret = payment.htlcs[0].prev_hop.phantom_shared_secret;
8785                                         if phantom_shared_secret.is_some() {
8786                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
8787                                                         .expect("Failed to get node_id for phantom node recipient");
8788                                                 receiver_node_id = Some(phantom_pubkey)
8789                                         }
8790                                         for claimable_htlc in payment.htlcs {
8791                                                 claimable_amt_msat += claimable_htlc.value;
8792
8793                                                 // Add a holding-cell claim of the payment to the Channel, which should be
8794                                                 // applied ~immediately on peer reconnection. Because it won't generate a
8795                                                 // new commitment transaction we can just provide the payment preimage to
8796                                                 // the corresponding ChannelMonitor and nothing else.
8797                                                 //
8798                                                 // We do so directly instead of via the normal ChannelMonitor update
8799                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
8800                                                 // we're not allowed to call it directly yet. Further, we do the update
8801                                                 // without incrementing the ChannelMonitor update ID as there isn't any
8802                                                 // reason to.
8803                                                 // If we were to generate a new ChannelMonitor update ID here and then
8804                                                 // crash before the user finishes block connect we'd end up force-closing
8805                                                 // this channel as well. On the flip side, there's no harm in restarting
8806                                                 // without the new monitor persisted - we'll end up right back here on
8807                                                 // restart.
8808                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
8809                                                 if let Some(peer_node_id) = id_to_peer.get(&previous_channel_id){
8810                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
8811                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8812                                                         let peer_state = &mut *peer_state_lock;
8813                                                         if let Some(channel) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
8814                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &args.logger);
8815                                                         }
8816                                                 }
8817                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
8818                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
8819                                                 }
8820                                         }
8821                                         pending_events_read.push_back((events::Event::PaymentClaimed {
8822                                                 receiver_node_id,
8823                                                 payment_hash,
8824                                                 purpose: payment.purpose,
8825                                                 amount_msat: claimable_amt_msat,
8826                                         }, None));
8827                                 }
8828                         }
8829                 }
8830
8831                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
8832                         if let Some(peer_state) = per_peer_state.get(&node_id) {
8833                                 for (_, actions) in monitor_update_blocked_actions.iter() {
8834                                         for action in actions.iter() {
8835                                                 if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
8836                                                         downstream_counterparty_and_funding_outpoint:
8837                                                                 Some((blocked_node_id, blocked_channel_outpoint, blocking_action)), ..
8838                                                 } = action {
8839                                                         if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
8840                                                                 blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
8841                                                                         .entry(blocked_channel_outpoint.to_channel_id())
8842                                                                         .or_insert_with(Vec::new).push(blocking_action.clone());
8843                                                         }
8844                                                 }
8845                                         }
8846                                 }
8847                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
8848                         } else {
8849                                 log_error!(args.logger, "Got blocked actions without a per-peer-state for {}", node_id);
8850                                 return Err(DecodeError::InvalidValue);
8851                         }
8852                 }
8853
8854                 let channel_manager = ChannelManager {
8855                         genesis_hash,
8856                         fee_estimator: bounded_fee_estimator,
8857                         chain_monitor: args.chain_monitor,
8858                         tx_broadcaster: args.tx_broadcaster,
8859                         router: args.router,
8860
8861                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
8862
8863                         inbound_payment_key: expanded_inbound_key,
8864                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
8865                         pending_outbound_payments: pending_outbounds,
8866                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
8867
8868                         forward_htlcs: Mutex::new(forward_htlcs),
8869                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments, pending_claiming_payments: pending_claiming_payments.unwrap() }),
8870                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
8871                         id_to_peer: Mutex::new(id_to_peer),
8872                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
8873                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
8874
8875                         probing_cookie_secret: probing_cookie_secret.unwrap(),
8876
8877                         our_network_pubkey,
8878                         secp_ctx,
8879
8880                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
8881
8882                         per_peer_state: FairRwLock::new(per_peer_state),
8883
8884                         pending_events: Mutex::new(pending_events_read),
8885                         pending_events_processor: AtomicBool::new(false),
8886                         pending_background_events: Mutex::new(pending_background_events),
8887                         total_consistency_lock: RwLock::new(()),
8888                         #[cfg(debug_assertions)]
8889                         background_events_processed_since_startup: AtomicBool::new(false),
8890                         persistence_notifier: Notifier::new(),
8891
8892                         entropy_source: args.entropy_source,
8893                         node_signer: args.node_signer,
8894                         signer_provider: args.signer_provider,
8895
8896                         logger: args.logger,
8897                         default_configuration: args.default_config,
8898                 };
8899
8900                 for htlc_source in failed_htlcs.drain(..) {
8901                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
8902                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
8903                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
8904                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
8905                 }
8906
8907                 //TODO: Broadcast channel update for closed channels, but only after we've made a
8908                 //connection or two.
8909
8910                 Ok((best_block_hash.clone(), channel_manager))
8911         }
8912 }
8913
8914 #[cfg(test)]
8915 mod tests {
8916         use bitcoin::hashes::Hash;
8917         use bitcoin::hashes::sha256::Hash as Sha256;
8918         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8919         use core::sync::atomic::Ordering;
8920         use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
8921         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
8922         use crate::ln::channelmanager::{inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
8923         use crate::ln::functional_test_utils::*;
8924         use crate::ln::msgs::{self, ErrorAction};
8925         use crate::ln::msgs::ChannelMessageHandler;
8926         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
8927         use crate::util::errors::APIError;
8928         use crate::util::test_utils;
8929         use crate::util::config::{ChannelConfig, ChannelConfigUpdate};
8930         use crate::sign::EntropySource;
8931
8932         #[test]
8933         fn test_notify_limits() {
8934                 // Check that a few cases which don't require the persistence of a new ChannelManager,
8935                 // indeed, do not cause the persistence of a new ChannelManager.
8936                 let chanmon_cfgs = create_chanmon_cfgs(3);
8937                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8938                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8939                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8940
8941                 // All nodes start with a persistable update pending as `create_network` connects each node
8942                 // with all other nodes to make most tests simpler.
8943                 assert!(nodes[0].node.get_persistable_update_future().poll_is_complete());
8944                 assert!(nodes[1].node.get_persistable_update_future().poll_is_complete());
8945                 assert!(nodes[2].node.get_persistable_update_future().poll_is_complete());
8946
8947                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
8948
8949                 // We check that the channel info nodes have doesn't change too early, even though we try
8950                 // to connect messages with new values
8951                 chan.0.contents.fee_base_msat *= 2;
8952                 chan.1.contents.fee_base_msat *= 2;
8953                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
8954                         &nodes[1].node.get_our_node_id()).pop().unwrap();
8955                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
8956                         &nodes[0].node.get_our_node_id()).pop().unwrap();
8957
8958                 // The first two nodes (which opened a channel) should now require fresh persistence
8959                 assert!(nodes[0].node.get_persistable_update_future().poll_is_complete());
8960                 assert!(nodes[1].node.get_persistable_update_future().poll_is_complete());
8961                 // ... but the last node should not.
8962                 assert!(!nodes[2].node.get_persistable_update_future().poll_is_complete());
8963                 // After persisting the first two nodes they should no longer need fresh persistence.
8964                 assert!(!nodes[0].node.get_persistable_update_future().poll_is_complete());
8965                 assert!(!nodes[1].node.get_persistable_update_future().poll_is_complete());
8966
8967                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
8968                 // about the channel.
8969                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
8970                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
8971                 assert!(!nodes[2].node.get_persistable_update_future().poll_is_complete());
8972
8973                 // The nodes which are a party to the channel should also ignore messages from unrelated
8974                 // parties.
8975                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
8976                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
8977                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
8978                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
8979                 assert!(!nodes[0].node.get_persistable_update_future().poll_is_complete());
8980                 assert!(!nodes[1].node.get_persistable_update_future().poll_is_complete());
8981
8982                 // At this point the channel info given by peers should still be the same.
8983                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
8984                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
8985
8986                 // An earlier version of handle_channel_update didn't check the directionality of the
8987                 // update message and would always update the local fee info, even if our peer was
8988                 // (spuriously) forwarding us our own channel_update.
8989                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
8990                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
8991                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
8992
8993                 // First deliver each peers' own message, checking that the node doesn't need to be
8994                 // persisted and that its channel info remains the same.
8995                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
8996                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
8997                 assert!(!nodes[0].node.get_persistable_update_future().poll_is_complete());
8998                 assert!(!nodes[1].node.get_persistable_update_future().poll_is_complete());
8999                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
9000                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
9001
9002                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
9003                 // the channel info has updated.
9004                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
9005                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
9006                 assert!(nodes[0].node.get_persistable_update_future().poll_is_complete());
9007                 assert!(nodes[1].node.get_persistable_update_future().poll_is_complete());
9008                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
9009                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
9010         }
9011
9012         #[test]
9013         fn test_keysend_dup_hash_partial_mpp() {
9014                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
9015                 // expected.
9016                 let chanmon_cfgs = create_chanmon_cfgs(2);
9017                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9018                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9019                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9020                 create_announced_chan_between_nodes(&nodes, 0, 1);
9021
9022                 // First, send a partial MPP payment.
9023                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
9024                 let mut mpp_route = route.clone();
9025                 mpp_route.paths.push(mpp_route.paths[0].clone());
9026
9027                 let payment_id = PaymentId([42; 32]);
9028                 // Use the utility function send_payment_along_path to send the payment with MPP data which
9029                 // indicates there are more HTLCs coming.
9030                 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.
9031                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9032                         RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap();
9033                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash,
9034                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
9035                 check_added_monitors!(nodes[0], 1);
9036                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9037                 assert_eq!(events.len(), 1);
9038                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9039
9040                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
9041                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9042                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
9043                 check_added_monitors!(nodes[0], 1);
9044                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9045                 assert_eq!(events.len(), 1);
9046                 let ev = events.drain(..).next().unwrap();
9047                 let payment_event = SendEvent::from_event(ev);
9048                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9049                 check_added_monitors!(nodes[1], 0);
9050                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9051                 expect_pending_htlcs_forwardable!(nodes[1]);
9052                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9053                 check_added_monitors!(nodes[1], 1);
9054                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9055                 assert!(updates.update_add_htlcs.is_empty());
9056                 assert!(updates.update_fulfill_htlcs.is_empty());
9057                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9058                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9059                 assert!(updates.update_fee.is_none());
9060                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9061                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9062                 expect_payment_failed!(nodes[0], our_payment_hash, true);
9063
9064                 // Send the second half of the original MPP payment.
9065                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash,
9066                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9067                 check_added_monitors!(nodes[0], 1);
9068                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9069                 assert_eq!(events.len(), 1);
9070                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
9071
9072                 // Claim the full MPP payment. Note that we can't use a test utility like
9073                 // claim_funds_along_route because the ordering of the messages causes the second half of the
9074                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
9075                 // lightning messages manually.
9076                 nodes[1].node.claim_funds(payment_preimage);
9077                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
9078                 check_added_monitors!(nodes[1], 2);
9079
9080                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9081                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
9082                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
9083                 check_added_monitors!(nodes[0], 1);
9084                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9085                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
9086                 check_added_monitors!(nodes[1], 1);
9087                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9088                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
9089                 check_added_monitors!(nodes[1], 1);
9090                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
9091                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
9092                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
9093                 check_added_monitors!(nodes[0], 1);
9094                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
9095                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
9096                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9097                 check_added_monitors!(nodes[0], 1);
9098                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
9099                 check_added_monitors!(nodes[1], 1);
9100                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
9101                 check_added_monitors!(nodes[1], 1);
9102                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
9103                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
9104                 check_added_monitors!(nodes[0], 1);
9105
9106                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
9107                 // path's success and a PaymentPathSuccessful event for each path's success.
9108                 let events = nodes[0].node.get_and_clear_pending_events();
9109                 assert_eq!(events.len(), 3);
9110                 match events[0] {
9111                         Event::PaymentSent { payment_id: ref id, payment_preimage: ref preimage, payment_hash: ref hash, .. } => {
9112                                 assert_eq!(Some(payment_id), *id);
9113                                 assert_eq!(payment_preimage, *preimage);
9114                                 assert_eq!(our_payment_hash, *hash);
9115                         },
9116                         _ => panic!("Unexpected event"),
9117                 }
9118                 match events[1] {
9119                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
9120                                 assert_eq!(payment_id, *actual_payment_id);
9121                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
9122                                 assert_eq!(route.paths[0], *path);
9123                         },
9124                         _ => panic!("Unexpected event"),
9125                 }
9126                 match events[2] {
9127                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
9128                                 assert_eq!(payment_id, *actual_payment_id);
9129                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
9130                                 assert_eq!(route.paths[0], *path);
9131                         },
9132                         _ => panic!("Unexpected event"),
9133                 }
9134         }
9135
9136         #[test]
9137         fn test_keysend_dup_payment_hash() {
9138                 do_test_keysend_dup_payment_hash(false);
9139                 do_test_keysend_dup_payment_hash(true);
9140         }
9141
9142         fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) {
9143                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
9144                 //      outbound regular payment fails as expected.
9145                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
9146                 //      fails as expected.
9147                 // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend
9148                 //      payment fails as expected. When `accept_mpp_keysend` is false, this tests that we
9149                 //      reject MPP keysend payments, since in this case where the payment has no payment
9150                 //      secret, a keysend payment with a duplicate hash is basically an MPP keysend. If
9151                 //      `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with
9152                 //      payment secrets and reject otherwise.
9153                 let chanmon_cfgs = create_chanmon_cfgs(2);
9154                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9155                 let mut mpp_keysend_cfg = test_default_channel_config();
9156                 mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend;
9157                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]);
9158                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9159                 create_announced_chan_between_nodes(&nodes, 0, 1);
9160                 let scorer = test_utils::TestScorer::new();
9161                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9162
9163                 // To start (1), send a regular payment but don't claim it.
9164                 let expected_route = [&nodes[1]];
9165                 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &expected_route, 100_000);
9166
9167                 // Next, attempt a keysend payment and make sure it fails.
9168                 let route_params = RouteParameters {
9169                         payment_params: PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
9170                         final_value_msat: 100_000,
9171                 };
9172                 let route = find_route(
9173                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
9174                         None, nodes[0].logger, &scorer, &(), &random_seed_bytes
9175                 ).unwrap();
9176                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9177                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
9178                 check_added_monitors!(nodes[0], 1);
9179                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9180                 assert_eq!(events.len(), 1);
9181                 let ev = events.drain(..).next().unwrap();
9182                 let payment_event = SendEvent::from_event(ev);
9183                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9184                 check_added_monitors!(nodes[1], 0);
9185                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9186                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
9187                 // fails), the second will process the resulting failure and fail the HTLC backward
9188                 expect_pending_htlcs_forwardable!(nodes[1]);
9189                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9190                 check_added_monitors!(nodes[1], 1);
9191                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9192                 assert!(updates.update_add_htlcs.is_empty());
9193                 assert!(updates.update_fulfill_htlcs.is_empty());
9194                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9195                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9196                 assert!(updates.update_fee.is_none());
9197                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9198                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9199                 expect_payment_failed!(nodes[0], payment_hash, true);
9200
9201                 // Finally, claim the original payment.
9202                 claim_payment(&nodes[0], &expected_route, payment_preimage);
9203
9204                 // To start (2), send a keysend payment but don't claim it.
9205                 let payment_preimage = PaymentPreimage([42; 32]);
9206                 let route = find_route(
9207                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
9208                         None, nodes[0].logger, &scorer, &(), &random_seed_bytes
9209                 ).unwrap();
9210                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9211                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
9212                 check_added_monitors!(nodes[0], 1);
9213                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9214                 assert_eq!(events.len(), 1);
9215                 let event = events.pop().unwrap();
9216                 let path = vec![&nodes[1]];
9217                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
9218
9219                 // Next, attempt a regular payment and make sure it fails.
9220                 let payment_secret = PaymentSecret([43; 32]);
9221                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9222                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9223                 check_added_monitors!(nodes[0], 1);
9224                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9225                 assert_eq!(events.len(), 1);
9226                 let ev = events.drain(..).next().unwrap();
9227                 let payment_event = SendEvent::from_event(ev);
9228                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9229                 check_added_monitors!(nodes[1], 0);
9230                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9231                 expect_pending_htlcs_forwardable!(nodes[1]);
9232                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9233                 check_added_monitors!(nodes[1], 1);
9234                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9235                 assert!(updates.update_add_htlcs.is_empty());
9236                 assert!(updates.update_fulfill_htlcs.is_empty());
9237                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9238                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9239                 assert!(updates.update_fee.is_none());
9240                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9241                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9242                 expect_payment_failed!(nodes[0], payment_hash, true);
9243
9244                 // Finally, succeed the keysend payment.
9245                 claim_payment(&nodes[0], &expected_route, payment_preimage);
9246
9247                 // To start (3), send a keysend payment but don't claim it.
9248                 let payment_id_1 = PaymentId([44; 32]);
9249                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9250                         RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
9251                 check_added_monitors!(nodes[0], 1);
9252                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9253                 assert_eq!(events.len(), 1);
9254                 let event = events.pop().unwrap();
9255                 let path = vec![&nodes[1]];
9256                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
9257
9258                 // Next, attempt a keysend payment and make sure it fails.
9259                 let route_params = RouteParameters {
9260                         payment_params: PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
9261                         final_value_msat: 100_000,
9262                 };
9263                 let route = find_route(
9264                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
9265                         None, nodes[0].logger, &scorer, &(), &random_seed_bytes
9266                 ).unwrap();
9267                 let payment_id_2 = PaymentId([45; 32]);
9268                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9269                         RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap();
9270                 check_added_monitors!(nodes[0], 1);
9271                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9272                 assert_eq!(events.len(), 1);
9273                 let ev = events.drain(..).next().unwrap();
9274                 let payment_event = SendEvent::from_event(ev);
9275                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9276                 check_added_monitors!(nodes[1], 0);
9277                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9278                 expect_pending_htlcs_forwardable!(nodes[1]);
9279                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9280                 check_added_monitors!(nodes[1], 1);
9281                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9282                 assert!(updates.update_add_htlcs.is_empty());
9283                 assert!(updates.update_fulfill_htlcs.is_empty());
9284                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9285                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9286                 assert!(updates.update_fee.is_none());
9287                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9288                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9289                 expect_payment_failed!(nodes[0], payment_hash, true);
9290
9291                 // Finally, claim the original payment.
9292                 claim_payment(&nodes[0], &expected_route, payment_preimage);
9293         }
9294
9295         #[test]
9296         fn test_keysend_hash_mismatch() {
9297                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
9298                 // preimage doesn't match the msg's payment hash.
9299                 let chanmon_cfgs = create_chanmon_cfgs(2);
9300                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9301                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9302                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9303
9304                 let payer_pubkey = nodes[0].node.get_our_node_id();
9305                 let payee_pubkey = nodes[1].node.get_our_node_id();
9306
9307                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9308                 let route_params = RouteParameters {
9309                         payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9310                         final_value_msat: 10_000,
9311                 };
9312                 let network_graph = nodes[0].network_graph.clone();
9313                 let first_hops = nodes[0].node.list_usable_channels();
9314                 let scorer = test_utils::TestScorer::new();
9315                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9316                 let route = find_route(
9317                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9318                         nodes[0].logger, &scorer, &(), &random_seed_bytes
9319                 ).unwrap();
9320
9321                 let test_preimage = PaymentPreimage([42; 32]);
9322                 let mismatch_payment_hash = PaymentHash([43; 32]);
9323                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash,
9324                         RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap();
9325                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash,
9326                         RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
9327                 check_added_monitors!(nodes[0], 1);
9328
9329                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9330                 assert_eq!(updates.update_add_htlcs.len(), 1);
9331                 assert!(updates.update_fulfill_htlcs.is_empty());
9332                 assert!(updates.update_fail_htlcs.is_empty());
9333                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9334                 assert!(updates.update_fee.is_none());
9335                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
9336
9337                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
9338         }
9339
9340         #[test]
9341         fn test_keysend_msg_with_secret_err() {
9342                 // Test that we error as expected if we receive a keysend payment that includes a payment
9343                 // secret when we don't support MPP keysend.
9344                 let mut reject_mpp_keysend_cfg = test_default_channel_config();
9345                 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
9346                 let chanmon_cfgs = create_chanmon_cfgs(2);
9347                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9348                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(reject_mpp_keysend_cfg)]);
9349                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9350
9351                 let payer_pubkey = nodes[0].node.get_our_node_id();
9352                 let payee_pubkey = nodes[1].node.get_our_node_id();
9353
9354                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9355                 let route_params = RouteParameters {
9356                         payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9357                         final_value_msat: 10_000,
9358                 };
9359                 let network_graph = nodes[0].network_graph.clone();
9360                 let first_hops = nodes[0].node.list_usable_channels();
9361                 let scorer = test_utils::TestScorer::new();
9362                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9363                 let route = find_route(
9364                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9365                         nodes[0].logger, &scorer, &(), &random_seed_bytes
9366                 ).unwrap();
9367
9368                 let test_preimage = PaymentPreimage([42; 32]);
9369                 let test_secret = PaymentSecret([43; 32]);
9370                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).into_inner());
9371                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash,
9372                         RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap();
9373                 nodes[0].node.test_send_payment_internal(&route, payment_hash,
9374                         RecipientOnionFields::secret_only(test_secret), Some(test_preimage),
9375                         PaymentId(payment_hash.0), None, session_privs).unwrap();
9376                 check_added_monitors!(nodes[0], 1);
9377
9378                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9379                 assert_eq!(updates.update_add_htlcs.len(), 1);
9380                 assert!(updates.update_fulfill_htlcs.is_empty());
9381                 assert!(updates.update_fail_htlcs.is_empty());
9382                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9383                 assert!(updates.update_fee.is_none());
9384                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
9385
9386                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
9387         }
9388
9389         #[test]
9390         fn test_multi_hop_missing_secret() {
9391                 let chanmon_cfgs = create_chanmon_cfgs(4);
9392                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9393                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9394                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9395
9396                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
9397                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
9398                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
9399                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
9400
9401                 // Marshall an MPP route.
9402                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
9403                 let path = route.paths[0].clone();
9404                 route.paths.push(path);
9405                 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
9406                 route.paths[0].hops[0].short_channel_id = chan_1_id;
9407                 route.paths[0].hops[1].short_channel_id = chan_3_id;
9408                 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
9409                 route.paths[1].hops[0].short_channel_id = chan_2_id;
9410                 route.paths[1].hops[1].short_channel_id = chan_4_id;
9411
9412                 match nodes[0].node.send_payment_with_route(&route, payment_hash,
9413                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0))
9414                 .unwrap_err() {
9415                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
9416                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
9417                         },
9418                         _ => panic!("unexpected error")
9419                 }
9420         }
9421
9422         #[test]
9423         fn test_drop_disconnected_peers_when_removing_channels() {
9424                 let chanmon_cfgs = create_chanmon_cfgs(2);
9425                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9426                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9427                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9428
9429                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9430
9431                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9432                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
9433
9434                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
9435                 check_closed_broadcast!(nodes[0], true);
9436                 check_added_monitors!(nodes[0], 1);
9437                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
9438
9439                 {
9440                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
9441                         // disconnected and the channel between has been force closed.
9442                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9443                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
9444                         assert_eq!(nodes_0_per_peer_state.len(), 1);
9445                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
9446                 }
9447
9448                 nodes[0].node.timer_tick_occurred();
9449
9450                 {
9451                         // Assert that nodes[1] has now been removed.
9452                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
9453                 }
9454         }
9455
9456         #[test]
9457         fn bad_inbound_payment_hash() {
9458                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
9459                 let chanmon_cfgs = create_chanmon_cfgs(2);
9460                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9461                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9462                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9463
9464                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
9465                 let payment_data = msgs::FinalOnionHopData {
9466                         payment_secret,
9467                         total_msat: 100_000,
9468                 };
9469
9470                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
9471                 // payment verification fails as expected.
9472                 let mut bad_payment_hash = payment_hash.clone();
9473                 bad_payment_hash.0[0] += 1;
9474                 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) {
9475                         Ok(_) => panic!("Unexpected ok"),
9476                         Err(()) => {
9477                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
9478                         }
9479                 }
9480
9481                 // Check that using the original payment hash succeeds.
9482                 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());
9483         }
9484
9485         #[test]
9486         fn test_id_to_peer_coverage() {
9487                 // Test that the `ChannelManager:id_to_peer` contains channels which have been assigned
9488                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
9489                 // the channel is successfully closed.
9490                 let chanmon_cfgs = create_chanmon_cfgs(2);
9491                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9492                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9493                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9494
9495                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9496                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9497                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9498                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9499                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9500
9501                 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9502                 let channel_id = &tx.txid().into_inner();
9503                 {
9504                         // Ensure that the `id_to_peer` map is empty until either party has received the
9505                         // funding transaction, and have the real `channel_id`.
9506                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
9507                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
9508                 }
9509
9510                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9511                 {
9512                         // Assert that `nodes[0]`'s `id_to_peer` map is populated with the channel as soon as
9513                         // as it has the funding transaction.
9514                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
9515                         assert_eq!(nodes_0_lock.len(), 1);
9516                         assert!(nodes_0_lock.contains_key(channel_id));
9517                 }
9518
9519                 assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
9520
9521                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9522
9523                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9524                 {
9525                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
9526                         assert_eq!(nodes_0_lock.len(), 1);
9527                         assert!(nodes_0_lock.contains_key(channel_id));
9528                 }
9529                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9530
9531                 {
9532                         // Assert that `nodes[1]`'s `id_to_peer` map is populated with the channel as soon as
9533                         // as it has the funding transaction.
9534                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
9535                         assert_eq!(nodes_1_lock.len(), 1);
9536                         assert!(nodes_1_lock.contains_key(channel_id));
9537                 }
9538                 check_added_monitors!(nodes[1], 1);
9539                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9540                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9541                 check_added_monitors!(nodes[0], 1);
9542                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9543                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9544                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9545                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
9546
9547                 nodes[0].node.close_channel(channel_id, &nodes[1].node.get_our_node_id()).unwrap();
9548                 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()));
9549                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
9550                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
9551
9552                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
9553                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
9554                 {
9555                         // Assert that the channel is kept in the `id_to_peer` map for both nodes until the
9556                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
9557                         // fee for the closing transaction has been negotiated and the parties has the other
9558                         // party's signature for the fee negotiated closing transaction.)
9559                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
9560                         assert_eq!(nodes_0_lock.len(), 1);
9561                         assert!(nodes_0_lock.contains_key(channel_id));
9562                 }
9563
9564                 {
9565                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
9566                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
9567                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
9568                         // kept in the `nodes[1]`'s `id_to_peer` map.
9569                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
9570                         assert_eq!(nodes_1_lock.len(), 1);
9571                         assert!(nodes_1_lock.contains_key(channel_id));
9572                 }
9573
9574                 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()));
9575                 {
9576                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
9577                         // therefore has all it needs to fully close the channel (both signatures for the
9578                         // closing transaction).
9579                         // Assert that the channel is removed from `nodes[0]`'s `id_to_peer` map as it can be
9580                         // fully closed by `nodes[0]`.
9581                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
9582
9583                         // Assert that the channel is still in `nodes[1]`'s  `id_to_peer` map, as `nodes[1]`
9584                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
9585                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
9586                         assert_eq!(nodes_1_lock.len(), 1);
9587                         assert!(nodes_1_lock.contains_key(channel_id));
9588                 }
9589
9590                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
9591
9592                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
9593                 {
9594                         // Assert that the channel has now been removed from both parties `id_to_peer` map once
9595                         // they both have everything required to fully close the channel.
9596                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
9597                 }
9598                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
9599
9600                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
9601                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
9602         }
9603
9604         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
9605                 let expected_message = format!("Not connected to node: {}", expected_public_key);
9606                 check_api_error_message(expected_message, res_err)
9607         }
9608
9609         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
9610                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
9611                 check_api_error_message(expected_message, res_err)
9612         }
9613
9614         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
9615                 match res_err {
9616                         Err(APIError::APIMisuseError { err }) => {
9617                                 assert_eq!(err, expected_err_message);
9618                         },
9619                         Err(APIError::ChannelUnavailable { err }) => {
9620                                 assert_eq!(err, expected_err_message);
9621                         },
9622                         Ok(_) => panic!("Unexpected Ok"),
9623                         Err(_) => panic!("Unexpected Error"),
9624                 }
9625         }
9626
9627         #[test]
9628         fn test_api_calls_with_unkown_counterparty_node() {
9629                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
9630                 // expected if the `counterparty_node_id` is an unkown peer in the
9631                 // `ChannelManager::per_peer_state` map.
9632                 let chanmon_cfg = create_chanmon_cfgs(2);
9633                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
9634                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
9635                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
9636
9637                 // Dummy values
9638                 let channel_id = [4; 32];
9639                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
9640                 let intercept_id = InterceptId([0; 32]);
9641
9642                 // Test the API functions.
9643                 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);
9644
9645                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
9646
9647                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
9648
9649                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
9650
9651                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
9652
9653                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
9654
9655                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
9656         }
9657
9658         #[test]
9659         fn test_connection_limiting() {
9660                 // Test that we limit un-channel'd peers and un-funded channels properly.
9661                 let chanmon_cfgs = create_chanmon_cfgs(2);
9662                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9663                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9664                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9665
9666                 // Note that create_network connects the nodes together for us
9667
9668                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9669                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9670
9671                 let mut funding_tx = None;
9672                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
9673                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
9674                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9675
9676                         if idx == 0 {
9677                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9678                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9679                                 funding_tx = Some(tx.clone());
9680                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
9681                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9682
9683                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9684                                 check_added_monitors!(nodes[1], 1);
9685                                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9686
9687                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9688
9689                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9690                                 check_added_monitors!(nodes[0], 1);
9691                                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9692                         }
9693                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
9694                 }
9695
9696                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
9697                 open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
9698                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
9699                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
9700                         open_channel_msg.temporary_channel_id);
9701
9702                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
9703                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
9704                 // limit.
9705                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
9706                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
9707                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
9708                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
9709                         peer_pks.push(random_pk);
9710                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
9711                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
9712                         }, true).unwrap();
9713                 }
9714                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
9715                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
9716                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
9717                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
9718                 }, true).unwrap_err();
9719
9720                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
9721                 // them if we have too many un-channel'd peers.
9722                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
9723                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
9724                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
9725                 for ev in chan_closed_events {
9726                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
9727                 }
9728                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
9729                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
9730                 }, true).unwrap();
9731                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
9732                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
9733                 }, true).unwrap_err();
9734
9735                 // but of course if the connection is outbound its allowed...
9736                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
9737                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
9738                 }, false).unwrap();
9739                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
9740
9741                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
9742                 // Even though we accept one more connection from new peers, we won't actually let them
9743                 // open channels.
9744                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
9745                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
9746                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
9747                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
9748                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
9749                 }
9750                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
9751                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
9752                         open_channel_msg.temporary_channel_id);
9753
9754                 // Of course, however, outbound channels are always allowed
9755                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None).unwrap();
9756                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
9757
9758                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
9759                 // "protected" and can connect again.
9760                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
9761                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
9762                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
9763                 }, true).unwrap();
9764                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
9765
9766                 // Further, because the first channel was funded, we can open another channel with
9767                 // last_random_pk.
9768                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
9769                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
9770         }
9771
9772         #[test]
9773         fn test_outbound_chans_unlimited() {
9774                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
9775                 let chanmon_cfgs = create_chanmon_cfgs(2);
9776                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9777                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9778                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9779
9780                 // Note that create_network connects the nodes together for us
9781
9782                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9783                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9784
9785                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
9786                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
9787                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9788                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
9789                 }
9790
9791                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
9792                 // rejected.
9793                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
9794                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
9795                         open_channel_msg.temporary_channel_id);
9796
9797                 // but we can still open an outbound channel.
9798                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9799                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
9800
9801                 // but even with such an outbound channel, additional inbound channels will still fail.
9802                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
9803                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
9804                         open_channel_msg.temporary_channel_id);
9805         }
9806
9807         #[test]
9808         fn test_0conf_limiting() {
9809                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
9810                 // flag set and (sometimes) accept channels as 0conf.
9811                 let chanmon_cfgs = create_chanmon_cfgs(2);
9812                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9813                 let mut settings = test_default_channel_config();
9814                 settings.manually_accept_inbound_channels = true;
9815                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
9816                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9817
9818                 // Note that create_network connects the nodes together for us
9819
9820                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9821                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9822
9823                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
9824                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
9825                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
9826                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
9827                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
9828                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
9829                         }, true).unwrap();
9830
9831                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
9832                         let events = nodes[1].node.get_and_clear_pending_events();
9833                         match events[0] {
9834                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
9835                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
9836                                 }
9837                                 _ => panic!("Unexpected event"),
9838                         }
9839                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
9840                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
9841                 }
9842
9843                 // If we try to accept a channel from another peer non-0conf it will fail.
9844                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
9845                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
9846                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
9847                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
9848                 }, true).unwrap();
9849                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
9850                 let events = nodes[1].node.get_and_clear_pending_events();
9851                 match events[0] {
9852                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
9853                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
9854                                         Err(APIError::APIMisuseError { err }) =>
9855                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
9856                                         _ => panic!(),
9857                                 }
9858                         }
9859                         _ => panic!("Unexpected event"),
9860                 }
9861                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
9862                         open_channel_msg.temporary_channel_id);
9863
9864                 // ...however if we accept the same channel 0conf it should work just fine.
9865                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
9866                 let events = nodes[1].node.get_and_clear_pending_events();
9867                 match events[0] {
9868                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
9869                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
9870                         }
9871                         _ => panic!("Unexpected event"),
9872                 }
9873                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
9874         }
9875
9876         #[test]
9877         fn reject_excessively_underpaying_htlcs() {
9878                 let chanmon_cfg = create_chanmon_cfgs(1);
9879                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
9880                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
9881                 let node = create_network(1, &node_cfg, &node_chanmgr);
9882                 let sender_intended_amt_msat = 100;
9883                 let extra_fee_msat = 10;
9884                 let hop_data = msgs::OnionHopData {
9885                         amt_to_forward: 100,
9886                         outgoing_cltv_value: 42,
9887                         format: msgs::OnionHopDataFormat::FinalNode {
9888                                 keysend_preimage: None,
9889                                 payment_metadata: None,
9890                                 payment_data: Some(msgs::FinalOnionHopData {
9891                                         payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
9892                                 }),
9893                         }
9894                 };
9895                 // Check that if the amount we received + the penultimate hop extra fee is less than the sender
9896                 // intended amount, we fail the payment.
9897                 if let Err(crate::ln::channelmanager::ReceiveError { err_code, .. }) =
9898                         node[0].node.construct_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
9899                                 sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat))
9900                 {
9901                         assert_eq!(err_code, 19);
9902                 } else { panic!(); }
9903
9904                 // If amt_received + extra_fee is equal to the sender intended amount, we're fine.
9905                 let hop_data = msgs::OnionHopData { // This is the same hop_data as above, OnionHopData doesn't implement Clone
9906                         amt_to_forward: 100,
9907                         outgoing_cltv_value: 42,
9908                         format: msgs::OnionHopDataFormat::FinalNode {
9909                                 keysend_preimage: None,
9910                                 payment_metadata: None,
9911                                 payment_data: Some(msgs::FinalOnionHopData {
9912                                         payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
9913                                 }),
9914                         }
9915                 };
9916                 assert!(node[0].node.construct_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
9917                         sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat)).is_ok());
9918         }
9919
9920         #[test]
9921         fn test_inbound_anchors_manual_acceptance() {
9922                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
9923                 // flag set and (sometimes) accept channels as 0conf.
9924                 let mut anchors_cfg = test_default_channel_config();
9925                 anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
9926
9927                 let mut anchors_manual_accept_cfg = anchors_cfg.clone();
9928                 anchors_manual_accept_cfg.manually_accept_inbound_channels = true;
9929
9930                 let chanmon_cfgs = create_chanmon_cfgs(3);
9931                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9932                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs,
9933                         &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]);
9934                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9935
9936                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9937                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9938
9939                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
9940                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9941                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9942                 match &msg_events[0] {
9943                         MessageSendEvent::HandleError { node_id, action } => {
9944                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9945                                 match action {
9946                                         ErrorAction::SendErrorMessage { msg } =>
9947                                                 assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()),
9948                                         _ => panic!("Unexpected error action"),
9949                                 }
9950                         }
9951                         _ => panic!("Unexpected event"),
9952                 }
9953
9954                 nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
9955                 let events = nodes[2].node.get_and_clear_pending_events();
9956                 match events[0] {
9957                         Event::OpenChannelRequest { temporary_channel_id, .. } =>
9958                                 nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(),
9959                         _ => panic!("Unexpected event"),
9960                 }
9961                 get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9962         }
9963
9964         #[test]
9965         fn test_anchors_zero_fee_htlc_tx_fallback() {
9966                 // Tests that if both nodes support anchors, but the remote node does not want to accept
9967                 // anchor channels at the moment, an error it sent to the local node such that it can retry
9968                 // the channel without the anchors feature.
9969                 let chanmon_cfgs = create_chanmon_cfgs(2);
9970                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9971                 let mut anchors_config = test_default_channel_config();
9972                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
9973                 anchors_config.manually_accept_inbound_channels = true;
9974                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
9975                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9976
9977                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None).unwrap();
9978                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9979                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
9980
9981                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
9982                 let events = nodes[1].node.get_and_clear_pending_events();
9983                 match events[0] {
9984                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
9985                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
9986                         }
9987                         _ => panic!("Unexpected event"),
9988                 }
9989
9990                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
9991                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
9992
9993                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9994                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
9995
9996                 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9997         }
9998
9999         #[test]
10000         fn test_update_channel_config() {
10001                 let chanmon_cfg = create_chanmon_cfgs(2);
10002                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
10003                 let mut user_config = test_default_channel_config();
10004                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
10005                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
10006                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
10007                 let channel = &nodes[0].node.list_channels()[0];
10008
10009                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
10010                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10011                 assert_eq!(events.len(), 0);
10012
10013                 user_config.channel_config.forwarding_fee_base_msat += 10;
10014                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
10015                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat);
10016                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10017                 assert_eq!(events.len(), 1);
10018                 match &events[0] {
10019                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
10020                         _ => panic!("expected BroadcastChannelUpdate event"),
10021                 }
10022
10023                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap();
10024                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10025                 assert_eq!(events.len(), 0);
10026
10027                 let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6;
10028                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
10029                         cltv_expiry_delta: Some(new_cltv_expiry_delta),
10030                         ..Default::default()
10031                 }).unwrap();
10032                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
10033                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10034                 assert_eq!(events.len(), 1);
10035                 match &events[0] {
10036                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
10037                         _ => panic!("expected BroadcastChannelUpdate event"),
10038                 }
10039
10040                 let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100;
10041                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
10042                         forwarding_fee_proportional_millionths: Some(new_fee),
10043                         ..Default::default()
10044                 }).unwrap();
10045                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
10046                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee);
10047                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10048                 assert_eq!(events.len(), 1);
10049                 match &events[0] {
10050                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
10051                         _ => panic!("expected BroadcastChannelUpdate event"),
10052                 }
10053         }
10054 }
10055
10056 #[cfg(ldk_bench)]
10057 pub mod bench {
10058         use crate::chain::Listen;
10059         use crate::chain::chainmonitor::{ChainMonitor, Persist};
10060         use crate::sign::{KeysManager, InMemorySigner};
10061         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
10062         use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
10063         use crate::ln::functional_test_utils::*;
10064         use crate::ln::msgs::{ChannelMessageHandler, Init};
10065         use crate::routing::gossip::NetworkGraph;
10066         use crate::routing::router::{PaymentParameters, RouteParameters};
10067         use crate::util::test_utils;
10068         use crate::util::config::{UserConfig, MaxDustHTLCExposure};
10069
10070         use bitcoin::hashes::Hash;
10071         use bitcoin::hashes::sha256::Hash as Sha256;
10072         use bitcoin::{Block, BlockHeader, PackedLockTime, Transaction, TxMerkleNode, TxOut};
10073
10074         use crate::sync::{Arc, Mutex};
10075
10076         use criterion::Criterion;
10077
10078         type Manager<'a, P> = ChannelManager<
10079                 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
10080                         &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
10081                         &'a test_utils::TestLogger, &'a P>,
10082                 &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
10083                 &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
10084                 &'a test_utils::TestLogger>;
10085
10086         struct ANodeHolder<'a, P: Persist<InMemorySigner>> {
10087                 node: &'a Manager<'a, P>,
10088         }
10089         impl<'a, P: Persist<InMemorySigner>> NodeHolder for ANodeHolder<'a, P> {
10090                 type CM = Manager<'a, P>;
10091                 #[inline]
10092                 fn node(&self) -> &Manager<'a, P> { self.node }
10093                 #[inline]
10094                 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None }
10095         }
10096
10097         pub fn bench_sends(bench: &mut Criterion) {
10098                 bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new());
10099         }
10100
10101         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) {
10102                 // Do a simple benchmark of sending a payment back and forth between two nodes.
10103                 // Note that this is unrealistic as each payment send will require at least two fsync
10104                 // calls per node.
10105                 let network = bitcoin::Network::Testnet;
10106                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
10107
10108                 let tx_broadcaster = test_utils::TestBroadcaster::new(network);
10109                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
10110                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
10111                 let scorer = Mutex::new(test_utils::TestScorer::new());
10112                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &scorer);
10113
10114                 let mut config: UserConfig = Default::default();
10115                 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
10116                 config.channel_handshake_config.minimum_depth = 1;
10117
10118                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
10119                 let seed_a = [1u8; 32];
10120                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
10121                 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 {
10122                         network,
10123                         best_block: BestBlock::from_network(network),
10124                 }, genesis_block.header.time);
10125                 let node_a_holder = ANodeHolder { node: &node_a };
10126
10127                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
10128                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
10129                 let seed_b = [2u8; 32];
10130                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
10131                 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 {
10132                         network,
10133                         best_block: BestBlock::from_network(network),
10134                 }, genesis_block.header.time);
10135                 let node_b_holder = ANodeHolder { node: &node_b };
10136
10137                 node_a.peer_connected(&node_b.get_our_node_id(), &Init {
10138                         features: node_b.init_features(), networks: None, remote_network_address: None
10139                 }, true).unwrap();
10140                 node_b.peer_connected(&node_a.get_our_node_id(), &Init {
10141                         features: node_a.init_features(), networks: None, remote_network_address: None
10142                 }, false).unwrap();
10143                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
10144                 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()));
10145                 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()));
10146
10147                 let tx;
10148                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
10149                         tx = Transaction { version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
10150                                 value: 8_000_000, script_pubkey: output_script,
10151                         }]};
10152                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
10153                 } else { panic!(); }
10154
10155                 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()));
10156                 let events_b = node_b.get_and_clear_pending_events();
10157                 assert_eq!(events_b.len(), 1);
10158                 match events_b[0] {
10159                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
10160                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
10161                         },
10162                         _ => panic!("Unexpected event"),
10163                 }
10164
10165                 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()));
10166                 let events_a = node_a.get_and_clear_pending_events();
10167                 assert_eq!(events_a.len(), 1);
10168                 match events_a[0] {
10169                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
10170                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
10171                         },
10172                         _ => panic!("Unexpected event"),
10173                 }
10174
10175                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
10176
10177                 let block = create_dummy_block(BestBlock::from_network(network).block_hash(), 42, vec![tx]);
10178                 Listen::block_connected(&node_a, &block, 1);
10179                 Listen::block_connected(&node_b, &block, 1);
10180
10181                 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()));
10182                 let msg_events = node_a.get_and_clear_pending_msg_events();
10183                 assert_eq!(msg_events.len(), 2);
10184                 match msg_events[0] {
10185                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
10186                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
10187                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
10188                         },
10189                         _ => panic!(),
10190                 }
10191                 match msg_events[1] {
10192                         MessageSendEvent::SendChannelUpdate { .. } => {},
10193                         _ => panic!(),
10194                 }
10195
10196                 let events_a = node_a.get_and_clear_pending_events();
10197                 assert_eq!(events_a.len(), 1);
10198                 match events_a[0] {
10199                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
10200                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
10201                         },
10202                         _ => panic!("Unexpected event"),
10203                 }
10204
10205                 let events_b = node_b.get_and_clear_pending_events();
10206                 assert_eq!(events_b.len(), 1);
10207                 match events_b[0] {
10208                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
10209                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
10210                         },
10211                         _ => panic!("Unexpected event"),
10212                 }
10213
10214                 let mut payment_count: u64 = 0;
10215                 macro_rules! send_payment {
10216                         ($node_a: expr, $node_b: expr) => {
10217                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
10218                                         .with_bolt11_features($node_b.invoice_features()).unwrap();
10219                                 let mut payment_preimage = PaymentPreimage([0; 32]);
10220                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
10221                                 payment_count += 1;
10222                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
10223                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
10224
10225                                 $node_a.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
10226                                         PaymentId(payment_hash.0), RouteParameters {
10227                                                 payment_params, final_value_msat: 10_000,
10228                                         }, Retry::Attempts(0)).unwrap();
10229                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
10230                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
10231                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
10232                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
10233                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
10234                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
10235                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &get_event_msg!(ANodeHolder { node: &$node_a }, MessageSendEvent::SendRevokeAndACK, $node_b.get_our_node_id()));
10236
10237                                 expect_pending_htlcs_forwardable!(ANodeHolder { node: &$node_b });
10238                                 expect_payment_claimable!(ANodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
10239                                 $node_b.claim_funds(payment_preimage);
10240                                 expect_payment_claimed!(ANodeHolder { node: &$node_b }, payment_hash, 10_000);
10241
10242                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
10243                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
10244                                                 assert_eq!(node_id, $node_a.get_our_node_id());
10245                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10246                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
10247                                         },
10248                                         _ => panic!("Failed to generate claim event"),
10249                                 }
10250
10251                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
10252                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
10253                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
10254                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &get_event_msg!(ANodeHolder { node: &$node_b }, MessageSendEvent::SendRevokeAndACK, $node_a.get_our_node_id()));
10255
10256                                 expect_payment_sent!(ANodeHolder { node: &$node_a }, payment_preimage);
10257                         }
10258                 }
10259
10260                 bench.bench_function(bench_name, |b| b.iter(|| {
10261                         send_payment!(node_a, node_b);
10262                         send_payment!(node_b, node_a);
10263                 }));
10264         }
10265 }