Merge pull request #1948 from alecchendev/custom-fail-back-err
[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 [`find_route`] for that) nor does it manage constructing
17 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
18 //! imply it needs to fail HTLCs/payments/channels it manages).
19 //!
20 //! [`find_route`]: crate::routing::router::find_route
21
22 use bitcoin::blockdata::block::BlockHeader;
23 use bitcoin::blockdata::transaction::Transaction;
24 use bitcoin::blockdata::constants::genesis_block;
25 use bitcoin::network::constants::Network;
26
27 use bitcoin::hashes::Hash;
28 use bitcoin::hashes::sha256::Hash as Sha256;
29 use bitcoin::hash_types::{BlockHash, Txid};
30
31 use bitcoin::secp256k1::{SecretKey,PublicKey};
32 use bitcoin::secp256k1::Secp256k1;
33 use bitcoin::{LockTime, secp256k1, Sequence};
34
35 use crate::chain;
36 use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
37 use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
38 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};
39 use crate::chain::transaction::{OutPoint, TransactionData};
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, ChannelError, ChannelUpdateStatus, UpdateFulfillCommitFetch};
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::{DefaultRouter, InFlightHtlcs, PaymentParameters, Route, RouteHop, RoutePath, Router};
49 use crate::routing::scoring::ProbabilisticScorer;
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, MAX_VALUE_MSAT};
54 #[cfg(test)]
55 use crate::ln::outbound_payment;
56 use crate::ln::outbound_payment::{OutboundPayments, PendingOutboundPayment};
57 use crate::ln::wire::Encode;
58 use crate::chain::keysinterface::{EntropySource, KeysManager, NodeSigner, Recipient, SignerProvider, ChannelSigner};
59 use crate::util::config::{UserConfig, ChannelConfig};
60 use crate::util::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
61 use crate::util::events;
62 use crate::util::wakers::{Future, Notifier};
63 use crate::util::scid_utils::fake_scid;
64 use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
65 use crate::util::logger::{Level, Logger};
66 use crate::util::errors::APIError;
67
68 use crate::io;
69 use crate::prelude::*;
70 use core::{cmp, mem};
71 use core::cell::RefCell;
72 use crate::io::Read;
73 use crate::sync::{Arc, Mutex, RwLock, RwLockReadGuard, FairRwLock};
74 use core::sync::atomic::{AtomicUsize, Ordering};
75 use core::time::Duration;
76 use core::ops::Deref;
77
78 // Re-export this for use in the public API.
79 pub use crate::ln::outbound_payment::PaymentSendFailure;
80
81 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
82 //
83 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
84 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
85 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
86 //
87 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
88 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
89 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
90 // before we forward it.
91 //
92 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
93 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
94 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
95 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
96 // our payment, which we can use to decode errors or inform the user that the payment was sent.
97
98 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
99 pub(super) enum PendingHTLCRouting {
100         Forward {
101                 onion_packet: msgs::OnionPacket,
102                 /// The SCID from the onion that we should forward to. This could be a real SCID or a fake one
103                 /// generated using `get_fake_scid` from the scid_utils::fake_scid module.
104                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
105         },
106         Receive {
107                 payment_data: msgs::FinalOnionHopData,
108                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
109                 phantom_shared_secret: Option<[u8; 32]>,
110         },
111         ReceiveKeysend {
112                 payment_preimage: PaymentPreimage,
113                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
114         },
115 }
116
117 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
118 pub(super) struct PendingHTLCInfo {
119         pub(super) routing: PendingHTLCRouting,
120         pub(super) incoming_shared_secret: [u8; 32],
121         payment_hash: PaymentHash,
122         pub(super) incoming_amt_msat: Option<u64>, // Added in 0.0.113
123         pub(super) outgoing_amt_msat: u64,
124         pub(super) outgoing_cltv_value: u32,
125 }
126
127 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
128 pub(super) enum HTLCFailureMsg {
129         Relay(msgs::UpdateFailHTLC),
130         Malformed(msgs::UpdateFailMalformedHTLC),
131 }
132
133 /// Stores whether we can't forward an HTLC or relevant forwarding info
134 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
135 pub(super) enum PendingHTLCStatus {
136         Forward(PendingHTLCInfo),
137         Fail(HTLCFailureMsg),
138 }
139
140 pub(super) struct PendingAddHTLCInfo {
141         pub(super) forward_info: PendingHTLCInfo,
142
143         // These fields are produced in `forward_htlcs()` and consumed in
144         // `process_pending_htlc_forwards()` for constructing the
145         // `HTLCSource::PreviousHopData` for failed and forwarded
146         // HTLCs.
147         //
148         // Note that this may be an outbound SCID alias for the associated channel.
149         prev_short_channel_id: u64,
150         prev_htlc_id: u64,
151         prev_funding_outpoint: OutPoint,
152         prev_user_channel_id: u128,
153 }
154
155 pub(super) enum HTLCForwardInfo {
156         AddHTLC(PendingAddHTLCInfo),
157         FailHTLC {
158                 htlc_id: u64,
159                 err_packet: msgs::OnionErrorPacket,
160         },
161 }
162
163 /// Tracks the inbound corresponding to an outbound HTLC
164 #[derive(Clone, Hash, PartialEq, Eq)]
165 pub(crate) struct HTLCPreviousHopData {
166         // Note that this may be an outbound SCID alias for the associated channel.
167         short_channel_id: u64,
168         htlc_id: u64,
169         incoming_packet_shared_secret: [u8; 32],
170         phantom_shared_secret: Option<[u8; 32]>,
171
172         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
173         // channel with a preimage provided by the forward channel.
174         outpoint: OutPoint,
175 }
176
177 enum OnionPayload {
178         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
179         Invoice {
180                 /// This is only here for backwards-compatibility in serialization, in the future it can be
181                 /// removed, breaking clients running 0.0.106 and earlier.
182                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
183         },
184         /// Contains the payer-provided preimage.
185         Spontaneous(PaymentPreimage),
186 }
187
188 /// HTLCs that are to us and can be failed/claimed by the user
189 struct ClaimableHTLC {
190         prev_hop: HTLCPreviousHopData,
191         cltv_expiry: u32,
192         /// The amount (in msats) of this MPP part
193         value: u64,
194         onion_payload: OnionPayload,
195         timer_ticks: u8,
196         /// The sum total of all MPP parts
197         total_msat: u64,
198 }
199
200 /// A payment identifier used to uniquely identify a payment to LDK.
201 /// (C-not exported) as we just use [u8; 32] directly
202 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
203 pub struct PaymentId(pub [u8; 32]);
204
205 impl Writeable for PaymentId {
206         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
207                 self.0.write(w)
208         }
209 }
210
211 impl Readable for PaymentId {
212         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
213                 let buf: [u8; 32] = Readable::read(r)?;
214                 Ok(PaymentId(buf))
215         }
216 }
217
218 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
219 /// (C-not exported) as we just use [u8; 32] directly
220 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
221 pub struct InterceptId(pub [u8; 32]);
222
223 impl Writeable for InterceptId {
224         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
225                 self.0.write(w)
226         }
227 }
228
229 impl Readable for InterceptId {
230         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
231                 let buf: [u8; 32] = Readable::read(r)?;
232                 Ok(InterceptId(buf))
233         }
234 }
235 /// Tracks the inbound corresponding to an outbound HTLC
236 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
237 #[derive(Clone, PartialEq, Eq)]
238 pub(crate) enum HTLCSource {
239         PreviousHopData(HTLCPreviousHopData),
240         OutboundRoute {
241                 path: Vec<RouteHop>,
242                 session_priv: SecretKey,
243                 /// Technically we can recalculate this from the route, but we cache it here to avoid
244                 /// doing a double-pass on route when we get a failure back
245                 first_hop_htlc_msat: u64,
246                 payment_id: PaymentId,
247                 payment_secret: Option<PaymentSecret>,
248                 payment_params: Option<PaymentParameters>,
249         },
250 }
251 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
252 impl core::hash::Hash for HTLCSource {
253         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
254                 match self {
255                         HTLCSource::PreviousHopData(prev_hop_data) => {
256                                 0u8.hash(hasher);
257                                 prev_hop_data.hash(hasher);
258                         },
259                         HTLCSource::OutboundRoute { path, session_priv, payment_id, payment_secret, first_hop_htlc_msat, payment_params } => {
260                                 1u8.hash(hasher);
261                                 path.hash(hasher);
262                                 session_priv[..].hash(hasher);
263                                 payment_id.hash(hasher);
264                                 payment_secret.hash(hasher);
265                                 first_hop_htlc_msat.hash(hasher);
266                                 payment_params.hash(hasher);
267                         },
268                 }
269         }
270 }
271 #[cfg(not(feature = "grind_signatures"))]
272 #[cfg(test)]
273 impl HTLCSource {
274         pub fn dummy() -> Self {
275                 HTLCSource::OutboundRoute {
276                         path: Vec::new(),
277                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
278                         first_hop_htlc_msat: 0,
279                         payment_id: PaymentId([2; 32]),
280                         payment_secret: None,
281                         payment_params: None,
282                 }
283         }
284 }
285
286 struct ReceiveError {
287         err_code: u16,
288         err_data: Vec<u8>,
289         msg: &'static str,
290 }
291
292 /// This enum is used to specify which error data to send to peers when failing back an HTLC
293 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
294 ///
295 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
296 #[derive(Clone, Copy)]
297 pub enum FailureCode {
298         /// We had a temporary error processing the payment. Useful if no other error codes fit
299         /// and you want to indicate that the payer may want to retry.
300         TemporaryNodeFailure             = 0x2000 | 2,
301         /// We have a required feature which was not in this onion. For example, you may require
302         /// some additional metadata that was not provided with this payment.
303         RequiredNodeFeatureMissing       = 0x4000 | 0x2000 | 3,
304         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
305         /// the HTLC is too close to the current block height for safe handling.
306         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
307         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
308         IncorrectOrUnknownPaymentDetails = 0x4000 | 15,
309 }
310
311 type ShutdownResult = (Option<(OutPoint, ChannelMonitorUpdate)>, Vec<(HTLCSource, PaymentHash, PublicKey, [u8; 32])>);
312
313 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
314 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
315 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
316 /// peer_state lock. We then return the set of things that need to be done outside the lock in
317 /// this struct and call handle_error!() on it.
318
319 struct MsgHandleErrInternal {
320         err: msgs::LightningError,
321         chan_id: Option<([u8; 32], u128)>, // If Some a channel of ours has been closed
322         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
323 }
324 impl MsgHandleErrInternal {
325         #[inline]
326         fn send_err_msg_no_close(err: String, channel_id: [u8; 32]) -> Self {
327                 Self {
328                         err: LightningError {
329                                 err: err.clone(),
330                                 action: msgs::ErrorAction::SendErrorMessage {
331                                         msg: msgs::ErrorMessage {
332                                                 channel_id,
333                                                 data: err
334                                         },
335                                 },
336                         },
337                         chan_id: None,
338                         shutdown_finish: None,
339                 }
340         }
341         #[inline]
342         fn ignore_no_close(err: String) -> Self {
343                 Self {
344                         err: LightningError {
345                                 err,
346                                 action: msgs::ErrorAction::IgnoreError,
347                         },
348                         chan_id: None,
349                         shutdown_finish: None,
350                 }
351         }
352         #[inline]
353         fn from_no_close(err: msgs::LightningError) -> Self {
354                 Self { err, chan_id: None, shutdown_finish: None }
355         }
356         #[inline]
357         fn from_finish_shutdown(err: String, channel_id: [u8; 32], user_channel_id: u128, shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
358                 Self {
359                         err: LightningError {
360                                 err: err.clone(),
361                                 action: msgs::ErrorAction::SendErrorMessage {
362                                         msg: msgs::ErrorMessage {
363                                                 channel_id,
364                                                 data: err
365                                         },
366                                 },
367                         },
368                         chan_id: Some((channel_id, user_channel_id)),
369                         shutdown_finish: Some((shutdown_res, channel_update)),
370                 }
371         }
372         #[inline]
373         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
374                 Self {
375                         err: match err {
376                                 ChannelError::Warn(msg) =>  LightningError {
377                                         err: msg.clone(),
378                                         action: msgs::ErrorAction::SendWarningMessage {
379                                                 msg: msgs::WarningMessage {
380                                                         channel_id,
381                                                         data: msg
382                                                 },
383                                                 log_level: Level::Warn,
384                                         },
385                                 },
386                                 ChannelError::Ignore(msg) => LightningError {
387                                         err: msg,
388                                         action: msgs::ErrorAction::IgnoreError,
389                                 },
390                                 ChannelError::Close(msg) => LightningError {
391                                         err: msg.clone(),
392                                         action: msgs::ErrorAction::SendErrorMessage {
393                                                 msg: msgs::ErrorMessage {
394                                                         channel_id,
395                                                         data: msg
396                                                 },
397                                         },
398                                 },
399                         },
400                         chan_id: None,
401                         shutdown_finish: None,
402                 }
403         }
404 }
405
406 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
407 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
408 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
409 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
410 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
411
412 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
413 /// be sent in the order they appear in the return value, however sometimes the order needs to be
414 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
415 /// they were originally sent). In those cases, this enum is also returned.
416 #[derive(Clone, PartialEq)]
417 pub(super) enum RAACommitmentOrder {
418         /// Send the CommitmentUpdate messages first
419         CommitmentFirst,
420         /// Send the RevokeAndACK message first
421         RevokeAndACKFirst,
422 }
423
424 /// Information about a payment which is currently being claimed.
425 struct ClaimingPayment {
426         amount_msat: u64,
427         payment_purpose: events::PaymentPurpose,
428         receiver_node_id: PublicKey,
429 }
430 impl_writeable_tlv_based!(ClaimingPayment, {
431         (0, amount_msat, required),
432         (2, payment_purpose, required),
433         (4, receiver_node_id, required),
434 });
435
436 /// Information about claimable or being-claimed payments
437 struct ClaimablePayments {
438         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
439         /// failed/claimed by the user.
440         ///
441         /// Note that, no consistency guarantees are made about the channels given here actually
442         /// existing anymore by the time you go to read them!
443         ///
444         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
445         /// we don't get a duplicate payment.
446         claimable_htlcs: HashMap<PaymentHash, (events::PaymentPurpose, Vec<ClaimableHTLC>)>,
447
448         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
449         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
450         /// as an [`events::Event::PaymentClaimed`].
451         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
452 }
453
454 /// Events which we process internally but cannot be procsesed immediately at the generation site
455 /// for some reason. They are handled in timer_tick_occurred, so may be processed with
456 /// quite some time lag.
457 enum BackgroundEvent {
458         /// Handle a ChannelMonitorUpdate that closes a channel, broadcasting its current latest holder
459         /// commitment transaction.
460         ClosingMonitorUpdate((OutPoint, ChannelMonitorUpdate)),
461 }
462
463 pub(crate) enum MonitorUpdateCompletionAction {
464         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
465         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
466         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
467         /// event can be generated.
468         PaymentClaimed { payment_hash: PaymentHash },
469         /// Indicates an [`events::Event`] should be surfaced to the user.
470         EmitEvent { event: events::Event },
471 }
472
473 /// State we hold per-peer.
474 pub(super) struct PeerState<Signer: ChannelSigner> {
475         /// `temporary_channel_id` or `channel_id` -> `channel`.
476         ///
477         /// Holds all channels where the peer is the counterparty. Once a channel has been assigned a
478         /// `channel_id`, the `temporary_channel_id` key in the map is updated and is replaced by the
479         /// `channel_id`.
480         pub(super) channel_by_id: HashMap<[u8; 32], Channel<Signer>>,
481         /// The latest `InitFeatures` we heard from the peer.
482         latest_features: InitFeatures,
483         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
484         /// for broadcast messages, where ordering isn't as strict).
485         pub(super) pending_msg_events: Vec<MessageSendEvent>,
486 }
487
488 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
489 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
490 ///
491 /// For users who don't want to bother doing their own payment preimage storage, we also store that
492 /// here.
493 ///
494 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
495 /// and instead encoding it in the payment secret.
496 struct PendingInboundPayment {
497         /// The payment secret that the sender must use for us to accept this payment
498         payment_secret: PaymentSecret,
499         /// Time at which this HTLC expires - blocks with a header time above this value will result in
500         /// this payment being removed.
501         expiry_time: u64,
502         /// Arbitrary identifier the user specifies (or not)
503         user_payment_id: u64,
504         // Other required attributes of the payment, optionally enforced:
505         payment_preimage: Option<PaymentPreimage>,
506         min_value_msat: Option<u64>,
507 }
508
509 /// SimpleArcChannelManager is useful when you need a ChannelManager with a static lifetime, e.g.
510 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
511 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
512 /// SimpleRefChannelManager is the more appropriate type. Defining these type aliases prevents
513 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
514 /// that implements KeysInterface or Router for its keys manager and router, respectively, but this
515 /// type alias chooses the concrete types of KeysManager and DefaultRouter.
516 ///
517 /// (C-not exported) as Arcs don't make sense in bindings
518 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
519         Arc<M>,
520         Arc<T>,
521         Arc<KeysManager>,
522         Arc<KeysManager>,
523         Arc<KeysManager>,
524         Arc<F>,
525         Arc<DefaultRouter<
526                 Arc<NetworkGraph<Arc<L>>>,
527                 Arc<L>,
528                 Arc<Mutex<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>
529         >>,
530         Arc<L>
531 >;
532
533 /// SimpleRefChannelManager is a type alias for a ChannelManager reference, and is the reference
534 /// counterpart to the SimpleArcChannelManager type alias. Use this type by default when you don't
535 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
536 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
537 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
538 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
539 /// that implements KeysInterface or Router for its keys manager and router, respectively, but this
540 /// type alias chooses the concrete types of KeysManager and DefaultRouter.
541 ///
542 /// (C-not exported) as Arcs don't make sense in bindings
543 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> = ChannelManager<&'a M, &'b T, &'c KeysManager, &'c KeysManager, &'c KeysManager, &'d F, &'e DefaultRouter<&'f NetworkGraph<&'g L>, &'g L, &'h Mutex<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>>, &'g L>;
544
545 /// Manager which keeps track of a number of channels and sends messages to the appropriate
546 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
547 ///
548 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
549 /// to individual Channels.
550 ///
551 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
552 /// all peers during write/read (though does not modify this instance, only the instance being
553 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
554 /// called funding_transaction_generated for outbound channels).
555 ///
556 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
557 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
558 /// returning from chain::Watch::watch_/update_channel, with ChannelManagers, writing updates
559 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
560 /// the serialization process). If the deserialized version is out-of-date compared to the
561 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
562 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
563 ///
564 /// Note that the deserializer is only implemented for (BlockHash, ChannelManager), which
565 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
566 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
567 /// block_connected() to step towards your best block) upon deserialization before using the
568 /// object!
569 ///
570 /// Note that ChannelManager is responsible for tracking liveness of its channels and generating
571 /// ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid
572 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
573 /// offline for a full minute. In order to track this, you must call
574 /// timer_tick_occurred roughly once per minute, though it doesn't have to be perfect.
575 ///
576 /// Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager
577 /// a SimpleRefChannelManager, for conciseness. See their documentation for more details, but
578 /// essentially you should default to using a SimpleRefChannelManager, and use a
579 /// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
580 /// you're using lightning-net-tokio.
581 //
582 // Lock order:
583 // The tree structure below illustrates the lock order requirements for the different locks of the
584 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
585 // and should then be taken in the order of the lowest to the highest level in the tree.
586 // Note that locks on different branches shall not be taken at the same time, as doing so will
587 // create a new lock order for those specific locks in the order they were taken.
588 //
589 // Lock order tree:
590 //
591 // `total_consistency_lock`
592 //  |
593 //  |__`forward_htlcs`
594 //  |   |
595 //  |   |__`pending_intercepted_htlcs`
596 //  |
597 //  |__`per_peer_state`
598 //  |   |
599 //  |   |__`pending_inbound_payments`
600 //  |       |
601 //  |       |__`claimable_payments`
602 //  |       |
603 //  |       |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
604 //  |           |
605 //  |           |__`peer_state`
606 //  |               |
607 //  |               |__`id_to_peer`
608 //  |               |
609 //  |               |__`short_to_chan_info`
610 //  |               |
611 //  |               |__`outbound_scid_aliases`
612 //  |               |
613 //  |               |__`best_block`
614 //  |               |
615 //  |               |__`pending_events`
616 //  |                   |
617 //  |                   |__`pending_background_events`
618 //
619 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
620 where
621         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
622         T::Target: BroadcasterInterface,
623         ES::Target: EntropySource,
624         NS::Target: NodeSigner,
625         SP::Target: SignerProvider,
626         F::Target: FeeEstimator,
627         R::Target: Router,
628         L::Target: Logger,
629 {
630         default_configuration: UserConfig,
631         genesis_hash: BlockHash,
632         fee_estimator: LowerBoundedFeeEstimator<F>,
633         chain_monitor: M,
634         tx_broadcaster: T,
635         #[allow(unused)]
636         router: R,
637
638         /// See `ChannelManager` struct-level documentation for lock order requirements.
639         #[cfg(test)]
640         pub(super) best_block: RwLock<BestBlock>,
641         #[cfg(not(test))]
642         best_block: RwLock<BestBlock>,
643         secp_ctx: Secp256k1<secp256k1::All>,
644
645         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
646         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
647         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
648         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
649         ///
650         /// See `ChannelManager` struct-level documentation for lock order requirements.
651         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
652
653         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
654         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
655         /// (if the channel has been force-closed), however we track them here to prevent duplicative
656         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
657         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
658         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
659         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
660         /// after reloading from disk while replaying blocks against ChannelMonitors.
661         ///
662         /// See `PendingOutboundPayment` documentation for more info.
663         ///
664         /// See `ChannelManager` struct-level documentation for lock order requirements.
665         pending_outbound_payments: OutboundPayments,
666
667         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
668         ///
669         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
670         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
671         /// and via the classic SCID.
672         ///
673         /// Note that no consistency guarantees are made about the existence of a channel with the
674         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
675         ///
676         /// See `ChannelManager` struct-level documentation for lock order requirements.
677         #[cfg(test)]
678         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
679         #[cfg(not(test))]
680         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
681         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
682         /// until the user tells us what we should do with them.
683         ///
684         /// See `ChannelManager` struct-level documentation for lock order requirements.
685         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
686
687         /// The sets of payments which are claimable or currently being claimed. See
688         /// [`ClaimablePayments`]' individual field docs for more info.
689         ///
690         /// See `ChannelManager` struct-level documentation for lock order requirements.
691         claimable_payments: Mutex<ClaimablePayments>,
692
693         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
694         /// and some closed channels which reached a usable state prior to being closed. This is used
695         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
696         /// active channel list on load.
697         ///
698         /// See `ChannelManager` struct-level documentation for lock order requirements.
699         outbound_scid_aliases: Mutex<HashSet<u64>>,
700
701         /// `channel_id` -> `counterparty_node_id`.
702         ///
703         /// Only `channel_id`s are allowed as keys in this map, and not `temporary_channel_id`s. As
704         /// multiple channels with the same `temporary_channel_id` to different peers can exist,
705         /// allowing `temporary_channel_id`s in this map would cause collisions for such channels.
706         ///
707         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
708         /// the corresponding channel for the event, as we only have access to the `channel_id` during
709         /// the handling of the events.
710         ///
711         /// Note that no consistency guarantees are made about the existence of a peer with the
712         /// `counterparty_node_id` in our other maps.
713         ///
714         /// TODO:
715         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
716         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
717         /// would break backwards compatability.
718         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
719         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
720         /// required to access the channel with the `counterparty_node_id`.
721         ///
722         /// See `ChannelManager` struct-level documentation for lock order requirements.
723         id_to_peer: Mutex<HashMap<[u8; 32], PublicKey>>,
724
725         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
726         ///
727         /// Outbound SCID aliases are added here once the channel is available for normal use, with
728         /// SCIDs being added once the funding transaction is confirmed at the channel's required
729         /// confirmation depth.
730         ///
731         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
732         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
733         /// channel with the `channel_id` in our other maps.
734         ///
735         /// See `ChannelManager` struct-level documentation for lock order requirements.
736         #[cfg(test)]
737         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, [u8; 32])>>,
738         #[cfg(not(test))]
739         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, [u8; 32])>>,
740
741         our_network_pubkey: PublicKey,
742
743         inbound_payment_key: inbound_payment::ExpandedKey,
744
745         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
746         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
747         /// we encrypt the namespace identifier using these bytes.
748         ///
749         /// [fake scids]: crate::util::scid_utils::fake_scid
750         fake_scid_rand_bytes: [u8; 32],
751
752         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
753         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
754         /// keeping additional state.
755         probing_cookie_secret: [u8; 32],
756
757         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
758         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
759         /// very far in the past, and can only ever be up to two hours in the future.
760         highest_seen_timestamp: AtomicUsize,
761
762         /// The bulk of our storage will eventually be here (message queues and the like). Currently
763         /// the `per_peer_state` stores our channels on a per-peer basis, as well as the peer's latest
764         /// features.
765         ///
766         /// If we are connected to a peer we always at least have an entry here, even if no channels
767         /// are currently open with that peer.
768         ///
769         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
770         /// operate on the inner value freely. This opens up for parallel per-peer operation for
771         /// channels.
772         ///
773         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
774         ///
775         /// See `ChannelManager` struct-level documentation for lock order requirements.
776         #[cfg(not(any(test, feature = "_test_utils")))]
777         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<<SP::Target as SignerProvider>::Signer>>>>,
778         #[cfg(any(test, feature = "_test_utils"))]
779         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<<SP::Target as SignerProvider>::Signer>>>>,
780
781         /// See `ChannelManager` struct-level documentation for lock order requirements.
782         pending_events: Mutex<Vec<events::Event>>,
783         /// See `ChannelManager` struct-level documentation for lock order requirements.
784         pending_background_events: Mutex<Vec<BackgroundEvent>>,
785         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
786         /// Essentially just when we're serializing ourselves out.
787         /// Taken first everywhere where we are making changes before any other locks.
788         /// When acquiring this lock in read mode, rather than acquiring it directly, call
789         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
790         /// Notifier the lock contains sends out a notification when the lock is released.
791         total_consistency_lock: RwLock<()>,
792
793         persistence_notifier: Notifier,
794
795         entropy_source: ES,
796         node_signer: NS,
797         signer_provider: SP,
798
799         logger: L,
800 }
801
802 /// Chain-related parameters used to construct a new `ChannelManager`.
803 ///
804 /// Typically, the block-specific parameters are derived from the best block hash for the network,
805 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
806 /// are not needed when deserializing a previously constructed `ChannelManager`.
807 #[derive(Clone, Copy, PartialEq)]
808 pub struct ChainParameters {
809         /// The network for determining the `chain_hash` in Lightning messages.
810         pub network: Network,
811
812         /// The hash and height of the latest block successfully connected.
813         ///
814         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
815         pub best_block: BestBlock,
816 }
817
818 #[derive(Copy, Clone, PartialEq)]
819 enum NotifyOption {
820         DoPersist,
821         SkipPersist,
822 }
823
824 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
825 /// desirable to notify any listeners on `await_persistable_update_timeout`/
826 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
827 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
828 /// sending the aforementioned notification (since the lock being released indicates that the
829 /// updates are ready for persistence).
830 ///
831 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
832 /// notify or not based on whether relevant changes have been made, providing a closure to
833 /// `optionally_notify` which returns a `NotifyOption`.
834 struct PersistenceNotifierGuard<'a, F: Fn() -> NotifyOption> {
835         persistence_notifier: &'a Notifier,
836         should_persist: F,
837         // We hold onto this result so the lock doesn't get released immediately.
838         _read_guard: RwLockReadGuard<'a, ()>,
839 }
840
841 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
842         fn notify_on_drop(lock: &'a RwLock<()>, notifier: &'a Notifier) -> PersistenceNotifierGuard<'a, impl Fn() -> NotifyOption> {
843                 PersistenceNotifierGuard::optionally_notify(lock, notifier, || -> NotifyOption { NotifyOption::DoPersist })
844         }
845
846         fn optionally_notify<F: Fn() -> NotifyOption>(lock: &'a RwLock<()>, notifier: &'a Notifier, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
847                 let read_guard = lock.read().unwrap();
848
849                 PersistenceNotifierGuard {
850                         persistence_notifier: notifier,
851                         should_persist: persist_check,
852                         _read_guard: read_guard,
853                 }
854         }
855 }
856
857 impl<'a, F: Fn() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
858         fn drop(&mut self) {
859                 if (self.should_persist)() == NotifyOption::DoPersist {
860                         self.persistence_notifier.notify();
861                 }
862         }
863 }
864
865 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
866 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
867 ///
868 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
869 ///
870 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
871 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
872 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
873 /// the maximum required amount in lnd as of March 2021.
874 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
875
876 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
877 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
878 ///
879 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
880 ///
881 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
882 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
883 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
884 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
885 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
886 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
887 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
888 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
889 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
890 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
891 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
892 // routing failure for any HTLC sender picking up an LDK node among the first hops.
893 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
894
895 /// Minimum CLTV difference between the current block height and received inbound payments.
896 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
897 /// this value.
898 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
899 // any payments to succeed. Further, we don't want payments to fail if a block was found while
900 // a payment was being routed, so we add an extra block to be safe.
901 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
902
903 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
904 // ie that if the next-hop peer fails the HTLC within
905 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
906 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
907 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
908 // LATENCY_GRACE_PERIOD_BLOCKS.
909 #[deny(const_err)]
910 #[allow(dead_code)]
911 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;
912
913 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
914 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
915 #[deny(const_err)]
916 #[allow(dead_code)]
917 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
918
919 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
920 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
921
922 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until we time-out the
923 /// idempotency of payments by [`PaymentId`]. See
924 /// [`OutboundPayments::remove_stale_resolved_payments`].
925 pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
926
927 /// Information needed for constructing an invoice route hint for this channel.
928 #[derive(Clone, Debug, PartialEq)]
929 pub struct CounterpartyForwardingInfo {
930         /// Base routing fee in millisatoshis.
931         pub fee_base_msat: u32,
932         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
933         pub fee_proportional_millionths: u32,
934         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
935         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
936         /// `cltv_expiry_delta` for more details.
937         pub cltv_expiry_delta: u16,
938 }
939
940 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
941 /// to better separate parameters.
942 #[derive(Clone, Debug, PartialEq)]
943 pub struct ChannelCounterparty {
944         /// The node_id of our counterparty
945         pub node_id: PublicKey,
946         /// The Features the channel counterparty provided upon last connection.
947         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
948         /// many routing-relevant features are present in the init context.
949         pub features: InitFeatures,
950         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
951         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
952         /// claiming at least this value on chain.
953         ///
954         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
955         ///
956         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
957         pub unspendable_punishment_reserve: u64,
958         /// Information on the fees and requirements that the counterparty requires when forwarding
959         /// payments to us through this channel.
960         pub forwarding_info: Option<CounterpartyForwardingInfo>,
961         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
962         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
963         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
964         pub outbound_htlc_minimum_msat: Option<u64>,
965         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
966         pub outbound_htlc_maximum_msat: Option<u64>,
967 }
968
969 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
970 #[derive(Clone, Debug, PartialEq)]
971 pub struct ChannelDetails {
972         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
973         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
974         /// Note that this means this value is *not* persistent - it can change once during the
975         /// lifetime of the channel.
976         pub channel_id: [u8; 32],
977         /// Parameters which apply to our counterparty. See individual fields for more information.
978         pub counterparty: ChannelCounterparty,
979         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
980         /// our counterparty already.
981         ///
982         /// Note that, if this has been set, `channel_id` will be equivalent to
983         /// `funding_txo.unwrap().to_channel_id()`.
984         pub funding_txo: Option<OutPoint>,
985         /// The features which this channel operates with. See individual features for more info.
986         ///
987         /// `None` until negotiation completes and the channel type is finalized.
988         pub channel_type: Option<ChannelTypeFeatures>,
989         /// The position of the funding transaction in the chain. None if the funding transaction has
990         /// not yet been confirmed and the channel fully opened.
991         ///
992         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
993         /// payments instead of this. See [`get_inbound_payment_scid`].
994         ///
995         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
996         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
997         ///
998         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
999         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1000         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1001         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1002         /// [`confirmations_required`]: Self::confirmations_required
1003         pub short_channel_id: Option<u64>,
1004         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1005         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1006         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1007         /// `Some(0)`).
1008         ///
1009         /// This will be `None` as long as the channel is not available for routing outbound payments.
1010         ///
1011         /// [`short_channel_id`]: Self::short_channel_id
1012         /// [`confirmations_required`]: Self::confirmations_required
1013         pub outbound_scid_alias: Option<u64>,
1014         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1015         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1016         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1017         /// when they see a payment to be routed to us.
1018         ///
1019         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1020         /// previous values for inbound payment forwarding.
1021         ///
1022         /// [`short_channel_id`]: Self::short_channel_id
1023         pub inbound_scid_alias: Option<u64>,
1024         /// The value, in satoshis, of this channel as appears in the funding output
1025         pub channel_value_satoshis: u64,
1026         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1027         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1028         /// this value on chain.
1029         ///
1030         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1031         ///
1032         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1033         ///
1034         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1035         pub unspendable_punishment_reserve: Option<u64>,
1036         /// The `user_channel_id` passed in to create_channel, or a random value if the channel was
1037         /// inbound. This may be zero for inbound channels serialized with LDK versions prior to
1038         /// 0.0.113.
1039         pub user_channel_id: u128,
1040         /// Our total balance.  This is the amount we would get if we close the channel.
1041         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1042         /// amount is not likely to be recoverable on close.
1043         ///
1044         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1045         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1046         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1047         /// This does not consider any on-chain fees.
1048         ///
1049         /// See also [`ChannelDetails::outbound_capacity_msat`]
1050         pub balance_msat: u64,
1051         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1052         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1053         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1054         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1055         ///
1056         /// See also [`ChannelDetails::balance_msat`]
1057         ///
1058         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1059         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1060         /// should be able to spend nearly this amount.
1061         pub outbound_capacity_msat: u64,
1062         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1063         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1064         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1065         /// to use a limit as close as possible to the HTLC limit we can currently send.
1066         ///
1067         /// See also [`ChannelDetails::balance_msat`] and [`ChannelDetails::outbound_capacity_msat`].
1068         pub next_outbound_htlc_limit_msat: u64,
1069         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1070         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1071         /// available for inclusion in new inbound HTLCs).
1072         /// Note that there are some corner cases not fully handled here, so the actual available
1073         /// inbound capacity may be slightly higher than this.
1074         ///
1075         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1076         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1077         /// However, our counterparty should be able to spend nearly this amount.
1078         pub inbound_capacity_msat: u64,
1079         /// The number of required confirmations on the funding transaction before the funding will be
1080         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1081         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1082         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1083         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1084         ///
1085         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1086         ///
1087         /// [`is_outbound`]: ChannelDetails::is_outbound
1088         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1089         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1090         pub confirmations_required: Option<u32>,
1091         /// The current number of confirmations on the funding transaction.
1092         ///
1093         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1094         pub confirmations: Option<u32>,
1095         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1096         /// until we can claim our funds after we force-close the channel. During this time our
1097         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1098         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1099         /// time to claim our non-HTLC-encumbered funds.
1100         ///
1101         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1102         pub force_close_spend_delay: Option<u16>,
1103         /// True if the channel was initiated (and thus funded) by us.
1104         pub is_outbound: bool,
1105         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1106         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1107         /// required confirmation count has been reached (and we were connected to the peer at some
1108         /// point after the funding transaction received enough confirmations). The required
1109         /// confirmation count is provided in [`confirmations_required`].
1110         ///
1111         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1112         pub is_channel_ready: bool,
1113         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1114         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1115         ///
1116         /// This is a strict superset of `is_channel_ready`.
1117         pub is_usable: bool,
1118         /// True if this channel is (or will be) publicly-announced.
1119         pub is_public: bool,
1120         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1121         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1122         pub inbound_htlc_minimum_msat: Option<u64>,
1123         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1124         pub inbound_htlc_maximum_msat: Option<u64>,
1125         /// Set of configurable parameters that affect channel operation.
1126         ///
1127         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1128         pub config: Option<ChannelConfig>,
1129 }
1130
1131 impl ChannelDetails {
1132         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1133         /// This should be used for providing invoice hints or in any other context where our
1134         /// counterparty will forward a payment to us.
1135         ///
1136         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1137         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1138         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1139                 self.inbound_scid_alias.or(self.short_channel_id)
1140         }
1141
1142         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1143         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1144         /// we're sending or forwarding a payment outbound over this channel.
1145         ///
1146         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1147         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1148         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1149                 self.short_channel_id.or(self.outbound_scid_alias)
1150         }
1151 }
1152
1153 /// Route hints used in constructing invoices for [phantom node payents].
1154 ///
1155 /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
1156 #[derive(Clone)]
1157 pub struct PhantomRouteHints {
1158         /// The list of channels to be included in the invoice route hints.
1159         pub channels: Vec<ChannelDetails>,
1160         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1161         /// route hints.
1162         pub phantom_scid: u64,
1163         /// The pubkey of the real backing node that would ultimately receive the payment.
1164         pub real_node_pubkey: PublicKey,
1165 }
1166
1167 macro_rules! handle_error {
1168         ($self: ident, $internal: expr, $counterparty_node_id: expr) => {
1169                 match $internal {
1170                         Ok(msg) => Ok(msg),
1171                         Err(MsgHandleErrInternal { err, chan_id, shutdown_finish }) => {
1172                                 #[cfg(any(feature = "_test_utils", test))]
1173                                 {
1174                                         // In testing, ensure there are no deadlocks where the lock is already held upon
1175                                         // entering the macro.
1176                                         debug_assert!($self.pending_events.try_lock().is_ok());
1177                                         debug_assert!($self.per_peer_state.try_write().is_ok());
1178                                 }
1179
1180                                 let mut msg_events = Vec::with_capacity(2);
1181
1182                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1183                                         $self.finish_force_close_channel(shutdown_res);
1184                                         if let Some(update) = update_option {
1185                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1186                                                         msg: update
1187                                                 });
1188                                         }
1189                                         if let Some((channel_id, user_channel_id)) = chan_id {
1190                                                 $self.pending_events.lock().unwrap().push(events::Event::ChannelClosed {
1191                                                         channel_id, user_channel_id,
1192                                                         reason: ClosureReason::ProcessingError { err: err.err.clone() }
1193                                                 });
1194                                         }
1195                                 }
1196
1197                                 log_error!($self.logger, "{}", err.err);
1198                                 if let msgs::ErrorAction::IgnoreError = err.action {
1199                                 } else {
1200                                         msg_events.push(events::MessageSendEvent::HandleError {
1201                                                 node_id: $counterparty_node_id,
1202                                                 action: err.action.clone()
1203                                         });
1204                                 }
1205
1206                                 if !msg_events.is_empty() {
1207                                         let per_peer_state = $self.per_peer_state.read().unwrap();
1208                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
1209                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
1210                                                 peer_state.pending_msg_events.append(&mut msg_events);
1211                                         }
1212                                         #[cfg(any(feature = "_test_utils", test))]
1213                                         {
1214                                                 if let None = per_peer_state.get(&$counterparty_node_id) {
1215                                                         // This shouldn't occour in tests unless an unkown counterparty_node_id
1216                                                         // has been passed to our message handling functions.
1217                                                         let expected_error_str = format!("Can't find a peer matching the passed counterparty node_id {}", $counterparty_node_id);
1218                                                         match err.action {
1219                                                                 msgs::ErrorAction::SendErrorMessage {
1220                                                                         msg: msgs::ErrorMessage { ref channel_id, ref data }
1221                                                                 }
1222                                                                 => {
1223                                                                         assert_eq!(*data, expected_error_str);
1224                                                                         if let Some((err_channel_id, _user_channel_id)) = chan_id {
1225                                                                                 debug_assert_eq!(*channel_id, err_channel_id);
1226                                                                         }
1227                                                                 }
1228                                                                 _ => debug_assert!(false, "Unexpected event"),
1229                                                         }
1230                                                 }
1231                                         }
1232                                 }
1233
1234                                 // Return error in case higher-API need one
1235                                 Err(err)
1236                         },
1237                 }
1238         }
1239 }
1240
1241 macro_rules! update_maps_on_chan_removal {
1242         ($self: expr, $channel: expr) => {{
1243                 $self.id_to_peer.lock().unwrap().remove(&$channel.channel_id());
1244                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1245                 if let Some(short_id) = $channel.get_short_channel_id() {
1246                         short_to_chan_info.remove(&short_id);
1247                 } else {
1248                         // If the channel was never confirmed on-chain prior to its closure, remove the
1249                         // outbound SCID alias we used for it from the collision-prevention set. While we
1250                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
1251                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
1252                         // opening a million channels with us which are closed before we ever reach the funding
1253                         // stage.
1254                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel.outbound_scid_alias());
1255                         debug_assert!(alias_removed);
1256                 }
1257                 short_to_chan_info.remove(&$channel.outbound_scid_alias());
1258         }}
1259 }
1260
1261 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
1262 macro_rules! convert_chan_err {
1263         ($self: ident, $err: expr, $channel: expr, $channel_id: expr) => {
1264                 match $err {
1265                         ChannelError::Warn(msg) => {
1266                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), $channel_id.clone()))
1267                         },
1268                         ChannelError::Ignore(msg) => {
1269                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $channel_id.clone()))
1270                         },
1271                         ChannelError::Close(msg) => {
1272                                 log_error!($self.logger, "Closing channel {} due to close-required error: {}", log_bytes!($channel_id[..]), msg);
1273                                 update_maps_on_chan_removal!($self, $channel);
1274                                 let shutdown_res = $channel.force_shutdown(true);
1275                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, $channel.get_user_id(),
1276                                         shutdown_res, $self.get_channel_update_for_broadcast(&$channel).ok()))
1277                         },
1278                 }
1279         }
1280 }
1281
1282 macro_rules! break_chan_entry {
1283         ($self: ident, $res: expr, $entry: expr) => {
1284                 match $res {
1285                         Ok(res) => res,
1286                         Err(e) => {
1287                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut(), $entry.key());
1288                                 if drop {
1289                                         $entry.remove_entry();
1290                                 }
1291                                 break Err(res);
1292                         }
1293                 }
1294         }
1295 }
1296
1297 macro_rules! try_chan_entry {
1298         ($self: ident, $res: expr, $entry: expr) => {
1299                 match $res {
1300                         Ok(res) => res,
1301                         Err(e) => {
1302                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut(), $entry.key());
1303                                 if drop {
1304                                         $entry.remove_entry();
1305                                 }
1306                                 return Err(res);
1307                         }
1308                 }
1309         }
1310 }
1311
1312 macro_rules! remove_channel {
1313         ($self: expr, $entry: expr) => {
1314                 {
1315                         let channel = $entry.remove_entry().1;
1316                         update_maps_on_chan_removal!($self, channel);
1317                         channel
1318                 }
1319         }
1320 }
1321
1322 macro_rules! handle_monitor_update_res {
1323         ($self: ident, $err: expr, $chan: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $resend_channel_ready: expr, $failed_forwards: expr, $failed_fails: expr, $failed_finalized_fulfills: expr, $chan_id: expr) => {
1324                 match $err {
1325                         ChannelMonitorUpdateStatus::PermanentFailure => {
1326                                 log_error!($self.logger, "Closing channel {} due to monitor update ChannelMonitorUpdateStatus::PermanentFailure", log_bytes!($chan_id[..]));
1327                                 update_maps_on_chan_removal!($self, $chan);
1328                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
1329                                 // chain in a confused state! We need to move them into the ChannelMonitor which
1330                                 // will be responsible for failing backwards once things confirm on-chain.
1331                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
1332                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
1333                                 // us bother trying to claim it just to forward on to another peer. If we're
1334                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
1335                                 // given up the preimage yet, so might as well just wait until the payment is
1336                                 // retried, avoiding the on-chain fees.
1337                                 let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure".to_owned(), *$chan_id, $chan.get_user_id(),
1338                                                 $chan.force_shutdown(false), $self.get_channel_update_for_broadcast(&$chan).ok() ));
1339                                 (res, true)
1340                         },
1341                         ChannelMonitorUpdateStatus::InProgress => {
1342                                 log_info!($self.logger, "Disabling channel {} due to monitor update in progress. On restore will send {} and process {} forwards, {} fails, and {} fulfill finalizations",
1343                                                 log_bytes!($chan_id[..]),
1344                                                 if $resend_commitment && $resend_raa {
1345                                                                 match $action_type {
1346                                                                         RAACommitmentOrder::CommitmentFirst => { "commitment then RAA" },
1347                                                                         RAACommitmentOrder::RevokeAndACKFirst => { "RAA then commitment" },
1348                                                                 }
1349                                                         } else if $resend_commitment { "commitment" }
1350                                                         else if $resend_raa { "RAA" }
1351                                                         else { "nothing" },
1352                                                 (&$failed_forwards as &Vec<(PendingHTLCInfo, u64)>).len(),
1353                                                 (&$failed_fails as &Vec<(HTLCSource, PaymentHash, HTLCFailReason)>).len(),
1354                                                 (&$failed_finalized_fulfills as &Vec<HTLCSource>).len());
1355                                 if !$resend_commitment {
1356                                         debug_assert!($action_type == RAACommitmentOrder::RevokeAndACKFirst || !$resend_raa);
1357                                 }
1358                                 if !$resend_raa {
1359                                         debug_assert!($action_type == RAACommitmentOrder::CommitmentFirst || !$resend_commitment);
1360                                 }
1361                                 $chan.monitor_updating_paused($resend_raa, $resend_commitment, $resend_channel_ready, $failed_forwards, $failed_fails, $failed_finalized_fulfills);
1362                                 (Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor".to_owned()), *$chan_id)), false)
1363                         },
1364                         ChannelMonitorUpdateStatus::Completed => {
1365                                 (Ok(()), false)
1366                         },
1367                 }
1368         };
1369         ($self: ident, $err: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $resend_channel_ready: expr, $failed_forwards: expr, $failed_fails: expr, $failed_finalized_fulfills: expr) => { {
1370                 let (res, drop) = handle_monitor_update_res!($self, $err, $entry.get_mut(), $action_type, $resend_raa, $resend_commitment, $resend_channel_ready, $failed_forwards, $failed_fails, $failed_finalized_fulfills, $entry.key());
1371                 if drop {
1372                         $entry.remove_entry();
1373                 }
1374                 res
1375         } };
1376         ($self: ident, $err: expr, $entry: expr, $action_type: path, $chan_id: expr, COMMITMENT_UPDATE_ONLY) => { {
1377                 debug_assert!($action_type == RAACommitmentOrder::CommitmentFirst);
1378                 handle_monitor_update_res!($self, $err, $entry, $action_type, false, true, false, Vec::new(), Vec::new(), Vec::new(), $chan_id)
1379         } };
1380         ($self: ident, $err: expr, $entry: expr, $action_type: path, $chan_id: expr, NO_UPDATE) => {
1381                 handle_monitor_update_res!($self, $err, $entry, $action_type, false, false, false, Vec::new(), Vec::new(), Vec::new(), $chan_id)
1382         };
1383         ($self: ident, $err: expr, $entry: expr, $action_type: path, $resend_channel_ready: expr, OPTIONALLY_RESEND_FUNDING_LOCKED) => {
1384                 handle_monitor_update_res!($self, $err, $entry, $action_type, false, false, $resend_channel_ready, Vec::new(), Vec::new(), Vec::new())
1385         };
1386         ($self: ident, $err: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
1387                 handle_monitor_update_res!($self, $err, $entry, $action_type, $resend_raa, $resend_commitment, false, Vec::new(), Vec::new(), Vec::new())
1388         };
1389         ($self: ident, $err: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
1390                 handle_monitor_update_res!($self, $err, $entry, $action_type, $resend_raa, $resend_commitment, false, $failed_forwards, $failed_fails, Vec::new())
1391         };
1392 }
1393
1394 macro_rules! send_channel_ready {
1395         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
1396                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
1397                         node_id: $channel.get_counterparty_node_id(),
1398                         msg: $channel_ready_msg,
1399                 });
1400                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
1401                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
1402                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1403                 let outbound_alias_insert = short_to_chan_info.insert($channel.outbound_scid_alias(), ($channel.get_counterparty_node_id(), $channel.channel_id()));
1404                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.get_counterparty_node_id(), $channel.channel_id()),
1405                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
1406                 if let Some(real_scid) = $channel.get_short_channel_id() {
1407                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.get_counterparty_node_id(), $channel.channel_id()));
1408                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.get_counterparty_node_id(), $channel.channel_id()),
1409                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
1410                 }
1411         }}
1412 }
1413
1414 macro_rules! emit_channel_ready_event {
1415         ($self: expr, $channel: expr) => {
1416                 if $channel.should_emit_channel_ready_event() {
1417                         {
1418                                 let mut pending_events = $self.pending_events.lock().unwrap();
1419                                 pending_events.push(events::Event::ChannelReady {
1420                                         channel_id: $channel.channel_id(),
1421                                         user_channel_id: $channel.get_user_id(),
1422                                         counterparty_node_id: $channel.get_counterparty_node_id(),
1423                                         channel_type: $channel.get_channel_type().clone(),
1424                                 });
1425                         }
1426                         $channel.set_channel_ready_event_emitted();
1427                 }
1428         }
1429 }
1430
1431 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>
1432 where
1433         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
1434         T::Target: BroadcasterInterface,
1435         ES::Target: EntropySource,
1436         NS::Target: NodeSigner,
1437         SP::Target: SignerProvider,
1438         F::Target: FeeEstimator,
1439         R::Target: Router,
1440         L::Target: Logger,
1441 {
1442         /// Constructs a new ChannelManager to hold several channels and route between them.
1443         ///
1444         /// This is the main "logic hub" for all channel-related actions, and implements
1445         /// ChannelMessageHandler.
1446         ///
1447         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
1448         ///
1449         /// Users need to notify the new ChannelManager when a new block is connected or
1450         /// disconnected using its `block_connected` and `block_disconnected` methods, starting
1451         /// from after `params.latest_hash`.
1452         pub fn new(fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES, node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters) -> Self {
1453                 let mut secp_ctx = Secp256k1::new();
1454                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
1455                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
1456                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
1457                 ChannelManager {
1458                         default_configuration: config.clone(),
1459                         genesis_hash: genesis_block(params.network).header.block_hash(),
1460                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
1461                         chain_monitor,
1462                         tx_broadcaster,
1463                         router,
1464
1465                         best_block: RwLock::new(params.best_block),
1466
1467                         outbound_scid_aliases: Mutex::new(HashSet::new()),
1468                         pending_inbound_payments: Mutex::new(HashMap::new()),
1469                         pending_outbound_payments: OutboundPayments::new(),
1470                         forward_htlcs: Mutex::new(HashMap::new()),
1471                         claimable_payments: Mutex::new(ClaimablePayments { claimable_htlcs: HashMap::new(), pending_claiming_payments: HashMap::new() }),
1472                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
1473                         id_to_peer: Mutex::new(HashMap::new()),
1474                         short_to_chan_info: FairRwLock::new(HashMap::new()),
1475
1476                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
1477                         secp_ctx,
1478
1479                         inbound_payment_key: expanded_inbound_key,
1480                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
1481
1482                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
1483
1484                         highest_seen_timestamp: AtomicUsize::new(0),
1485
1486                         per_peer_state: FairRwLock::new(HashMap::new()),
1487
1488                         pending_events: Mutex::new(Vec::new()),
1489                         pending_background_events: Mutex::new(Vec::new()),
1490                         total_consistency_lock: RwLock::new(()),
1491                         persistence_notifier: Notifier::new(),
1492
1493                         entropy_source,
1494                         node_signer,
1495                         signer_provider,
1496
1497                         logger,
1498                 }
1499         }
1500
1501         /// Gets the current configuration applied to all new channels.
1502         pub fn get_current_default_configuration(&self) -> &UserConfig {
1503                 &self.default_configuration
1504         }
1505
1506         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
1507                 let height = self.best_block.read().unwrap().height();
1508                 let mut outbound_scid_alias = 0;
1509                 let mut i = 0;
1510                 loop {
1511                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
1512                                 outbound_scid_alias += 1;
1513                         } else {
1514                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
1515                         }
1516                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
1517                                 break;
1518                         }
1519                         i += 1;
1520                         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"); }
1521                 }
1522                 outbound_scid_alias
1523         }
1524
1525         /// Creates a new outbound channel to the given remote node and with the given value.
1526         ///
1527         /// `user_channel_id` will be provided back as in
1528         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
1529         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
1530         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
1531         /// is simply copied to events and otherwise ignored.
1532         ///
1533         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
1534         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
1535         ///
1536         /// Note that we do not check if you are currently connected to the given peer. If no
1537         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
1538         /// the channel eventually being silently forgotten (dropped on reload).
1539         ///
1540         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
1541         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
1542         /// [`ChannelDetails::channel_id`] until after
1543         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
1544         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
1545         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
1546         ///
1547         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
1548         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
1549         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
1550         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> {
1551                 if channel_value_satoshis < 1000 {
1552                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
1553                 }
1554
1555                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
1556                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
1557                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
1558
1559                 let per_peer_state = self.per_peer_state.read().unwrap();
1560
1561                 let peer_state_mutex_opt = per_peer_state.get(&their_network_key);
1562                 if let None = peer_state_mutex_opt {
1563                         return Err(APIError::APIMisuseError { err: format!("Not connected to node: {}", their_network_key) });
1564                 }
1565
1566                 let mut peer_state = peer_state_mutex_opt.unwrap().lock().unwrap();
1567                 let channel = {
1568                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
1569                         let their_features = &peer_state.latest_features;
1570                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
1571                         match Channel::new_outbound(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
1572                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
1573                                 self.best_block.read().unwrap().height(), outbound_scid_alias)
1574                         {
1575                                 Ok(res) => res,
1576                                 Err(e) => {
1577                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
1578                                         return Err(e);
1579                                 },
1580                         }
1581                 };
1582                 let res = channel.get_open_channel(self.genesis_hash.clone());
1583
1584                 let temporary_channel_id = channel.channel_id();
1585                 match peer_state.channel_by_id.entry(temporary_channel_id) {
1586                         hash_map::Entry::Occupied(_) => {
1587                                 if cfg!(fuzzing) {
1588                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
1589                                 } else {
1590                                         panic!("RNG is bad???");
1591                                 }
1592                         },
1593                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
1594                 }
1595
1596                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
1597                         node_id: their_network_key,
1598                         msg: res,
1599                 });
1600                 Ok(temporary_channel_id)
1601         }
1602
1603         fn list_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<<SP::Target as SignerProvider>::Signer>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
1604                 let mut res = Vec::new();
1605                 // Allocate our best estimate of the number of channels we have in the `res`
1606                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
1607                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
1608                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
1609                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
1610                 // the same channel.
1611                 res.reserve(self.short_to_chan_info.read().unwrap().len());
1612                 {
1613                         let best_block_height = self.best_block.read().unwrap().height();
1614                         let per_peer_state = self.per_peer_state.read().unwrap();
1615                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
1616                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
1617                                 let peer_state = &mut *peer_state_lock;
1618                                 for (channel_id, channel) in peer_state.channel_by_id.iter().filter(f) {
1619                                         let balance = channel.get_available_balances();
1620                                         let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1621                                                 channel.get_holder_counterparty_selected_channel_reserve_satoshis();
1622                                         res.push(ChannelDetails {
1623                                                 channel_id: (*channel_id).clone(),
1624                                                 counterparty: ChannelCounterparty {
1625                                                         node_id: channel.get_counterparty_node_id(),
1626                                                         features: peer_state.latest_features.clone(),
1627                                                         unspendable_punishment_reserve: to_remote_reserve_satoshis,
1628                                                         forwarding_info: channel.counterparty_forwarding_info(),
1629                                                         // Ensures that we have actually received the `htlc_minimum_msat` value
1630                                                         // from the counterparty through the `OpenChannel` or `AcceptChannel`
1631                                                         // message (as they are always the first message from the counterparty).
1632                                                         // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1633                                                         // default `0` value set by `Channel::new_outbound`.
1634                                                         outbound_htlc_minimum_msat: if channel.have_received_message() {
1635                                                                 Some(channel.get_counterparty_htlc_minimum_msat()) } else { None },
1636                                                         outbound_htlc_maximum_msat: channel.get_counterparty_htlc_maximum_msat(),
1637                                                 },
1638                                                 funding_txo: channel.get_funding_txo(),
1639                                                 // Note that accept_channel (or open_channel) is always the first message, so
1640                                                 // `have_received_message` indicates that type negotiation has completed.
1641                                                 channel_type: if channel.have_received_message() { Some(channel.get_channel_type().clone()) } else { None },
1642                                                 short_channel_id: channel.get_short_channel_id(),
1643                                                 outbound_scid_alias: if channel.is_usable() { Some(channel.outbound_scid_alias()) } else { None },
1644                                                 inbound_scid_alias: channel.latest_inbound_scid_alias(),
1645                                                 channel_value_satoshis: channel.get_value_satoshis(),
1646                                                 unspendable_punishment_reserve: to_self_reserve_satoshis,
1647                                                 balance_msat: balance.balance_msat,
1648                                                 inbound_capacity_msat: balance.inbound_capacity_msat,
1649                                                 outbound_capacity_msat: balance.outbound_capacity_msat,
1650                                                 next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1651                                                 user_channel_id: channel.get_user_id(),
1652                                                 confirmations_required: channel.minimum_depth(),
1653                                                 confirmations: Some(channel.get_funding_tx_confirmations(best_block_height)),
1654                                                 force_close_spend_delay: channel.get_counterparty_selected_contest_delay(),
1655                                                 is_outbound: channel.is_outbound(),
1656                                                 is_channel_ready: channel.is_usable(),
1657                                                 is_usable: channel.is_live(),
1658                                                 is_public: channel.should_announce(),
1659                                                 inbound_htlc_minimum_msat: Some(channel.get_holder_htlc_minimum_msat()),
1660                                                 inbound_htlc_maximum_msat: channel.get_holder_htlc_maximum_msat(),
1661                                                 config: Some(channel.config()),
1662                                         });
1663                                 }
1664                         }
1665                 }
1666                 res
1667         }
1668
1669         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
1670         /// more information.
1671         pub fn list_channels(&self) -> Vec<ChannelDetails> {
1672                 self.list_channels_with_filter(|_| true)
1673         }
1674
1675         /// Gets the list of usable channels, in random order. Useful as an argument to [`find_route`]
1676         /// to ensure non-announced channels are used.
1677         ///
1678         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
1679         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
1680         /// are.
1681         ///
1682         /// [`find_route`]: crate::routing::router::find_route
1683         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
1684                 // Note we use is_live here instead of usable which leads to somewhat confused
1685                 // internal/external nomenclature, but that's ok cause that's probably what the user
1686                 // really wanted anyway.
1687                 self.list_channels_with_filter(|&(_, ref channel)| channel.is_live())
1688         }
1689
1690         /// Helper function that issues the channel close events
1691         fn issue_channel_close_events(&self, channel: &Channel<<SP::Target as SignerProvider>::Signer>, closure_reason: ClosureReason) {
1692                 let mut pending_events_lock = self.pending_events.lock().unwrap();
1693                 match channel.unbroadcasted_funding() {
1694                         Some(transaction) => {
1695                                 pending_events_lock.push(events::Event::DiscardFunding { channel_id: channel.channel_id(), transaction })
1696                         },
1697                         None => {},
1698                 }
1699                 pending_events_lock.push(events::Event::ChannelClosed {
1700                         channel_id: channel.channel_id(),
1701                         user_channel_id: channel.get_user_id(),
1702                         reason: closure_reason
1703                 });
1704         }
1705
1706         fn close_channel_internal(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: Option<u32>) -> Result<(), APIError> {
1707                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
1708
1709                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)>;
1710                 let result: Result<(), _> = loop {
1711                         let per_peer_state = self.per_peer_state.read().unwrap();
1712
1713                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
1714                         if let None = peer_state_mutex_opt {
1715                                 return Err(APIError::APIMisuseError { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) });
1716                         }
1717
1718                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
1719                         let peer_state = &mut *peer_state_lock;
1720                         match peer_state.channel_by_id.entry(channel_id.clone()) {
1721                                 hash_map::Entry::Occupied(mut chan_entry) => {
1722                                         let (shutdown_msg, monitor_update, htlcs) = chan_entry.get_mut().get_shutdown(&self.signer_provider, &peer_state.latest_features, target_feerate_sats_per_1000_weight)?;
1723                                         failed_htlcs = htlcs;
1724
1725                                         // Update the monitor with the shutdown script if necessary.
1726                                         if let Some(monitor_update) = monitor_update {
1727                                                 let update_res = self.chain_monitor.update_channel(chan_entry.get().get_funding_txo().unwrap(), &monitor_update);
1728                                                 let (result, is_permanent) =
1729                                                         handle_monitor_update_res!(self, update_res, chan_entry.get_mut(), RAACommitmentOrder::CommitmentFirst, chan_entry.key(), NO_UPDATE);
1730                                                 if is_permanent {
1731                                                         remove_channel!(self, chan_entry);
1732                                                         break result;
1733                                                 }
1734                                         }
1735
1736                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1737                                                 node_id: *counterparty_node_id,
1738                                                 msg: shutdown_msg
1739                                         });
1740
1741                                         if chan_entry.get().is_shutdown() {
1742                                                 let channel = remove_channel!(self, chan_entry);
1743                                                 if let Ok(channel_update) = self.get_channel_update_for_broadcast(&channel) {
1744                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1745                                                                 msg: channel_update
1746                                                         });
1747                                                 }
1748                                                 self.issue_channel_close_events(&channel, ClosureReason::HolderForceClosed);
1749                                         }
1750                                         break Ok(());
1751                                 },
1752                                 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) })
1753                         }
1754                 };
1755
1756                 for htlc_source in failed_htlcs.drain(..) {
1757                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
1758                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
1759                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
1760                 }
1761
1762                 let _ = handle_error!(self, result, *counterparty_node_id);
1763                 Ok(())
1764         }
1765
1766         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
1767         /// will be accepted on the given channel, and after additional timeout/the closing of all
1768         /// pending HTLCs, the channel will be closed on chain.
1769         ///
1770         ///  * If we are the channel initiator, we will pay between our [`Background`] and
1771         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
1772         ///    estimate.
1773         ///  * If our counterparty is the channel initiator, we will require a channel closing
1774         ///    transaction feerate of at least our [`Background`] feerate or the feerate which
1775         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
1776         ///    counterparty to pay as much fee as they'd like, however.
1777         ///
1778         /// May generate a SendShutdown message event on success, which should be relayed.
1779         ///
1780         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
1781         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
1782         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
1783         pub fn close_channel(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey) -> Result<(), APIError> {
1784                 self.close_channel_internal(channel_id, counterparty_node_id, None)
1785         }
1786
1787         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
1788         /// will be accepted on the given channel, and after additional timeout/the closing of all
1789         /// pending HTLCs, the channel will be closed on chain.
1790         ///
1791         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
1792         /// the channel being closed or not:
1793         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
1794         ///    transaction. The upper-bound is set by
1795         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
1796         ///    estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
1797         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
1798         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
1799         ///    will appear on a force-closure transaction, whichever is lower).
1800         ///
1801         /// May generate a SendShutdown message event on success, which should be relayed.
1802         ///
1803         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
1804         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
1805         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
1806         pub fn close_channel_with_target_feerate(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: u32) -> Result<(), APIError> {
1807                 self.close_channel_internal(channel_id, counterparty_node_id, Some(target_feerate_sats_per_1000_weight))
1808         }
1809
1810         #[inline]
1811         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
1812                 let (monitor_update_option, mut failed_htlcs) = shutdown_res;
1813                 log_debug!(self.logger, "Finishing force-closure of channel with {} HTLCs to fail", failed_htlcs.len());
1814                 for htlc_source in failed_htlcs.drain(..) {
1815                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
1816                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
1817                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
1818                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
1819                 }
1820                 if let Some((funding_txo, monitor_update)) = monitor_update_option {
1821                         // There isn't anything we can do if we get an update failure - we're already
1822                         // force-closing. The monitor update on the required in-memory copy should broadcast
1823                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
1824                         // ignore the result here.
1825                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
1826                 }
1827         }
1828
1829         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
1830         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
1831         fn force_close_channel_with_peer(&self, channel_id: &[u8; 32], peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
1832         -> Result<PublicKey, APIError> {
1833                 let per_peer_state = self.per_peer_state.read().unwrap();
1834                 let peer_state_mutex_opt = per_peer_state.get(peer_node_id);
1835                 let mut chan = {
1836                         if let None = peer_state_mutex_opt {
1837                                 return Err(APIError::APIMisuseError{ err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) });
1838                         }
1839                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
1840                         let peer_state = &mut *peer_state_lock;
1841                         if let hash_map::Entry::Occupied(chan) = peer_state.channel_by_id.entry(channel_id.clone()) {
1842                                 if let Some(peer_msg) = peer_msg {
1843                                         self.issue_channel_close_events(chan.get(),ClosureReason::CounterpartyForceClosed { peer_msg: peer_msg.to_string() });
1844                                 } else {
1845                                         self.issue_channel_close_events(chan.get(),ClosureReason::HolderForceClosed);
1846                                 }
1847                                 remove_channel!(self, chan)
1848                         } else {
1849                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(*channel_id), peer_node_id) });
1850                         }
1851                 };
1852                 log_error!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
1853                 self.finish_force_close_channel(chan.force_shutdown(broadcast));
1854                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
1855                         let mut peer_state = peer_state_mutex_opt.unwrap().lock().unwrap();
1856                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1857                                 msg: update
1858                         });
1859                 }
1860
1861                 Ok(chan.get_counterparty_node_id())
1862         }
1863
1864         fn force_close_sending_error(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
1865                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
1866                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
1867                         Ok(counterparty_node_id) => {
1868                                 let per_peer_state = self.per_peer_state.read().unwrap();
1869                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
1870                                         let mut peer_state = peer_state_mutex.lock().unwrap();
1871                                         peer_state.pending_msg_events.push(
1872                                                 events::MessageSendEvent::HandleError {
1873                                                         node_id: counterparty_node_id,
1874                                                         action: msgs::ErrorAction::SendErrorMessage {
1875                                                                 msg: msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() }
1876                                                         },
1877                                                 }
1878                                         );
1879                                 }
1880                                 Ok(())
1881                         },
1882                         Err(e) => Err(e)
1883                 }
1884         }
1885
1886         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
1887         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
1888         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
1889         /// channel.
1890         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey)
1891         -> Result<(), APIError> {
1892                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
1893         }
1894
1895         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
1896         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
1897         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
1898         ///
1899         /// You can always get the latest local transaction(s) to broadcast from
1900         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
1901         pub fn force_close_without_broadcasting_txn(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey)
1902         -> Result<(), APIError> {
1903                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
1904         }
1905
1906         /// Force close all channels, immediately broadcasting the latest local commitment transaction
1907         /// for each to the chain and rejecting new HTLCs on each.
1908         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
1909                 for chan in self.list_channels() {
1910                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
1911                 }
1912         }
1913
1914         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
1915         /// local transaction(s).
1916         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
1917                 for chan in self.list_channels() {
1918                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
1919                 }
1920         }
1921
1922         fn construct_recv_pending_htlc_info(&self, hop_data: msgs::OnionHopData, shared_secret: [u8; 32],
1923                 payment_hash: PaymentHash, amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>) -> Result<PendingHTLCInfo, ReceiveError>
1924         {
1925                 // final_incorrect_cltv_expiry
1926                 if hop_data.outgoing_cltv_value != cltv_expiry {
1927                         return Err(ReceiveError {
1928                                 msg: "Upstream node set CLTV to the wrong value",
1929                                 err_code: 18,
1930                                 err_data: cltv_expiry.to_be_bytes().to_vec()
1931                         })
1932                 }
1933                 // final_expiry_too_soon
1934                 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure
1935                 // we have at least HTLC_FAIL_BACK_BUFFER blocks to go.
1936                 //
1937                 // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
1938                 // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
1939                 // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
1940                 let current_height: u32 = self.best_block.read().unwrap().height();
1941                 if (hop_data.outgoing_cltv_value as u64) <= current_height as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1 {
1942                         let mut err_data = Vec::with_capacity(12);
1943                         err_data.extend_from_slice(&amt_msat.to_be_bytes());
1944                         err_data.extend_from_slice(&current_height.to_be_bytes());
1945                         return Err(ReceiveError {
1946                                 err_code: 0x4000 | 15, err_data,
1947                                 msg: "The final CLTV expiry is too soon to handle",
1948                         });
1949                 }
1950                 if hop_data.amt_to_forward > amt_msat {
1951                         return Err(ReceiveError {
1952                                 err_code: 19,
1953                                 err_data: amt_msat.to_be_bytes().to_vec(),
1954                                 msg: "Upstream node sent less than we were supposed to receive in payment",
1955                         });
1956                 }
1957
1958                 let routing = match hop_data.format {
1959                         msgs::OnionHopDataFormat::NonFinalNode { .. } => {
1960                                 return Err(ReceiveError {
1961                                         err_code: 0x4000|22,
1962                                         err_data: Vec::new(),
1963                                         msg: "Got non final data with an HMAC of 0",
1964                                 });
1965                         },
1966                         msgs::OnionHopDataFormat::FinalNode { payment_data, keysend_preimage } => {
1967                                 if payment_data.is_some() && keysend_preimage.is_some() {
1968                                         return Err(ReceiveError {
1969                                                 err_code: 0x4000|22,
1970                                                 err_data: Vec::new(),
1971                                                 msg: "We don't support MPP keysend payments",
1972                                         });
1973                                 } else if let Some(data) = payment_data {
1974                                         PendingHTLCRouting::Receive {
1975                                                 payment_data: data,
1976                                                 incoming_cltv_expiry: hop_data.outgoing_cltv_value,
1977                                                 phantom_shared_secret,
1978                                         }
1979                                 } else if let Some(payment_preimage) = keysend_preimage {
1980                                         // We need to check that the sender knows the keysend preimage before processing this
1981                                         // payment further. Otherwise, an intermediary routing hop forwarding non-keysend-HTLC X
1982                                         // could discover the final destination of X, by probing the adjacent nodes on the route
1983                                         // with a keysend payment of identical payment hash to X and observing the processing
1984                                         // time discrepancies due to a hash collision with X.
1985                                         let hashed_preimage = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1986                                         if hashed_preimage != payment_hash {
1987                                                 return Err(ReceiveError {
1988                                                         err_code: 0x4000|22,
1989                                                         err_data: Vec::new(),
1990                                                         msg: "Payment preimage didn't match payment hash",
1991                                                 });
1992                                         }
1993
1994                                         PendingHTLCRouting::ReceiveKeysend {
1995                                                 payment_preimage,
1996                                                 incoming_cltv_expiry: hop_data.outgoing_cltv_value,
1997                                         }
1998                                 } else {
1999                                         return Err(ReceiveError {
2000                                                 err_code: 0x4000|0x2000|3,
2001                                                 err_data: Vec::new(),
2002                                                 msg: "We require payment_secrets",
2003                                         });
2004                                 }
2005                         },
2006                 };
2007                 Ok(PendingHTLCInfo {
2008                         routing,
2009                         payment_hash,
2010                         incoming_shared_secret: shared_secret,
2011                         incoming_amt_msat: Some(amt_msat),
2012                         outgoing_amt_msat: amt_msat,
2013                         outgoing_cltv_value: hop_data.outgoing_cltv_value,
2014                 })
2015         }
2016
2017         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> PendingHTLCStatus {
2018                 macro_rules! return_malformed_err {
2019                         ($msg: expr, $err_code: expr) => {
2020                                 {
2021                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2022                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
2023                                                 channel_id: msg.channel_id,
2024                                                 htlc_id: msg.htlc_id,
2025                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
2026                                                 failure_code: $err_code,
2027                                         }));
2028                                 }
2029                         }
2030                 }
2031
2032                 if let Err(_) = msg.onion_routing_packet.public_key {
2033                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
2034                 }
2035
2036                 let shared_secret = self.node_signer.ecdh(
2037                         Recipient::Node, &msg.onion_routing_packet.public_key.unwrap(), None
2038                 ).unwrap().secret_bytes();
2039
2040                 if msg.onion_routing_packet.version != 0 {
2041                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
2042                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
2043                         //the hash doesn't really serve any purpose - in the case of hashing all data, the
2044                         //receiving node would have to brute force to figure out which version was put in the
2045                         //packet by the node that send us the message, in the case of hashing the hop_data, the
2046                         //node knows the HMAC matched, so they already know what is there...
2047                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
2048                 }
2049                 macro_rules! return_err {
2050                         ($msg: expr, $err_code: expr, $data: expr) => {
2051                                 {
2052                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2053                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2054                                                 channel_id: msg.channel_id,
2055                                                 htlc_id: msg.htlc_id,
2056                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
2057                                                         .get_encrypted_failure_packet(&shared_secret, &None),
2058                                         }));
2059                                 }
2060                         }
2061                 }
2062
2063                 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) {
2064                         Ok(res) => res,
2065                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
2066                                 return_malformed_err!(err_msg, err_code);
2067                         },
2068                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
2069                                 return_err!(err_msg, err_code, &[0; 0]);
2070                         },
2071                 };
2072
2073                 let pending_forward_info = match next_hop {
2074                         onion_utils::Hop::Receive(next_hop_data) => {
2075                                 // OUR PAYMENT!
2076                                 match self.construct_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash, msg.amount_msat, msg.cltv_expiry, None) {
2077                                         Ok(info) => {
2078                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
2079                                                 // message, however that would leak that we are the recipient of this payment, so
2080                                                 // instead we stay symmetric with the forwarding case, only responding (after a
2081                                                 // delay) once they've send us a commitment_signed!
2082                                                 PendingHTLCStatus::Forward(info)
2083                                         },
2084                                         Err(ReceiveError { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
2085                                 }
2086                         },
2087                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
2088                                 let new_pubkey = msg.onion_routing_packet.public_key.unwrap();
2089                                 let outgoing_packet = msgs::OnionPacket {
2090                                         version: 0,
2091                                         public_key: onion_utils::next_hop_packet_pubkey(&self.secp_ctx, new_pubkey, &shared_secret),
2092                                         hop_data: new_packet_bytes,
2093                                         hmac: next_hop_hmac.clone(),
2094                                 };
2095
2096                                 let short_channel_id = match next_hop_data.format {
2097                                         msgs::OnionHopDataFormat::NonFinalNode { short_channel_id } => short_channel_id,
2098                                         msgs::OnionHopDataFormat::FinalNode { .. } => {
2099                                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0;0]);
2100                                         },
2101                                 };
2102
2103                                 PendingHTLCStatus::Forward(PendingHTLCInfo {
2104                                         routing: PendingHTLCRouting::Forward {
2105                                                 onion_packet: outgoing_packet,
2106                                                 short_channel_id,
2107                                         },
2108                                         payment_hash: msg.payment_hash.clone(),
2109                                         incoming_shared_secret: shared_secret,
2110                                         incoming_amt_msat: Some(msg.amount_msat),
2111                                         outgoing_amt_msat: next_hop_data.amt_to_forward,
2112                                         outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
2113                                 })
2114                         }
2115                 };
2116
2117                 if let &PendingHTLCStatus::Forward(PendingHTLCInfo { ref routing, ref outgoing_amt_msat, ref outgoing_cltv_value, .. }) = &pending_forward_info {
2118                         // If short_channel_id is 0 here, we'll reject the HTLC as there cannot be a channel
2119                         // with a short_channel_id of 0. This is important as various things later assume
2120                         // short_channel_id is non-0 in any ::Forward.
2121                         if let &PendingHTLCRouting::Forward { ref short_channel_id, .. } = routing {
2122                                 if let Some((err, mut code, chan_update)) = loop {
2123                                         let id_option = self.short_to_chan_info.read().unwrap().get(short_channel_id).cloned();
2124                                         let forwarding_chan_info_opt = match id_option {
2125                                                 None => { // unknown_next_peer
2126                                                         // Note that this is likely a timing oracle for detecting whether an scid is a
2127                                                         // phantom or an intercept.
2128                                                         if (self.default_configuration.accept_intercept_htlcs &&
2129                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, *short_channel_id, &self.genesis_hash)) ||
2130                                                            fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, *short_channel_id, &self.genesis_hash)
2131                                                         {
2132                                                                 None
2133                                                         } else {
2134                                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2135                                                         }
2136                                                 },
2137                                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
2138                                         };
2139                                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
2140                                                 let per_peer_state = self.per_peer_state.read().unwrap();
2141                                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
2142                                                 if let None = peer_state_mutex_opt {
2143                                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2144                                                 }
2145                                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
2146                                                 let peer_state = &mut *peer_state_lock;
2147                                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id) {
2148                                                         None => {
2149                                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
2150                                                                 // have no consistency guarantees.
2151                                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2152                                                         },
2153                                                         Some(chan) => chan
2154                                                 };
2155                                                 if !chan.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
2156                                                         // Note that the behavior here should be identical to the above block - we
2157                                                         // should NOT reveal the existence or non-existence of a private channel if
2158                                                         // we don't allow forwards outbound over them.
2159                                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
2160                                                 }
2161                                                 if chan.get_channel_type().supports_scid_privacy() && *short_channel_id != chan.outbound_scid_alias() {
2162                                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
2163                                                         // "refuse to forward unless the SCID alias was used", so we pretend
2164                                                         // we don't have the channel here.
2165                                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
2166                                                 }
2167                                                 let chan_update_opt = self.get_channel_update_for_onion(*short_channel_id, chan).ok();
2168
2169                                                 // Note that we could technically not return an error yet here and just hope
2170                                                 // that the connection is reestablished or monitor updated by the time we get
2171                                                 // around to doing the actual forward, but better to fail early if we can and
2172                                                 // hopefully an attacker trying to path-trace payments cannot make this occur
2173                                                 // on a small/per-node/per-channel scale.
2174                                                 if !chan.is_live() { // channel_disabled
2175                                                         break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, chan_update_opt));
2176                                                 }
2177                                                 if *outgoing_amt_msat < chan.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
2178                                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
2179                                                 }
2180                                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, *outgoing_amt_msat, *outgoing_cltv_value) {
2181                                                         break Some((err, code, chan_update_opt));
2182                                                 }
2183                                                 chan_update_opt
2184                                         } else {
2185                                                 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
2186                                                         // We really should set `incorrect_cltv_expiry` here but as we're not
2187                                                         // forwarding over a real channel we can't generate a channel_update
2188                                                         // for it. Instead we just return a generic temporary_node_failure.
2189                                                         break Some((
2190                                                                 "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
2191                                                                 0x2000 | 2, None,
2192                                                         ));
2193                                                 }
2194                                                 None
2195                                         };
2196
2197                                         let cur_height = self.best_block.read().unwrap().height() + 1;
2198                                         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now,
2199                                         // but we want to be robust wrt to counterparty packet sanitization (see
2200                                         // HTLC_FAIL_BACK_BUFFER rationale).
2201                                         if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
2202                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, chan_update_opt));
2203                                         }
2204                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
2205                                                 break Some(("CLTV expiry is too far in the future", 21, None));
2206                                         }
2207                                         // If the HTLC expires ~now, don't bother trying to forward it to our
2208                                         // counterparty. They should fail it anyway, but we don't want to bother with
2209                                         // the round-trips or risk them deciding they definitely want the HTLC and
2210                                         // force-closing to ensure they get it if we're offline.
2211                                         // We previously had a much more aggressive check here which tried to ensure
2212                                         // our counterparty receives an HTLC which has *our* risk threshold met on it,
2213                                         // but there is no need to do that, and since we're a bit conservative with our
2214                                         // risk threshold it just results in failing to forward payments.
2215                                         if (*outgoing_cltv_value) as u64 <= (cur_height + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
2216                                                 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, chan_update_opt));
2217                                         }
2218
2219                                         break None;
2220                                 }
2221                                 {
2222                                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
2223                                         if let Some(chan_update) = chan_update {
2224                                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
2225                                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
2226                                                 }
2227                                                 else if code == 0x1000 | 13 {
2228                                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
2229                                                 }
2230                                                 else if code == 0x1000 | 20 {
2231                                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
2232                                                         0u16.write(&mut res).expect("Writes cannot fail");
2233                                                 }
2234                                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
2235                                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
2236                                                 chan_update.write(&mut res).expect("Writes cannot fail");
2237                                         } else if code & 0x1000 == 0x1000 {
2238                                                 // If we're trying to return an error that requires a `channel_update` but
2239                                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
2240                                                 // generate an update), just use the generic "temporary_node_failure"
2241                                                 // instead.
2242                                                 code = 0x2000 | 2;
2243                                         }
2244                                         return_err!(err, code, &res.0[..]);
2245                                 }
2246                         }
2247                 }
2248
2249                 pending_forward_info
2250         }
2251
2252         /// Gets the current channel_update for the given channel. This first checks if the channel is
2253         /// public, and thus should be called whenever the result is going to be passed out in a
2254         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
2255         ///
2256         /// May be called with peer_state already locked!
2257         fn get_channel_update_for_broadcast(&self, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
2258                 if !chan.should_announce() {
2259                         return Err(LightningError {
2260                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
2261                                 action: msgs::ErrorAction::IgnoreError
2262                         });
2263                 }
2264                 if chan.get_short_channel_id().is_none() {
2265                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
2266                 }
2267                 log_trace!(self.logger, "Attempting to generate broadcast channel update for channel {}", log_bytes!(chan.channel_id()));
2268                 self.get_channel_update_for_unicast(chan)
2269         }
2270
2271         /// Gets the current channel_update for the given channel. This does not check if the channel
2272         /// is public (only returning an Err if the channel does not yet have an assigned short_id),
2273         /// and thus MUST NOT be called unless the recipient of the resulting message has already
2274         /// provided evidence that they know about the existence of the channel.
2275         /// May be called with peer_state already locked!
2276         fn get_channel_update_for_unicast(&self, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
2277                 log_trace!(self.logger, "Attempting to generate channel update for channel {}", log_bytes!(chan.channel_id()));
2278                 let short_channel_id = match chan.get_short_channel_id().or(chan.latest_inbound_scid_alias()) {
2279                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
2280                         Some(id) => id,
2281                 };
2282
2283                 self.get_channel_update_for_onion(short_channel_id, chan)
2284         }
2285         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
2286                 log_trace!(self.logger, "Generating channel update for channel {}", log_bytes!(chan.channel_id()));
2287                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.get_counterparty_node_id().serialize()[..];
2288
2289                 let unsigned = msgs::UnsignedChannelUpdate {
2290                         chain_hash: self.genesis_hash,
2291                         short_channel_id,
2292                         timestamp: chan.get_update_time_counter(),
2293                         flags: (!were_node_one) as u8 | ((!chan.is_live() as u8) << 1),
2294                         cltv_expiry_delta: chan.get_cltv_expiry_delta(),
2295                         htlc_minimum_msat: chan.get_counterparty_htlc_minimum_msat(),
2296                         htlc_maximum_msat: chan.get_announced_htlc_max_msat(),
2297                         fee_base_msat: chan.get_outbound_forwarding_fee_base_msat(),
2298                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
2299                         excess_data: Vec::new(),
2300                 };
2301                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
2302                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
2303                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
2304                 // channel.
2305                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
2306
2307                 Ok(msgs::ChannelUpdate {
2308                         signature: sig,
2309                         contents: unsigned
2310                 })
2311         }
2312
2313         // Only public for testing, this should otherwise never be called direcly
2314         pub(crate) fn send_payment_along_path(&self, path: &Vec<RouteHop>, payment_params: &Option<PaymentParameters>, payment_hash: &PaymentHash, payment_secret: &Option<PaymentSecret>, total_value: u64, cur_height: u32, payment_id: PaymentId, keysend_preimage: &Option<PaymentPreimage>, session_priv_bytes: [u8; 32]) -> Result<(), APIError> {
2315                 log_trace!(self.logger, "Attempting to send payment for path with next hop {}", path.first().unwrap().short_channel_id);
2316                 let prng_seed = self.entropy_source.get_secure_random_bytes();
2317                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
2318
2319                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
2320                         .map_err(|_| APIError::InvalidRoute{err: "Pubkey along hop was maliciously selected"})?;
2321                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, payment_secret, cur_height, keysend_preimage)?;
2322                 if onion_utils::route_size_insane(&onion_payloads) {
2323                         return Err(APIError::InvalidRoute{err: "Route size too large considering onion data"});
2324                 }
2325                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash);
2326
2327                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2328
2329                 let err: Result<(), _> = loop {
2330                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.first().unwrap().short_channel_id) {
2331                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
2332                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
2333                         };
2334
2335                         let per_peer_state = self.per_peer_state.read().unwrap();
2336                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
2337                         if let None = peer_state_mutex_opt {
2338                                 return Err(APIError::InvalidRoute{err: "No peer matching the path's first hop found!" });
2339                         }
2340                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
2341                         let peer_state = &mut *peer_state_lock;
2342                         if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(id) {
2343                                 match {
2344                                         if !chan.get().is_live() {
2345                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!".to_owned()});
2346                                         }
2347                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(
2348                                                 htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
2349                                                         path: path.clone(),
2350                                                         session_priv: session_priv.clone(),
2351                                                         first_hop_htlc_msat: htlc_msat,
2352                                                         payment_id,
2353                                                         payment_secret: payment_secret.clone(),
2354                                                         payment_params: payment_params.clone(),
2355                                                 }, onion_packet, &self.logger),
2356                                                 chan)
2357                                 } {
2358                                         Some((update_add, commitment_signed, monitor_update)) => {
2359                                                 let update_err = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), &monitor_update);
2360                                                 let chan_id = chan.get().channel_id();
2361                                                 match (update_err,
2362                                                         handle_monitor_update_res!(self, update_err, chan,
2363                                                                 RAACommitmentOrder::CommitmentFirst, false, true))
2364                                                 {
2365                                                         (ChannelMonitorUpdateStatus::PermanentFailure, Err(e)) => break Err(e),
2366                                                         (ChannelMonitorUpdateStatus::Completed, Ok(())) => {},
2367                                                         (ChannelMonitorUpdateStatus::InProgress, Err(_)) => {
2368                                                                 // Note that MonitorUpdateInProgress here indicates (per function
2369                                                                 // docs) that we will resend the commitment update once monitor
2370                                                                 // updating completes. Therefore, we must return an error
2371                                                                 // indicating that it is unsafe to retry the payment wholesale,
2372                                                                 // which we do in the send_payment check for
2373                                                                 // MonitorUpdateInProgress, below.
2374                                                                 return Err(APIError::MonitorUpdateInProgress);
2375                                                         },
2376                                                         _ => unreachable!(),
2377                                                 }
2378
2379                                                 log_debug!(self.logger, "Sending payment along path resulted in a commitment_signed for channel {}", log_bytes!(chan_id));
2380                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2381                                                         node_id: path.first().unwrap().pubkey,
2382                                                         updates: msgs::CommitmentUpdate {
2383                                                                 update_add_htlcs: vec![update_add],
2384                                                                 update_fulfill_htlcs: Vec::new(),
2385                                                                 update_fail_htlcs: Vec::new(),
2386                                                                 update_fail_malformed_htlcs: Vec::new(),
2387                                                                 update_fee: None,
2388                                                                 commitment_signed,
2389                                                         },
2390                                                 });
2391                                         },
2392                                         None => { },
2393                                 }
2394                         } else {
2395                                 // The channel was likely removed after we fetched the id from the
2396                                 // `short_to_chan_info` map, but before we successfully locked the
2397                                 // `channel_by_id` map.
2398                                 // This can occur as no consistency guarantees exists between the two maps.
2399                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
2400                         }
2401                         return Ok(());
2402                 };
2403
2404                 match handle_error!(self, err, path.first().unwrap().pubkey) {
2405                         Ok(_) => unreachable!(),
2406                         Err(e) => {
2407                                 Err(APIError::ChannelUnavailable { err: e.err })
2408                         },
2409                 }
2410         }
2411
2412         /// Sends a payment along a given route.
2413         ///
2414         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
2415         /// fields for more info.
2416         ///
2417         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
2418         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
2419         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
2420         /// [`Event::PaymentSent`]) LDK will not stop you from sending a second payment with the same
2421         /// [`PaymentId`].
2422         ///
2423         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
2424         /// tracking of payments, including state to indicate once a payment has completed. Because you
2425         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
2426         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
2427         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
2428         ///
2429         /// May generate SendHTLCs message(s) event on success, which should be relayed (e.g. via
2430         /// [`PeerManager::process_events`]).
2431         ///
2432         /// Each path may have a different return value, and PaymentSendValue may return a Vec with
2433         /// each entry matching the corresponding-index entry in the route paths, see
2434         /// PaymentSendFailure for more info.
2435         ///
2436         /// In general, a path may raise:
2437         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
2438         ///    node public key) is specified.
2439         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available for updates
2440         ///    (including due to previous monitor update failure or new permanent monitor update
2441         ///    failure).
2442         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
2443         ///    relevant updates.
2444         ///
2445         /// Note that depending on the type of the PaymentSendFailure the HTLC may have been
2446         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
2447         /// different route unless you intend to pay twice!
2448         ///
2449         /// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
2450         /// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
2451         /// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
2452         /// must not contain multiple paths as multi-path payments require a recipient-provided
2453         /// payment_secret.
2454         ///
2455         /// If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
2456         /// bit set (either as required or as available). If multiple paths are present in the Route,
2457         /// we assume the invoice had the basic_mpp feature set.
2458         ///
2459         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2460         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
2461         pub fn send_payment(&self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
2462                 let best_block_height = self.best_block.read().unwrap().height();
2463                 self.pending_outbound_payments
2464                         .send_payment_with_route(route, payment_hash, payment_secret, payment_id, &self.entropy_source, &self.node_signer, best_block_height,
2465                                 |path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2466                                 self.send_payment_along_path(path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2467         }
2468
2469         #[cfg(test)]
2470         fn test_send_payment_internal(&self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>, keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>, onion_session_privs: Vec<[u8; 32]>) -> Result<(), PaymentSendFailure> {
2471                 let best_block_height = self.best_block.read().unwrap().height();
2472                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, payment_secret, keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer, best_block_height,
2473                         |path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2474                         self.send_payment_along_path(path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2475         }
2476
2477         #[cfg(test)]
2478         pub(crate) fn test_add_new_pending_payment(&self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId, route: &Route) -> Result<Vec<[u8; 32]>, PaymentSendFailure> {
2479                 let best_block_height = self.best_block.read().unwrap().height();
2480                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, payment_secret, payment_id, route, &self.entropy_source, best_block_height)
2481         }
2482
2483
2484         /// Retries a payment along the given [`Route`].
2485         ///
2486         /// Errors returned are a superset of those returned from [`send_payment`], so see
2487         /// [`send_payment`] documentation for more details on errors. This method will also error if the
2488         /// retry amount puts the payment more than 10% over the payment's total amount, if the payment
2489         /// for the given `payment_id` cannot be found (likely due to timeout or success), or if
2490         /// further retries have been disabled with [`abandon_payment`].
2491         ///
2492         /// [`send_payment`]: [`ChannelManager::send_payment`]
2493         /// [`abandon_payment`]: [`ChannelManager::abandon_payment`]
2494         pub fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
2495                 let best_block_height = self.best_block.read().unwrap().height();
2496                 self.pending_outbound_payments.retry_payment_with_route(route, payment_id, &self.entropy_source, &self.node_signer, best_block_height,
2497                         |path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2498                         self.send_payment_along_path(path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2499         }
2500
2501         /// Signals that no further retries for the given payment will occur.
2502         ///
2503         /// After this method returns, no future calls to [`retry_payment`] for the given `payment_id`
2504         /// are allowed. If no [`Event::PaymentFailed`] event had been generated before, one will be
2505         /// generated as soon as there are no remaining pending HTLCs for this payment.
2506         ///
2507         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
2508         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
2509         /// determine the ultimate status of a payment.
2510         ///
2511         /// If an [`Event::PaymentFailed`] event is generated and we restart without this
2512         /// [`ChannelManager`] having been persisted, the payment may still be in the pending state
2513         /// upon restart. This allows further calls to [`retry_payment`] (and requiring a second call
2514         /// to [`abandon_payment`] to mark the payment as failed again). Otherwise, future calls to
2515         /// [`retry_payment`] will fail with [`PaymentSendFailure::ParameterError`].
2516         ///
2517         /// [`abandon_payment`]: Self::abandon_payment
2518         /// [`retry_payment`]: Self::retry_payment
2519         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
2520         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2521         pub fn abandon_payment(&self, payment_id: PaymentId) {
2522                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2523                 if let Some(payment_failed_ev) = self.pending_outbound_payments.abandon_payment(payment_id) {
2524                         self.pending_events.lock().unwrap().push(payment_failed_ev);
2525                 }
2526         }
2527
2528         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
2529         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
2530         /// the preimage, it must be a cryptographically secure random value that no intermediate node
2531         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
2532         /// never reach the recipient.
2533         ///
2534         /// See [`send_payment`] documentation for more details on the return value of this function
2535         /// and idempotency guarantees provided by the [`PaymentId`] key.
2536         ///
2537         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
2538         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
2539         ///
2540         /// Note that `route` must have exactly one path.
2541         ///
2542         /// [`send_payment`]: Self::send_payment
2543         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
2544                 let best_block_height = self.best_block.read().unwrap().height();
2545                 self.pending_outbound_payments.send_spontaneous_payment(route, payment_preimage, payment_id, &self.entropy_source, &self.node_signer, best_block_height,
2546                         |path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2547                         self.send_payment_along_path(path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2548         }
2549
2550         /// Send a payment that is probing the given route for liquidity. We calculate the
2551         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
2552         /// us to easily discern them from real payments.
2553         pub fn send_probe(&self, hops: Vec<RouteHop>) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
2554                 let best_block_height = self.best_block.read().unwrap().height();
2555                 self.pending_outbound_payments.send_probe(hops, self.probing_cookie_secret, &self.entropy_source, &self.node_signer, best_block_height,
2556                         |path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2557                         self.send_payment_along_path(path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2558         }
2559
2560         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
2561         /// payment probe.
2562         #[cfg(test)]
2563         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
2564                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
2565         }
2566
2567         /// Handles the generation of a funding transaction, optionally (for tests) with a function
2568         /// which checks the correctness of the funding transaction given the associated channel.
2569         fn funding_transaction_generated_intern<FundingOutput: Fn(&Channel<<SP::Target as SignerProvider>::Signer>, &Transaction) -> Result<OutPoint, APIError>>(
2570                 &self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, funding_transaction: Transaction, find_funding_output: FundingOutput
2571         ) -> Result<(), APIError> {
2572                 let per_peer_state = self.per_peer_state.read().unwrap();
2573                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
2574                 if let None = peer_state_mutex_opt {
2575                         return Err(APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })
2576                 }
2577
2578                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
2579                 let peer_state = &mut *peer_state_lock;
2580                 let (chan, msg) = {
2581                         let (res, chan) = {
2582                                 match peer_state.channel_by_id.remove(temporary_channel_id) {
2583                                         Some(mut chan) => {
2584                                                 let funding_txo = find_funding_output(&chan, &funding_transaction)?;
2585
2586                                                 (chan.get_outbound_funding_created(funding_transaction, funding_txo, &self.logger)
2587                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
2588                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.get_user_id(), chan.force_shutdown(true), None)
2589                                                         } else { unreachable!(); })
2590                                                 , chan)
2591                                         },
2592                                         None => { return Err(APIError::ChannelUnavailable { err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(*temporary_channel_id), counterparty_node_id) }) },
2593                                 }
2594                         };
2595                         match handle_error!(self, res, chan.get_counterparty_node_id()) {
2596                                 Ok(funding_msg) => {
2597                                         (chan, funding_msg)
2598                                 },
2599                                 Err(_) => { return Err(APIError::ChannelUnavailable {
2600                                         err: "Error deriving keys or signing initial commitment transactions - either our RNG or our counterparty's RNG is broken or the Signer refused to sign".to_owned()
2601                                 }) },
2602                         }
2603                 };
2604
2605                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
2606                         node_id: chan.get_counterparty_node_id(),
2607                         msg,
2608                 });
2609                 match peer_state.channel_by_id.entry(chan.channel_id()) {
2610                         hash_map::Entry::Occupied(_) => {
2611                                 panic!("Generated duplicate funding txid?");
2612                         },
2613                         hash_map::Entry::Vacant(e) => {
2614                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
2615                                 if id_to_peer.insert(chan.channel_id(), chan.get_counterparty_node_id()).is_some() {
2616                                         panic!("id_to_peer map already contained funding txid, which shouldn't be possible");
2617                                 }
2618                                 e.insert(chan);
2619                         }
2620                 }
2621                 Ok(())
2622         }
2623
2624         #[cfg(test)]
2625         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> {
2626                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, |_, tx| {
2627                         Ok(OutPoint { txid: tx.txid(), index: output_index })
2628                 })
2629         }
2630
2631         /// Call this upon creation of a funding transaction for the given channel.
2632         ///
2633         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
2634         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
2635         ///
2636         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
2637         /// across the p2p network.
2638         ///
2639         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
2640         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
2641         ///
2642         /// May panic if the output found in the funding transaction is duplicative with some other
2643         /// channel (note that this should be trivially prevented by using unique funding transaction
2644         /// keys per-channel).
2645         ///
2646         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
2647         /// counterparty's signature the funding transaction will automatically be broadcast via the
2648         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
2649         ///
2650         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
2651         /// not currently support replacing a funding transaction on an existing channel. Instead,
2652         /// create a new channel with a conflicting funding transaction.
2653         ///
2654         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
2655         /// the wallet software generating the funding transaction to apply anti-fee sniping as
2656         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
2657         /// for more details.
2658         ///
2659         /// [`Event::FundingGenerationReady`]: crate::util::events::Event::FundingGenerationReady
2660         /// [`Event::ChannelClosed`]: crate::util::events::Event::ChannelClosed
2661         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
2662                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2663
2664                 for inp in funding_transaction.input.iter() {
2665                         if inp.witness.is_empty() {
2666                                 return Err(APIError::APIMisuseError {
2667                                         err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
2668                                 });
2669                         }
2670                 }
2671                 {
2672                         let height = self.best_block.read().unwrap().height();
2673                         // Transactions are evaluated as final by network mempools at the next block. However, the modules
2674                         // constituting our Lightning node might not have perfect sync about their blockchain views. Thus, if
2675                         // the wallet module is in advance on the LDK view, allow one more block of headroom.
2676                         if !funding_transaction.input.iter().all(|input| input.sequence == Sequence::MAX) && LockTime::from(funding_transaction.lock_time).is_block_height() && funding_transaction.lock_time.0 > height + 2 {
2677                                 return Err(APIError::APIMisuseError {
2678                                         err: "Funding transaction absolute timelock is non-final".to_owned()
2679                                 });
2680                         }
2681                 }
2682                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, |chan, tx| {
2683                         let mut output_index = None;
2684                         let expected_spk = chan.get_funding_redeemscript().to_v0_p2wsh();
2685                         for (idx, outp) in tx.output.iter().enumerate() {
2686                                 if outp.script_pubkey == expected_spk && outp.value == chan.get_value_satoshis() {
2687                                         if output_index.is_some() {
2688                                                 return Err(APIError::APIMisuseError {
2689                                                         err: "Multiple outputs matched the expected script and value".to_owned()
2690                                                 });
2691                                         }
2692                                         if idx > u16::max_value() as usize {
2693                                                 return Err(APIError::APIMisuseError {
2694                                                         err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
2695                                                 });
2696                                         }
2697                                         output_index = Some(idx as u16);
2698                                 }
2699                         }
2700                         if output_index.is_none() {
2701                                 return Err(APIError::APIMisuseError {
2702                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
2703                                 });
2704                         }
2705                         Ok(OutPoint { txid: tx.txid(), index: output_index.unwrap() })
2706                 })
2707         }
2708
2709         /// Atomically updates the [`ChannelConfig`] for the given channels.
2710         ///
2711         /// Once the updates are applied, each eligible channel (advertised with a known short channel
2712         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
2713         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
2714         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
2715         ///
2716         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
2717         /// `counterparty_node_id` is provided.
2718         ///
2719         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
2720         /// below [`MIN_CLTV_EXPIRY_DELTA`].
2721         ///
2722         /// If an error is returned, none of the updates should be considered applied.
2723         ///
2724         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
2725         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
2726         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
2727         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
2728         /// [`ChannelUpdate`]: msgs::ChannelUpdate
2729         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
2730         /// [`APIMisuseError`]: APIError::APIMisuseError
2731         pub fn update_channel_config(
2732                 &self, counterparty_node_id: &PublicKey, channel_ids: &[[u8; 32]], config: &ChannelConfig,
2733         ) -> Result<(), APIError> {
2734                 if config.cltv_expiry_delta < MIN_CLTV_EXPIRY_DELTA {
2735                         return Err(APIError::APIMisuseError {
2736                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
2737                         });
2738                 }
2739
2740                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(
2741                         &self.total_consistency_lock, &self.persistence_notifier,
2742                 );
2743                 let per_peer_state = self.per_peer_state.read().unwrap();
2744                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
2745                 if let None = peer_state_mutex_opt {
2746                         return Err(APIError::APIMisuseError{ err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) });
2747                 }
2748                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
2749                 let peer_state = &mut *peer_state_lock;
2750                 for channel_id in channel_ids {
2751                         if !peer_state.channel_by_id.contains_key(channel_id) {
2752                                 return Err(APIError::ChannelUnavailable {
2753                                         err: format!("Channel with ID {} was not found for the passed counterparty_node_id {}", log_bytes!(*channel_id), counterparty_node_id),
2754                                 });
2755                         }
2756                 }
2757                 for channel_id in channel_ids {
2758                         let channel = peer_state.channel_by_id.get_mut(channel_id).unwrap();
2759                         if !channel.update_config(config) {
2760                                 continue;
2761                         }
2762                         if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
2763                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
2764                         } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
2765                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
2766                                         node_id: channel.get_counterparty_node_id(),
2767                                         msg,
2768                                 });
2769                         }
2770                 }
2771                 Ok(())
2772         }
2773
2774         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
2775         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
2776         ///
2777         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
2778         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
2779         ///
2780         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
2781         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
2782         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
2783         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
2784         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
2785         ///
2786         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
2787         /// you from forwarding more than you received.
2788         ///
2789         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
2790         /// backwards.
2791         ///
2792         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
2793         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
2794         // TODO: when we move to deciding the best outbound channel at forward time, only take
2795         // `next_node_id` and not `next_hop_channel_id`
2796         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> {
2797                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2798
2799                 let next_hop_scid = {
2800                         let peer_state_lock = self.per_peer_state.read().unwrap();
2801                         if let Some(peer_state_mutex) = peer_state_lock.get(&next_node_id) {
2802                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2803                                 let peer_state = &mut *peer_state_lock;
2804                                 match peer_state.channel_by_id.get(next_hop_channel_id) {
2805                                         Some(chan) => {
2806                                                 if !chan.is_usable() {
2807                                                         return Err(APIError::ChannelUnavailable {
2808                                                                 err: format!("Channel with id {} not fully established", log_bytes!(*next_hop_channel_id))
2809                                                         })
2810                                                 }
2811                                                 chan.get_short_channel_id().unwrap_or(chan.outbound_scid_alias())
2812                                         },
2813                                         None => return Err(APIError::ChannelUnavailable {
2814                                                 err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(*next_hop_channel_id), next_node_id)
2815                                         })
2816                                 }
2817                         } else {
2818                                 return Err(APIError::APIMisuseError{ err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) });
2819                         }
2820                 };
2821
2822                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
2823                         .ok_or_else(|| APIError::APIMisuseError {
2824                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
2825                         })?;
2826
2827                 let routing = match payment.forward_info.routing {
2828                         PendingHTLCRouting::Forward { onion_packet, .. } => {
2829                                 PendingHTLCRouting::Forward { onion_packet, short_channel_id: next_hop_scid }
2830                         },
2831                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
2832                 };
2833                 let pending_htlc_info = PendingHTLCInfo {
2834                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
2835                 };
2836
2837                 let mut per_source_pending_forward = [(
2838                         payment.prev_short_channel_id,
2839                         payment.prev_funding_outpoint,
2840                         payment.prev_user_channel_id,
2841                         vec![(pending_htlc_info, payment.prev_htlc_id)]
2842                 )];
2843                 self.forward_htlcs(&mut per_source_pending_forward);
2844                 Ok(())
2845         }
2846
2847         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
2848         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
2849         ///
2850         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
2851         /// backwards.
2852         ///
2853         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
2854         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
2855                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2856
2857                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
2858                         .ok_or_else(|| APIError::APIMisuseError {
2859                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
2860                         })?;
2861
2862                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
2863                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
2864                                 short_channel_id: payment.prev_short_channel_id,
2865                                 outpoint: payment.prev_funding_outpoint,
2866                                 htlc_id: payment.prev_htlc_id,
2867                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
2868                                 phantom_shared_secret: None,
2869                         });
2870
2871                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
2872                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
2873                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
2874                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
2875
2876                 Ok(())
2877         }
2878
2879         /// Processes HTLCs which are pending waiting on random forward delay.
2880         ///
2881         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
2882         /// Will likely generate further events.
2883         pub fn process_pending_htlc_forwards(&self) {
2884                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2885
2886                 let mut new_events = Vec::new();
2887                 let mut failed_forwards = Vec::new();
2888                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
2889                 {
2890                         let mut forward_htlcs = HashMap::new();
2891                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
2892
2893                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
2894                                 if short_chan_id != 0 {
2895                                         macro_rules! forwarding_channel_not_found {
2896                                                 () => {
2897                                                         for forward_info in pending_forwards.drain(..) {
2898                                                                 match forward_info {
2899                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
2900                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
2901                                                                                 forward_info: PendingHTLCInfo {
2902                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
2903                                                                                         outgoing_cltv_value, incoming_amt_msat: _
2904                                                                                 }
2905                                                                         }) => {
2906                                                                                 macro_rules! failure_handler {
2907                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
2908                                                                                                 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2909
2910                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
2911                                                                                                         short_channel_id: prev_short_channel_id,
2912                                                                                                         outpoint: prev_funding_outpoint,
2913                                                                                                         htlc_id: prev_htlc_id,
2914                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
2915                                                                                                         phantom_shared_secret: $phantom_ss,
2916                                                                                                 });
2917
2918                                                                                                 let reason = if $next_hop_unknown {
2919                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
2920                                                                                                 } else {
2921                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
2922                                                                                                 };
2923
2924                                                                                                 failed_forwards.push((htlc_source, payment_hash,
2925                                                                                                         HTLCFailReason::reason($err_code, $err_data),
2926                                                                                                         reason
2927                                                                                                 ));
2928                                                                                                 continue;
2929                                                                                         }
2930                                                                                 }
2931                                                                                 macro_rules! fail_forward {
2932                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
2933                                                                                                 {
2934                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
2935                                                                                                 }
2936                                                                                         }
2937                                                                                 }
2938                                                                                 macro_rules! failed_payment {
2939                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
2940                                                                                                 {
2941                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
2942                                                                                                 }
2943                                                                                         }
2944                                                                                 }
2945                                                                                 if let PendingHTLCRouting::Forward { onion_packet, .. } = routing {
2946                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
2947                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.genesis_hash) {
2948                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
2949                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac, payment_hash) {
2950                                                                                                         Ok(res) => res,
2951                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
2952                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();
2953                                                                                                                 // In this scenario, the phantom would have sent us an
2954                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
2955                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
2956                                                                                                                 // of the onion.
2957                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
2958                                                                                                         },
2959                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
2960                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
2961                                                                                                         },
2962                                                                                                 };
2963                                                                                                 match next_hop {
2964                                                                                                         onion_utils::Hop::Receive(hop_data) => {
2965                                                                                                                 match self.construct_recv_pending_htlc_info(hop_data, incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value, Some(phantom_shared_secret)) {
2966                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
2967                                                                                                                         Err(ReceiveError { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
2968                                                                                                                 }
2969                                                                                                         },
2970                                                                                                         _ => panic!(),
2971                                                                                                 }
2972                                                                                         } else {
2973                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
2974                                                                                         }
2975                                                                                 } else {
2976                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
2977                                                                                 }
2978                                                                         },
2979                                                                         HTLCForwardInfo::FailHTLC { .. } => {
2980                                                                                 // Channel went away before we could fail it. This implies
2981                                                                                 // the channel is now on chain and our counterparty is
2982                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
2983                                                                                 // problem, not ours.
2984                                                                         }
2985                                                                 }
2986                                                         }
2987                                                 }
2988                                         }
2989                                         let (counterparty_node_id, forward_chan_id) = match self.short_to_chan_info.read().unwrap().get(&short_chan_id) {
2990                                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
2991                                                 None => {
2992                                                         forwarding_channel_not_found!();
2993                                                         continue;
2994                                                 }
2995                                         };
2996                                         let per_peer_state = self.per_peer_state.read().unwrap();
2997                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
2998                                         if let None = peer_state_mutex_opt {
2999                                                 forwarding_channel_not_found!();
3000                                                 continue;
3001                                         }
3002                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3003                                         let peer_state = &mut *peer_state_lock;
3004                                         match peer_state.channel_by_id.entry(forward_chan_id) {
3005                                                 hash_map::Entry::Vacant(_) => {
3006                                                         forwarding_channel_not_found!();
3007                                                         continue;
3008                                                 },
3009                                                 hash_map::Entry::Occupied(mut chan) => {
3010                                                         for forward_info in pending_forwards.drain(..) {
3011                                                                 match forward_info {
3012                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
3013                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id: _,
3014                                                                                 forward_info: PendingHTLCInfo {
3015                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
3016                                                                                         routing: PendingHTLCRouting::Forward { onion_packet, .. }, incoming_amt_msat: _,
3017                                                                                 },
3018                                                                         }) => {
3019                                                                                 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);
3020                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3021                                                                                         short_channel_id: prev_short_channel_id,
3022                                                                                         outpoint: prev_funding_outpoint,
3023                                                                                         htlc_id: prev_htlc_id,
3024                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
3025                                                                                         // Phantom payments are only PendingHTLCRouting::Receive.
3026                                                                                         phantom_shared_secret: None,
3027                                                                                 });
3028                                                                                 if let Err(e) = chan.get_mut().queue_add_htlc(outgoing_amt_msat,
3029                                                                                         payment_hash, outgoing_cltv_value, htlc_source.clone(),
3030                                                                                         onion_packet, &self.logger)
3031                                                                                 {
3032                                                                                         if let ChannelError::Ignore(msg) = e {
3033                                                                                                 log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
3034                                                                                         } else {
3035                                                                                                 panic!("Stated return value requirements in send_htlc() were not met");
3036                                                                                         }
3037                                                                                         let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan.get());
3038                                                                                         failed_forwards.push((htlc_source, payment_hash,
3039                                                                                                 HTLCFailReason::reason(failure_code, data),
3040                                                                                                 HTLCDestination::NextHopChannel { node_id: Some(chan.get().get_counterparty_node_id()), channel_id: forward_chan_id }
3041                                                                                         ));
3042                                                                                         continue;
3043                                                                                 }
3044                                                                         },
3045                                                                         HTLCForwardInfo::AddHTLC { .. } => {
3046                                                                                 panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
3047                                                                         },
3048                                                                         HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
3049                                                                                 log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
3050                                                                                 if let Err(e) = chan.get_mut().queue_fail_htlc(
3051                                                                                         htlc_id, err_packet, &self.logger
3052                                                                                 ) {
3053                                                                                         if let ChannelError::Ignore(msg) = e {
3054                                                                                                 log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
3055                                                                                         } else {
3056                                                                                                 panic!("Stated return value requirements in queue_fail_htlc() were not met");
3057                                                                                         }
3058                                                                                         // fail-backs are best-effort, we probably already have one
3059                                                                                         // pending, and if not that's OK, if not, the channel is on
3060                                                                                         // the chain and sending the HTLC-Timeout is their problem.
3061                                                                                         continue;
3062                                                                                 }
3063                                                                         },
3064                                                                 }
3065                                                         }
3066                                                 }
3067                                         }
3068                                 } else {
3069                                         for forward_info in pending_forwards.drain(..) {
3070                                                 match forward_info {
3071                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
3072                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
3073                                                                 forward_info: PendingHTLCInfo {
3074                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat, ..
3075                                                                 }
3076                                                         }) => {
3077                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret) = match routing {
3078                                                                         PendingHTLCRouting::Receive { payment_data, incoming_cltv_expiry, phantom_shared_secret } => {
3079                                                                                 let _legacy_hop_data = Some(payment_data.clone());
3080                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data }, Some(payment_data), phantom_shared_secret)
3081                                                                         },
3082                                                                         PendingHTLCRouting::ReceiveKeysend { payment_preimage, incoming_cltv_expiry } =>
3083                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage), None, None),
3084                                                                         _ => {
3085                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
3086                                                                         }
3087                                                                 };
3088                                                                 let claimable_htlc = ClaimableHTLC {
3089                                                                         prev_hop: HTLCPreviousHopData {
3090                                                                                 short_channel_id: prev_short_channel_id,
3091                                                                                 outpoint: prev_funding_outpoint,
3092                                                                                 htlc_id: prev_htlc_id,
3093                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
3094                                                                                 phantom_shared_secret,
3095                                                                         },
3096                                                                         value: outgoing_amt_msat,
3097                                                                         timer_ticks: 0,
3098                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
3099                                                                         cltv_expiry,
3100                                                                         onion_payload,
3101                                                                 };
3102
3103                                                                 macro_rules! fail_htlc {
3104                                                                         ($htlc: expr, $payment_hash: expr) => {
3105                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
3106                                                                                 htlc_msat_height_data.extend_from_slice(
3107                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
3108                                                                                 );
3109                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
3110                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
3111                                                                                                 outpoint: prev_funding_outpoint,
3112                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
3113                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
3114                                                                                                 phantom_shared_secret,
3115                                                                                         }), payment_hash,
3116                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
3117                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
3118                                                                                 ));
3119                                                                         }
3120                                                                 }
3121                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
3122                                                                 let mut receiver_node_id = self.our_network_pubkey;
3123                                                                 if phantom_shared_secret.is_some() {
3124                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
3125                                                                                 .expect("Failed to get node_id for phantom node recipient");
3126                                                                 }
3127
3128                                                                 macro_rules! check_total_value {
3129                                                                         ($payment_data: expr, $payment_preimage: expr) => {{
3130                                                                                 let mut payment_claimable_generated = false;
3131                                                                                 let purpose = || {
3132                                                                                         events::PaymentPurpose::InvoicePayment {
3133                                                                                                 payment_preimage: $payment_preimage,
3134                                                                                                 payment_secret: $payment_data.payment_secret,
3135                                                                                         }
3136                                                                                 };
3137                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
3138                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
3139                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3140                                                                                         continue
3141                                                                                 }
3142                                                                                 let (_, htlcs) = claimable_payments.claimable_htlcs.entry(payment_hash)
3143                                                                                         .or_insert_with(|| (purpose(), Vec::new()));
3144                                                                                 if htlcs.len() == 1 {
3145                                                                                         if let OnionPayload::Spontaneous(_) = htlcs[0].onion_payload {
3146                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as we already had an existing keysend HTLC with the same payment hash", log_bytes!(payment_hash.0));
3147                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
3148                                                                                                 continue
3149                                                                                         }
3150                                                                                 }
3151                                                                                 let mut total_value = claimable_htlc.value;
3152                                                                                 for htlc in htlcs.iter() {
3153                                                                                         total_value += htlc.value;
3154                                                                                         match &htlc.onion_payload {
3155                                                                                                 OnionPayload::Invoice { .. } => {
3156                                                                                                         if htlc.total_msat != $payment_data.total_msat {
3157                                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
3158                                                                                                                         log_bytes!(payment_hash.0), $payment_data.total_msat, htlc.total_msat);
3159                                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
3160                                                                                                         }
3161                                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
3162                                                                                                 },
3163                                                                                                 _ => unreachable!(),
3164                                                                                         }
3165                                                                                 }
3166                                                                                 if total_value >= msgs::MAX_VALUE_MSAT || total_value > $payment_data.total_msat {
3167                                                                                         log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the total value {} ran over expected value {} (or HTLCs were inconsistent)",
3168                                                                                                 log_bytes!(payment_hash.0), total_value, $payment_data.total_msat);
3169                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3170                                                                                 } else if total_value == $payment_data.total_msat {
3171                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
3172                                                                                         htlcs.push(claimable_htlc);
3173                                                                                         new_events.push(events::Event::PaymentClaimable {
3174                                                                                                 receiver_node_id: Some(receiver_node_id),
3175                                                                                                 payment_hash,
3176                                                                                                 purpose: purpose(),
3177                                                                                                 amount_msat: total_value,
3178                                                                                                 via_channel_id: Some(prev_channel_id),
3179                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
3180                                                                                         });
3181                                                                                         payment_claimable_generated = true;
3182                                                                                 } else {
3183                                                                                         // Nothing to do - we haven't reached the total
3184                                                                                         // payment value yet, wait until we receive more
3185                                                                                         // MPP parts.
3186                                                                                         htlcs.push(claimable_htlc);
3187                                                                                 }
3188                                                                                 payment_claimable_generated
3189                                                                         }}
3190                                                                 }
3191
3192                                                                 // Check that the payment hash and secret are known. Note that we
3193                                                                 // MUST take care to handle the "unknown payment hash" and
3194                                                                 // "incorrect payment secret" cases here identically or we'd expose
3195                                                                 // that we are the ultimate recipient of the given payment hash.
3196                                                                 // Further, we must not expose whether we have any other HTLCs
3197                                                                 // associated with the same payment_hash pending or not.
3198                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
3199                                                                 match payment_secrets.entry(payment_hash) {
3200                                                                         hash_map::Entry::Vacant(_) => {
3201                                                                                 match claimable_htlc.onion_payload {
3202                                                                                         OnionPayload::Invoice { .. } => {
3203                                                                                                 let payment_data = payment_data.unwrap();
3204                                                                                                 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) {
3205                                                                                                         Ok(result) => result,
3206                                                                                                         Err(()) => {
3207                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", log_bytes!(payment_hash.0));
3208                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
3209                                                                                                                 continue
3210                                                                                                         }
3211                                                                                                 };
3212                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
3213                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
3214                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
3215                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
3216                                                                                                                         log_bytes!(payment_hash.0), cltv_expiry, expected_min_expiry_height);
3217                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
3218                                                                                                                 continue;
3219                                                                                                         }
3220                                                                                                 }
3221                                                                                                 check_total_value!(payment_data, payment_preimage);
3222                                                                                         },
3223                                                                                         OnionPayload::Spontaneous(preimage) => {
3224                                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
3225                                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
3226                                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3227                                                                                                         continue
3228                                                                                                 }
3229                                                                                                 match claimable_payments.claimable_htlcs.entry(payment_hash) {
3230                                                                                                         hash_map::Entry::Vacant(e) => {
3231                                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
3232                                                                                                                 e.insert((purpose.clone(), vec![claimable_htlc]));
3233                                                                                                                 let prev_channel_id = prev_funding_outpoint.to_channel_id();
3234                                                                                                                 new_events.push(events::Event::PaymentClaimable {
3235                                                                                                                         receiver_node_id: Some(receiver_node_id),
3236                                                                                                                         payment_hash,
3237                                                                                                                         amount_msat: outgoing_amt_msat,
3238                                                                                                                         purpose,
3239                                                                                                                         via_channel_id: Some(prev_channel_id),
3240                                                                                                                         via_user_channel_id: Some(prev_user_channel_id),
3241                                                                                                                 });
3242                                                                                                         },
3243                                                                                                         hash_map::Entry::Occupied(_) => {
3244                                                                                                                 log_trace!(self.logger, "Failing new keysend HTLC with payment_hash {} for a duplicative payment hash", log_bytes!(payment_hash.0));
3245                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
3246                                                                                                         }
3247                                                                                                 }
3248                                                                                         }
3249                                                                                 }
3250                                                                         },
3251                                                                         hash_map::Entry::Occupied(inbound_payment) => {
3252                                                                                 if payment_data.is_none() {
3253                                                                                         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));
3254                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3255                                                                                         continue
3256                                                                                 };
3257                                                                                 let payment_data = payment_data.unwrap();
3258                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
3259                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", log_bytes!(payment_hash.0));
3260                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3261                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
3262                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
3263                                                                                                 log_bytes!(payment_hash.0), payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
3264                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3265                                                                                 } else {
3266                                                                                         let payment_claimable_generated = check_total_value!(payment_data, inbound_payment.get().payment_preimage);
3267                                                                                         if payment_claimable_generated {
3268                                                                                                 inbound_payment.remove_entry();
3269                                                                                         }
3270                                                                                 }
3271                                                                         },
3272                                                                 };
3273                                                         },
3274                                                         HTLCForwardInfo::FailHTLC { .. } => {
3275                                                                 panic!("Got pending fail of our own HTLC");
3276                                                         }
3277                                                 }
3278                                         }
3279                                 }
3280                         }
3281                 }
3282
3283                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
3284                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
3285                 }
3286                 self.forward_htlcs(&mut phantom_receives);
3287
3288                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
3289                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
3290                 // nice to do the work now if we can rather than while we're trying to get messages in the
3291                 // network stack.
3292                 self.check_free_holding_cells();
3293
3294                 if new_events.is_empty() { return }
3295                 let mut events = self.pending_events.lock().unwrap();
3296                 events.append(&mut new_events);
3297         }
3298
3299         /// Free the background events, generally called from timer_tick_occurred.
3300         ///
3301         /// Exposed for testing to allow us to process events quickly without generating accidental
3302         /// BroadcastChannelUpdate events in timer_tick_occurred.
3303         ///
3304         /// Expects the caller to have a total_consistency_lock read lock.
3305         fn process_background_events(&self) -> bool {
3306                 let mut background_events = Vec::new();
3307                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
3308                 if background_events.is_empty() {
3309                         return false;
3310                 }
3311
3312                 for event in background_events.drain(..) {
3313                         match event {
3314                                 BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)) => {
3315                                         // The channel has already been closed, so no use bothering to care about the
3316                                         // monitor updating completing.
3317                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
3318                                 },
3319                         }
3320                 }
3321                 true
3322         }
3323
3324         #[cfg(any(test, feature = "_test_utils"))]
3325         /// Process background events, for functional testing
3326         pub fn test_process_background_events(&self) {
3327                 self.process_background_events();
3328         }
3329
3330         fn update_channel_fee(&self, chan_id: &[u8; 32], chan: &mut Channel<<SP::Target as SignerProvider>::Signer>, new_feerate: u32) -> NotifyOption {
3331                 if !chan.is_outbound() { return NotifyOption::SkipPersist; }
3332                 // If the feerate has decreased by less than half, don't bother
3333                 if new_feerate <= chan.get_feerate() && new_feerate * 2 > chan.get_feerate() {
3334                         log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {}.",
3335                                 log_bytes!(chan_id[..]), chan.get_feerate(), new_feerate);
3336                         return NotifyOption::SkipPersist;
3337                 }
3338                 if !chan.is_live() {
3339                         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).",
3340                                 log_bytes!(chan_id[..]), chan.get_feerate(), new_feerate);
3341                         return NotifyOption::SkipPersist;
3342                 }
3343                 log_trace!(self.logger, "Channel {} qualifies for a feerate change from {} to {}.",
3344                         log_bytes!(chan_id[..]), chan.get_feerate(), new_feerate);
3345
3346                 chan.queue_update_fee(new_feerate, &self.logger);
3347                 NotifyOption::DoPersist
3348         }
3349
3350         #[cfg(fuzzing)]
3351         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
3352         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
3353         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
3354         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
3355         pub fn maybe_update_chan_fees(&self) {
3356                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
3357                         let mut should_persist = NotifyOption::SkipPersist;
3358
3359                         let new_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
3360
3361                         let per_peer_state = self.per_peer_state.read().unwrap();
3362                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
3363                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3364                                 let peer_state = &mut *peer_state_lock;
3365                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut() {
3366                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
3367                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
3368                                 }
3369                         }
3370
3371                         should_persist
3372                 });
3373         }
3374
3375         /// Performs actions which should happen on startup and roughly once per minute thereafter.
3376         ///
3377         /// This currently includes:
3378         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
3379         ///  * Broadcasting `ChannelUpdate` messages if we've been disconnected from our peer for more
3380         ///    than a minute, informing the network that they should no longer attempt to route over
3381         ///    the channel.
3382         ///  * Expiring a channel's previous `ChannelConfig` if necessary to only allow forwarding HTLCs
3383         ///    with the current `ChannelConfig`.
3384         ///
3385         /// Note that this may cause reentrancy through `chain::Watch::update_channel` calls or feerate
3386         /// estimate fetches.
3387         pub fn timer_tick_occurred(&self) {
3388                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
3389                         let mut should_persist = NotifyOption::SkipPersist;
3390                         if self.process_background_events() { should_persist = NotifyOption::DoPersist; }
3391
3392                         let new_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
3393
3394                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
3395                         let mut timed_out_mpp_htlcs = Vec::new();
3396                         {
3397                                 let per_peer_state = self.per_peer_state.read().unwrap();
3398                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
3399                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3400                                         let peer_state = &mut *peer_state_lock;
3401                                         let pending_msg_events = &mut peer_state.pending_msg_events;
3402                                         peer_state.channel_by_id.retain(|chan_id, chan| {
3403                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
3404                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
3405
3406                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
3407                                                         let (needs_close, err) = convert_chan_err!(self, e, chan, chan_id);
3408                                                         handle_errors.push((Err(err), *counterparty_node_id));
3409                                                         if needs_close { return false; }
3410                                                 }
3411
3412                                                 match chan.channel_update_status() {
3413                                                         ChannelUpdateStatus::Enabled if !chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged),
3414                                                         ChannelUpdateStatus::Disabled if chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged),
3415                                                         ChannelUpdateStatus::DisabledStaged if chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
3416                                                         ChannelUpdateStatus::EnabledStaged if !chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
3417                                                         ChannelUpdateStatus::DisabledStaged if !chan.is_live() => {
3418                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
3419                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3420                                                                                 msg: update
3421                                                                         });
3422                                                                 }
3423                                                                 should_persist = NotifyOption::DoPersist;
3424                                                                 chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
3425                                                         },
3426                                                         ChannelUpdateStatus::EnabledStaged if chan.is_live() => {
3427                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
3428                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3429                                                                                 msg: update
3430                                                                         });
3431                                                                 }
3432                                                                 should_persist = NotifyOption::DoPersist;
3433                                                                 chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
3434                                                         },
3435                                                         _ => {},
3436                                                 }
3437
3438                                                 chan.maybe_expire_prev_config();
3439
3440                                                 true
3441                                         });
3442                                 }
3443                         }
3444
3445                         self.claimable_payments.lock().unwrap().claimable_htlcs.retain(|payment_hash, (_, htlcs)| {
3446                                 if htlcs.is_empty() {
3447                                         // This should be unreachable
3448                                         debug_assert!(false);
3449                                         return false;
3450                                 }
3451                                 if let OnionPayload::Invoice { .. } = htlcs[0].onion_payload {
3452                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
3453                                         // In this case we're not going to handle any timeouts of the parts here.
3454                                         if htlcs[0].total_msat == htlcs.iter().fold(0, |total, htlc| total + htlc.value) {
3455                                                 return true;
3456                                         } else if htlcs.into_iter().any(|htlc| {
3457                                                 htlc.timer_ticks += 1;
3458                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
3459                                         }) {
3460                                                 timed_out_mpp_htlcs.extend(htlcs.drain(..).map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
3461                                                 return false;
3462                                         }
3463                                 }
3464                                 true
3465                         });
3466
3467                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
3468                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
3469                                 let reason = HTLCFailReason::from_failure_code(23);
3470                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
3471                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
3472                         }
3473
3474                         for (err, counterparty_node_id) in handle_errors.drain(..) {
3475                                 let _ = handle_error!(self, err, counterparty_node_id);
3476                         }
3477
3478                         self.pending_outbound_payments.remove_stale_resolved_payments(&self.pending_events);
3479
3480                         // Technically we don't need to do this here, but if we have holding cell entries in a
3481                         // channel that need freeing, it's better to do that here and block a background task
3482                         // than block the message queueing pipeline.
3483                         if self.check_free_holding_cells() {
3484                                 should_persist = NotifyOption::DoPersist;
3485                         }
3486
3487                         should_persist
3488                 });
3489         }
3490
3491         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
3492         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
3493         /// along the path (including in our own channel on which we received it).
3494         ///
3495         /// Note that in some cases around unclean shutdown, it is possible the payment may have
3496         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
3497         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
3498         /// may have already been failed automatically by LDK if it was nearing its expiration time.
3499         ///
3500         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
3501         /// [`ChannelManager::claim_funds`]), you should still monitor for
3502         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
3503         /// startup during which time claims that were in-progress at shutdown may be replayed.
3504         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
3505                 self.fail_htlc_backwards_with_reason(payment_hash, &FailureCode::IncorrectOrUnknownPaymentDetails);
3506         }
3507
3508         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
3509         /// reason for the failure.
3510         ///
3511         /// See [`FailureCode`] for valid failure codes.
3512         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: &FailureCode) {
3513                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3514
3515                 let removed_source = self.claimable_payments.lock().unwrap().claimable_htlcs.remove(payment_hash);
3516                 if let Some((_, mut sources)) = removed_source {
3517                         for htlc in sources.drain(..) {
3518                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
3519                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
3520                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
3521                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
3522                         }
3523                 }
3524         }
3525
3526         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
3527         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: &FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
3528                 match failure_code {
3529                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(*failure_code as u16),
3530                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(*failure_code as u16),
3531                         FailureCode::IncorrectOrUnknownPaymentDetails => {
3532                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
3533                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
3534                                 HTLCFailReason::reason(*failure_code as u16, htlc_msat_height_data)
3535                         }
3536                 }
3537         }
3538
3539         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
3540         /// that we want to return and a channel.
3541         ///
3542         /// This is for failures on the channel on which the HTLC was *received*, not failures
3543         /// forwarding
3544         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> (u16, Vec<u8>) {
3545                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
3546                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
3547                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
3548                 // an inbound SCID alias before the real SCID.
3549                 let scid_pref = if chan.should_announce() {
3550                         chan.get_short_channel_id().or(chan.latest_inbound_scid_alias())
3551                 } else {
3552                         chan.latest_inbound_scid_alias().or(chan.get_short_channel_id())
3553                 };
3554                 if let Some(scid) = scid_pref {
3555                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
3556                 } else {
3557                         (0x4000|10, Vec::new())
3558                 }
3559         }
3560
3561
3562         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
3563         /// that we want to return and a channel.
3564         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>) {
3565                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
3566                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
3567                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
3568                         if desired_err_code == 0x1000 | 20 {
3569                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
3570                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
3571                                 0u16.write(&mut enc).expect("Writes cannot fail");
3572                         }
3573                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
3574                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
3575                         upd.write(&mut enc).expect("Writes cannot fail");
3576                         (desired_err_code, enc.0)
3577                 } else {
3578                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
3579                         // which means we really shouldn't have gotten a payment to be forwarded over this
3580                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
3581                         // PERM|no_such_channel should be fine.
3582                         (0x4000|10, Vec::new())
3583                 }
3584         }
3585
3586         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
3587         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
3588         // be surfaced to the user.
3589         fn fail_holding_cell_htlcs(
3590                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: [u8; 32],
3591                 counterparty_node_id: &PublicKey
3592         ) {
3593                 let (failure_code, onion_failure_data) = {
3594                         let per_peer_state = self.per_peer_state.read().unwrap();
3595                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
3596                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3597                                 let peer_state = &mut *peer_state_lock;
3598                                 match peer_state.channel_by_id.entry(channel_id) {
3599                                         hash_map::Entry::Occupied(chan_entry) => {
3600                                                 self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan_entry.get())
3601                                         },
3602                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
3603                                 }
3604                         } else { (0x4000|10, Vec::new()) }
3605                 };
3606
3607                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
3608                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
3609                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
3610                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
3611                 }
3612         }
3613
3614         /// Fails an HTLC backwards to the sender of it to us.
3615         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
3616         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
3617                 #[cfg(any(feature = "_test_utils", test))]
3618                 {
3619                         // Ensure that no peer state channel storage lock is not held when calling this
3620                         // function.
3621                         // This ensures that future code doesn't introduce a lock_order requirement for
3622                         // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
3623                         // this function with any `per_peer_state` peer lock aquired would.
3624                         let per_peer_state = self.per_peer_state.read().unwrap();
3625                         for (_, peer) in per_peer_state.iter() {
3626                                 debug_assert!(peer.try_lock().is_ok());
3627                         }
3628                 }
3629
3630                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
3631                 //identify whether we sent it or not based on the (I presume) very different runtime
3632                 //between the branches here. We should make this async and move it into the forward HTLCs
3633                 //timer handling.
3634
3635                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3636                 // from block_connected which may run during initialization prior to the chain_monitor
3637                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
3638                 match source {
3639                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, ref payment_params, .. } => {
3640                                 self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path, session_priv, payment_id, payment_params, self.probing_cookie_secret, &self.secp_ctx, &self.pending_events, &self.logger);
3641                         },
3642                         HTLCSource::PreviousHopData(HTLCPreviousHopData { ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret, ref phantom_shared_secret, ref outpoint }) => {
3643                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with {:?}", log_bytes!(payment_hash.0), onion_error);
3644                                 let err_packet = onion_error.get_encrypted_failure_packet(incoming_packet_shared_secret, phantom_shared_secret);
3645
3646                                 let mut forward_event = None;
3647                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
3648                                 if forward_htlcs.is_empty() {
3649                                         forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
3650                                 }
3651                                 match forward_htlcs.entry(*short_channel_id) {
3652                                         hash_map::Entry::Occupied(mut entry) => {
3653                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet });
3654                                         },
3655                                         hash_map::Entry::Vacant(entry) => {
3656                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }));
3657                                         }
3658                                 }
3659                                 mem::drop(forward_htlcs);
3660                                 let mut pending_events = self.pending_events.lock().unwrap();
3661                                 if let Some(time) = forward_event {
3662                                         pending_events.push(events::Event::PendingHTLCsForwardable {
3663                                                 time_forwardable: time
3664                                         });
3665                                 }
3666                                 pending_events.push(events::Event::HTLCHandlingFailed {
3667                                         prev_channel_id: outpoint.to_channel_id(),
3668                                         failed_next_destination: destination,
3669                                 });
3670                         },
3671                 }
3672         }
3673
3674         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
3675         /// [`MessageSendEvent`]s needed to claim the payment.
3676         ///
3677         /// Note that calling this method does *not* guarantee that the payment has been claimed. You
3678         /// *must* wait for an [`Event::PaymentClaimed`] event which upon a successful claim will be
3679         /// provided to your [`EventHandler`] when [`process_pending_events`] is next called.
3680         ///
3681         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
3682         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
3683         /// event matches your expectation. If you fail to do so and call this method, you may provide
3684         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
3685         ///
3686         /// [`Event::PaymentClaimable`]: crate::util::events::Event::PaymentClaimable
3687         /// [`Event::PaymentClaimed`]: crate::util::events::Event::PaymentClaimed
3688         /// [`process_pending_events`]: EventsProvider::process_pending_events
3689         /// [`create_inbound_payment`]: Self::create_inbound_payment
3690         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
3691         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
3692                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
3693
3694                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3695
3696                 let mut sources = {
3697                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
3698                         if let Some((payment_purpose, sources)) = claimable_payments.claimable_htlcs.remove(&payment_hash) {
3699                                 let mut receiver_node_id = self.our_network_pubkey;
3700                                 for htlc in sources.iter() {
3701                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
3702                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
3703                                                         .expect("Failed to get node_id for phantom node recipient");
3704                                                 receiver_node_id = phantom_pubkey;
3705                                                 break;
3706                                         }
3707                                 }
3708
3709                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
3710                                         ClaimingPayment { amount_msat: sources.iter().map(|source| source.value).sum(),
3711                                         payment_purpose, receiver_node_id,
3712                                 });
3713                                 if dup_purpose.is_some() {
3714                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
3715                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
3716                                                 log_bytes!(payment_hash.0));
3717                                 }
3718                                 sources
3719                         } else { return; }
3720                 };
3721                 debug_assert!(!sources.is_empty());
3722
3723                 // If we are claiming an MPP payment, we check that all channels which contain a claimable
3724                 // HTLC still exist. While this isn't guaranteed to remain true if a channel closes while
3725                 // we're claiming (or even after we claim, before the commitment update dance completes),
3726                 // it should be a relatively rare race, and we'd rather not claim HTLCs that require us to
3727                 // go on-chain (and lose the on-chain fee to do so) than just reject the payment.
3728                 //
3729                 // Note that we'll still always get our funds - as long as the generated
3730                 // `ChannelMonitorUpdate` makes it out to the relevant monitor we can claim on-chain.
3731                 //
3732                 // If we find an HTLC which we would need to claim but for which we do not have a
3733                 // channel, we will fail all parts of the MPP payment. While we could wait and see if
3734                 // the sender retries the already-failed path(s), it should be a pretty rare case where
3735                 // we got all the HTLCs and then a channel closed while we were waiting for the user to
3736                 // provide the preimage, so worrying too much about the optimal handling isn't worth
3737                 // it.
3738                 let mut claimable_amt_msat = 0;
3739                 let mut expected_amt_msat = None;
3740                 let mut valid_mpp = true;
3741                 let mut errs = Vec::new();
3742                 let mut per_peer_state = Some(self.per_peer_state.read().unwrap());
3743                 for htlc in sources.iter() {
3744                         let (counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&htlc.prev_hop.short_channel_id) {
3745                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3746                                 None => {
3747                                         valid_mpp = false;
3748                                         break;
3749                                 }
3750                         };
3751
3752                         if let None = per_peer_state.as_ref().unwrap().get(&counterparty_node_id) {
3753                                 valid_mpp = false;
3754                                 break;
3755                         }
3756
3757                         let peer_state_mutex = per_peer_state.as_ref().unwrap().get(&counterparty_node_id).unwrap();
3758                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3759                         let peer_state = &mut *peer_state_lock;
3760
3761                         if let None = peer_state.channel_by_id.get(&chan_id) {
3762                                 valid_mpp = false;
3763                                 break;
3764                         }
3765
3766                         if expected_amt_msat.is_some() && expected_amt_msat != Some(htlc.total_msat) {
3767                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different total amounts - this should not be reachable!");
3768                                 debug_assert!(false);
3769                                 valid_mpp = false;
3770                                 break;
3771                         }
3772
3773                         expected_amt_msat = Some(htlc.total_msat);
3774                         if let OnionPayload::Spontaneous(_) = &htlc.onion_payload {
3775                                 // We don't currently support MPP for spontaneous payments, so just check
3776                                 // that there's one payment here and move on.
3777                                 if sources.len() != 1 {
3778                                         log_error!(self.logger, "Somehow ended up with an MPP spontaneous payment - this should not be reachable!");
3779                                         debug_assert!(false);
3780                                         valid_mpp = false;
3781                                         break;
3782                                 }
3783                         }
3784
3785                         claimable_amt_msat += htlc.value;
3786                 }
3787                 if sources.is_empty() || expected_amt_msat.is_none() {
3788                         mem::drop(per_peer_state);
3789                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
3790                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
3791                         return;
3792                 }
3793                 if claimable_amt_msat != expected_amt_msat.unwrap() {
3794                         mem::drop(per_peer_state);
3795                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
3796                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
3797                                 expected_amt_msat.unwrap(), claimable_amt_msat);
3798                         return;
3799                 }
3800                 if valid_mpp {
3801                         for htlc in sources.drain(..) {
3802                                 if per_peer_state.is_none() { per_peer_state = Some(self.per_peer_state.read().unwrap()); }
3803                                 if let Err((pk, err)) = self.claim_funds_from_hop(per_peer_state.take().unwrap(),
3804                                         htlc.prev_hop, payment_preimage,
3805                                         |_| Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash }))
3806                                 {
3807                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
3808                                                 // We got a temporary failure updating monitor, but will claim the
3809                                                 // HTLC when the monitor updating is restored (or on chain).
3810                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
3811                                         } else { errs.push((pk, err)); }
3812                                 }
3813                         }
3814                 }
3815                 mem::drop(per_peer_state);
3816                 if !valid_mpp {
3817                         for htlc in sources.drain(..) {
3818                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
3819                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
3820                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
3821                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
3822                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
3823                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
3824                         }
3825                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
3826                 }
3827
3828                 // Now we can handle any errors which were generated.
3829                 for (counterparty_node_id, err) in errs.drain(..) {
3830                         let res: Result<(), _> = Err(err);
3831                         let _ = handle_error!(self, res, counterparty_node_id);
3832                 }
3833         }
3834
3835         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>) -> Option<MonitorUpdateCompletionAction>>(&self,
3836                 per_peer_state_lock: RwLockReadGuard<HashMap<PublicKey, Mutex<PeerState<<SP::Target as SignerProvider>::Signer>>>>,
3837                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
3838         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
3839                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
3840
3841                 let chan_id = prev_hop.outpoint.to_channel_id();
3842
3843                 let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
3844                         Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
3845                         None => None
3846                 };
3847
3848                 let (found_channel, mut peer_state_opt) = if counterparty_node_id_opt.is_some() && per_peer_state_lock.get(&counterparty_node_id_opt.unwrap()).is_some() {
3849                         let peer_mutex = per_peer_state_lock.get(&counterparty_node_id_opt.unwrap()).unwrap();
3850                         let peer_state = peer_mutex.lock().unwrap();
3851                         let found_channel = peer_state.channel_by_id.contains_key(&chan_id);
3852                         (found_channel, Some(peer_state))
3853                 }  else { (false, None) };
3854
3855                 if found_channel {
3856                         let peer_state = &mut *peer_state_opt.as_mut().unwrap();
3857                         if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(chan_id) {
3858                                 let counterparty_node_id = chan.get().get_counterparty_node_id();
3859                                 match chan.get_mut().get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger) {
3860                                         Ok(msgs_monitor_option) => {
3861                                                 if let UpdateFulfillCommitFetch::NewClaim { msgs, htlc_value_msat, monitor_update } = msgs_monitor_option {
3862                                                         match self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), &monitor_update) {
3863                                                                 ChannelMonitorUpdateStatus::Completed => {},
3864                                                                 e => {
3865                                                                         log_given_level!(self.logger, if e == ChannelMonitorUpdateStatus::PermanentFailure { Level::Error } else { Level::Debug },
3866                                                                                 "Failed to update channel monitor with preimage {:?}: {:?}",
3867                                                                                 payment_preimage, e);
3868                                                                         let err = handle_monitor_update_res!(self, e, chan, RAACommitmentOrder::CommitmentFirst, false, msgs.is_some()).unwrap_err();
3869                                                                         mem::drop(peer_state_opt);
3870                                                                         mem::drop(per_peer_state_lock);
3871                                                                         self.handle_monitor_update_completion_actions(completion_action(Some(htlc_value_msat)));
3872                                                                         return Err((counterparty_node_id, err));
3873                                                                 }
3874                                                         }
3875                                                         if let Some((msg, commitment_signed)) = msgs {
3876                                                                 log_debug!(self.logger, "Claiming funds for HTLC with preimage {} resulted in a commitment_signed for channel {}",
3877                                                                         log_bytes!(payment_preimage.0), log_bytes!(chan.get().channel_id()));
3878                                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3879                                                                         node_id: counterparty_node_id,
3880                                                                         updates: msgs::CommitmentUpdate {
3881                                                                                 update_add_htlcs: Vec::new(),
3882                                                                                 update_fulfill_htlcs: vec![msg],
3883                                                                                 update_fail_htlcs: Vec::new(),
3884                                                                                 update_fail_malformed_htlcs: Vec::new(),
3885                                                                                 update_fee: None,
3886                                                                                 commitment_signed,
3887                                                                         }
3888                                                                 });
3889                                                         }
3890                                                         mem::drop(peer_state_opt);
3891                                                         mem::drop(per_peer_state_lock);
3892                                                         self.handle_monitor_update_completion_actions(completion_action(Some(htlc_value_msat)));
3893                                                         Ok(())
3894                                                 } else {
3895                                                         Ok(())
3896                                                 }
3897                                         },
3898                                         Err((e, monitor_update)) => {
3899                                                 match self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), &monitor_update) {
3900                                                         ChannelMonitorUpdateStatus::Completed => {},
3901                                                         e => {
3902                                                                 // TODO: This needs to be handled somehow - if we receive a monitor update
3903                                                                 // with a preimage we *must* somehow manage to propagate it to the upstream
3904                                                                 // channel, or we must have an ability to receive the same update and try
3905                                                                 // again on restart.
3906                                                                 log_given_level!(self.logger, if e == ChannelMonitorUpdateStatus::PermanentFailure { Level::Error } else { Level::Info },
3907                                                                         "Failed to update channel monitor with preimage {:?} immediately prior to force-close: {:?}",
3908                                                                         payment_preimage, e);
3909                                                         },
3910                                                 }
3911                                                 let (drop, res) = convert_chan_err!(self, e, chan.get_mut(), &chan_id);
3912                                                 if drop {
3913                                                         chan.remove_entry();
3914                                                 }
3915                                                 mem::drop(peer_state_opt);
3916                                                 mem::drop(per_peer_state_lock);
3917                                                 self.handle_monitor_update_completion_actions(completion_action(None));
3918                                                 Err((counterparty_node_id, res))
3919                                         },
3920                                 }
3921                         } else {
3922                                 // We've held the peer_state mutex since finding the channel and setting
3923                                 // found_channel to true, so the channel can't have been dropped.
3924                                 unreachable!()
3925                         }
3926                 } else {
3927                         let preimage_update = ChannelMonitorUpdate {
3928                                 update_id: CLOSED_CHANNEL_UPDATE_ID,
3929                                 updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
3930                                         payment_preimage,
3931                                 }],
3932                         };
3933                         // We update the ChannelMonitor on the backward link, after
3934                         // receiving an `update_fulfill_htlc` from the forward link.
3935                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
3936                         if update_res != ChannelMonitorUpdateStatus::Completed {
3937                                 // TODO: This needs to be handled somehow - if we receive a monitor update
3938                                 // with a preimage we *must* somehow manage to propagate it to the upstream
3939                                 // channel, or we must have an ability to receive the same event and try
3940                                 // again on restart.
3941                                 log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
3942                                         payment_preimage, update_res);
3943                         }
3944                         mem::drop(peer_state_opt);
3945                         mem::drop(per_peer_state_lock);
3946                         // Note that we do process the completion action here. This totally could be a
3947                         // duplicate claim, but we have no way of knowing without interrogating the
3948                         // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
3949                         // generally always allowed to be duplicative (and it's specifically noted in
3950                         // `PaymentForwarded`).
3951                         self.handle_monitor_update_completion_actions(completion_action(None));
3952                         Ok(())
3953                 }
3954         }
3955
3956         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
3957                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
3958         }
3959
3960         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage, forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, next_channel_id: [u8; 32]) {
3961                 match source {
3962                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
3963                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage, session_priv, path, from_onchain, &self.pending_events, &self.logger);
3964                         },
3965                         HTLCSource::PreviousHopData(hop_data) => {
3966                                 let prev_outpoint = hop_data.outpoint;
3967                                 let res = self.claim_funds_from_hop(self.per_peer_state.read().unwrap(), hop_data, payment_preimage,
3968                                         |htlc_claim_value_msat| {
3969                                                 if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
3970                                                         let fee_earned_msat = if let Some(claimed_htlc_value) = htlc_claim_value_msat {
3971                                                                 Some(claimed_htlc_value - forwarded_htlc_value)
3972                                                         } else { None };
3973
3974                                                         let prev_channel_id = Some(prev_outpoint.to_channel_id());
3975                                                         let next_channel_id = Some(next_channel_id);
3976
3977                                                         Some(MonitorUpdateCompletionAction::EmitEvent { event: events::Event::PaymentForwarded {
3978                                                                 fee_earned_msat,
3979                                                                 claim_from_onchain_tx: from_onchain,
3980                                                                 prev_channel_id,
3981                                                                 next_channel_id,
3982                                                         }})
3983                                                 } else { None }
3984                                         });
3985                                 if let Err((pk, err)) = res {
3986                                         let result: Result<(), _> = Err(err);
3987                                         let _ = handle_error!(self, result, pk);
3988                                 }
3989                         },
3990                 }
3991         }
3992
3993         /// Gets the node_id held by this ChannelManager
3994         pub fn get_our_node_id(&self) -> PublicKey {
3995                 self.our_network_pubkey.clone()
3996         }
3997
3998         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
3999                 for action in actions.into_iter() {
4000                         match action {
4001                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
4002                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4003                                         if let Some(ClaimingPayment { amount_msat, payment_purpose: purpose, receiver_node_id }) = payment {
4004                                                 self.pending_events.lock().unwrap().push(events::Event::PaymentClaimed {
4005                                                         payment_hash, purpose, amount_msat, receiver_node_id: Some(receiver_node_id),
4006                                                 });
4007                                         }
4008                                 },
4009                                 MonitorUpdateCompletionAction::EmitEvent { event } => {
4010                                         self.pending_events.lock().unwrap().push(event);
4011                                 },
4012                         }
4013                 }
4014         }
4015
4016         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
4017         /// update completion.
4018         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
4019                 channel: &mut Channel<<SP::Target as SignerProvider>::Signer>, raa: Option<msgs::RevokeAndACK>,
4020                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
4021                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
4022                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
4023         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
4024                 let mut htlc_forwards = None;
4025
4026                 let counterparty_node_id = channel.get_counterparty_node_id();
4027                 if !pending_forwards.is_empty() {
4028                         htlc_forwards = Some((channel.get_short_channel_id().unwrap_or(channel.outbound_scid_alias()),
4029                                 channel.get_funding_txo().unwrap(), channel.get_user_id(), pending_forwards));
4030                 }
4031
4032                 if let Some(msg) = channel_ready {
4033                         send_channel_ready!(self, pending_msg_events, channel, msg);
4034                 }
4035                 if let Some(msg) = announcement_sigs {
4036                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
4037                                 node_id: counterparty_node_id,
4038                                 msg,
4039                         });
4040                 }
4041
4042                 emit_channel_ready_event!(self, channel);
4043
4044                 macro_rules! handle_cs { () => {
4045                         if let Some(update) = commitment_update {
4046                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
4047                                         node_id: counterparty_node_id,
4048                                         updates: update,
4049                                 });
4050                         }
4051                 } }
4052                 macro_rules! handle_raa { () => {
4053                         if let Some(revoke_and_ack) = raa {
4054                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
4055                                         node_id: counterparty_node_id,
4056                                         msg: revoke_and_ack,
4057                                 });
4058                         }
4059                 } }
4060                 match order {
4061                         RAACommitmentOrder::CommitmentFirst => {
4062                                 handle_cs!();
4063                                 handle_raa!();
4064                         },
4065                         RAACommitmentOrder::RevokeAndACKFirst => {
4066                                 handle_raa!();
4067                                 handle_cs!();
4068                         },
4069                 }
4070
4071                 if let Some(tx) = funding_broadcastable {
4072                         log_info!(self.logger, "Broadcasting funding transaction with txid {}", tx.txid());
4073                         self.tx_broadcaster.broadcast_transaction(&tx);
4074                 }
4075
4076                 htlc_forwards
4077         }
4078
4079         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
4080                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4081
4082                 let htlc_forwards;
4083                 let (mut pending_failures, finalized_claims, counterparty_node_id) = {
4084                         let counterparty_node_id = match counterparty_node_id {
4085                                 Some(cp_id) => cp_id.clone(),
4086                                 None => {
4087                                         // TODO: Once we can rely on the counterparty_node_id from the
4088                                         // monitor event, this and the id_to_peer map should be removed.
4089                                         let id_to_peer = self.id_to_peer.lock().unwrap();
4090                                         match id_to_peer.get(&funding_txo.to_channel_id()) {
4091                                                 Some(cp_id) => cp_id.clone(),
4092                                                 None => return,
4093                                         }
4094                                 }
4095                         };
4096                         let per_peer_state = self.per_peer_state.read().unwrap();
4097                         let mut peer_state_lock;
4098                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
4099                         if let None = peer_state_mutex_opt { return }
4100                         peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4101                         let peer_state = &mut *peer_state_lock;
4102                         let mut channel = {
4103                                 match peer_state.channel_by_id.entry(funding_txo.to_channel_id()){
4104                                         hash_map::Entry::Occupied(chan) => chan,
4105                                         hash_map::Entry::Vacant(_) => return,
4106                                 }
4107                         };
4108                         if !channel.get().is_awaiting_monitor_update() || channel.get().get_latest_monitor_update_id() != highest_applied_update_id {
4109                                 return;
4110                         }
4111
4112                         let updates = channel.get_mut().monitor_updating_restored(&self.logger, &self.node_signer, self.genesis_hash, &self.default_configuration, self.best_block.read().unwrap().height());
4113                         let channel_update = if updates.channel_ready.is_some() && channel.get().is_usable() {
4114                                 // We only send a channel_update in the case where we are just now sending a
4115                                 // channel_ready and the channel is in a usable state. We may re-send a
4116                                 // channel_update later through the announcement_signatures process for public
4117                                 // channels, but there's no reason not to just inform our counterparty of our fees
4118                                 // now.
4119                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel.get()) {
4120                                         Some(events::MessageSendEvent::SendChannelUpdate {
4121                                                 node_id: channel.get().get_counterparty_node_id(),
4122                                                 msg,
4123                                         })
4124                                 } else { None }
4125                         } else { None };
4126                         htlc_forwards = self.handle_channel_resumption(&mut peer_state.pending_msg_events, channel.get_mut(), updates.raa, updates.commitment_update, updates.order, updates.accepted_htlcs, updates.funding_broadcastable, updates.channel_ready, updates.announcement_sigs);
4127                         if let Some(upd) = channel_update {
4128                                 peer_state.pending_msg_events.push(upd);
4129                         }
4130
4131                         (updates.failed_htlcs, updates.finalized_claimed_htlcs, counterparty_node_id)
4132                 };
4133                 if let Some(forwards) = htlc_forwards {
4134                         self.forward_htlcs(&mut [forwards][..]);
4135                 }
4136                 self.finalize_claims(finalized_claims);
4137                 for failure in pending_failures.drain(..) {
4138                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id: funding_txo.to_channel_id() };
4139                         self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
4140                 }
4141         }
4142
4143         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
4144         ///
4145         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
4146         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
4147         /// the channel.
4148         ///
4149         /// The `user_channel_id` parameter will be provided back in
4150         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
4151         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
4152         ///
4153         /// Note that this method will return an error and reject the channel, if it requires support
4154         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
4155         /// used to accept such channels.
4156         ///
4157         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
4158         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
4159         pub fn accept_inbound_channel(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
4160                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
4161         }
4162
4163         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
4164         /// it as confirmed immediately.
4165         ///
4166         /// The `user_channel_id` parameter will be provided back in
4167         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
4168         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
4169         ///
4170         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
4171         /// and (if the counterparty agrees), enables forwarding of payments immediately.
4172         ///
4173         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
4174         /// transaction and blindly assumes that it will eventually confirm.
4175         ///
4176         /// If it does not confirm before we decide to close the channel, or if the funding transaction
4177         /// does not pay to the correct script the correct amount, *you will lose funds*.
4178         ///
4179         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
4180         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
4181         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> {
4182                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
4183         }
4184
4185         fn do_accept_inbound_channel(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
4186                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4187
4188                 let per_peer_state = self.per_peer_state.read().unwrap();
4189                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4190                 if let None = peer_state_mutex_opt {
4191                         return Err(APIError::APIMisuseError { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) });
4192                 }
4193                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4194                 let peer_state = &mut *peer_state_lock;
4195                 match peer_state.channel_by_id.entry(temporary_channel_id.clone()) {
4196                         hash_map::Entry::Occupied(mut channel) => {
4197                                 if !channel.get().inbound_is_awaiting_accept() {
4198                                         return Err(APIError::APIMisuseError { err: "The channel isn't currently awaiting to be accepted.".to_owned() });
4199                                 }
4200                                 if accept_0conf {
4201                                         channel.get_mut().set_0conf();
4202                                 } else if channel.get().get_channel_type().requires_zero_conf() {
4203                                         let send_msg_err_event = events::MessageSendEvent::HandleError {
4204                                                 node_id: channel.get().get_counterparty_node_id(),
4205                                                 action: msgs::ErrorAction::SendErrorMessage{
4206                                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
4207                                                 }
4208                                         };
4209                                         peer_state.pending_msg_events.push(send_msg_err_event);
4210                                         let _ = remove_channel!(self, channel);
4211                                         return Err(APIError::APIMisuseError { err: "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned() });
4212                                 }
4213
4214                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
4215                                         node_id: channel.get().get_counterparty_node_id(),
4216                                         msg: channel.get_mut().accept_inbound_channel(user_channel_id),
4217                                 });
4218                         }
4219                         hash_map::Entry::Vacant(_) => {
4220                                 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) });
4221                         }
4222                 }
4223                 Ok(())
4224         }
4225
4226         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
4227                 if msg.chain_hash != self.genesis_hash {
4228                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
4229                 }
4230
4231                 if !self.default_configuration.accept_inbound_channels {
4232                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
4233                 }
4234
4235                 let mut random_bytes = [0u8; 16];
4236                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
4237                 let user_channel_id = u128::from_be_bytes(random_bytes);
4238
4239                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
4240                 let per_peer_state = self.per_peer_state.read().unwrap();
4241                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4242                 if let None = peer_state_mutex_opt {
4243                         return Err(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()))
4244                 }
4245                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4246                 let peer_state = &mut *peer_state_lock;
4247                 let mut channel = match Channel::new_from_req(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
4248                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id, &self.default_configuration,
4249                         self.best_block.read().unwrap().height(), &self.logger, outbound_scid_alias)
4250                 {
4251                         Err(e) => {
4252                                 self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
4253                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
4254                         },
4255                         Ok(res) => res
4256                 };
4257                 match peer_state.channel_by_id.entry(channel.channel_id()) {
4258                         hash_map::Entry::Occupied(_) => {
4259                                 self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
4260                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()))
4261                         },
4262                         hash_map::Entry::Vacant(entry) => {
4263                                 if !self.default_configuration.manually_accept_inbound_channels {
4264                                         if channel.get_channel_type().requires_zero_conf() {
4265                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
4266                                         }
4267                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
4268                                                 node_id: counterparty_node_id.clone(),
4269                                                 msg: channel.accept_inbound_channel(user_channel_id),
4270                                         });
4271                                 } else {
4272                                         let mut pending_events = self.pending_events.lock().unwrap();
4273                                         pending_events.push(
4274                                                 events::Event::OpenChannelRequest {
4275                                                         temporary_channel_id: msg.temporary_channel_id.clone(),
4276                                                         counterparty_node_id: counterparty_node_id.clone(),
4277                                                         funding_satoshis: msg.funding_satoshis,
4278                                                         push_msat: msg.push_msat,
4279                                                         channel_type: channel.get_channel_type().clone(),
4280                                                 }
4281                                         );
4282                                 }
4283
4284                                 entry.insert(channel);
4285                         }
4286                 }
4287                 Ok(())
4288         }
4289
4290         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
4291                 let (value, output_script, user_id) = {
4292                         let per_peer_state = self.per_peer_state.read().unwrap();
4293                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4294                         if let None = peer_state_mutex_opt {
4295                                 return Err(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))
4296                         }
4297                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4298                         let peer_state = &mut *peer_state_lock;
4299                         match peer_state.channel_by_id.entry(msg.temporary_channel_id) {
4300                                 hash_map::Entry::Occupied(mut chan) => {
4301                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), chan);
4302                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
4303                                 },
4304                                 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))
4305                         }
4306                 };
4307                 let mut pending_events = self.pending_events.lock().unwrap();
4308                 pending_events.push(events::Event::FundingGenerationReady {
4309                         temporary_channel_id: msg.temporary_channel_id,
4310                         counterparty_node_id: *counterparty_node_id,
4311                         channel_value_satoshis: value,
4312                         output_script,
4313                         user_channel_id: user_id,
4314                 });
4315                 Ok(())
4316         }
4317
4318         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
4319                 let per_peer_state = self.per_peer_state.read().unwrap();
4320                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4321                 if let None = peer_state_mutex_opt {
4322                         return Err(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))
4323                 }
4324                 let ((funding_msg, monitor, mut channel_ready), mut chan) = {
4325                         let best_block = *self.best_block.read().unwrap();
4326                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4327                         let peer_state = &mut *peer_state_lock;
4328                         match peer_state.channel_by_id.entry(msg.temporary_channel_id) {
4329                                 hash_map::Entry::Occupied(mut chan) => {
4330                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg, best_block, &self.signer_provider, &self.logger), chan), chan.remove())
4331                                 },
4332                                 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))
4333                         }
4334                 };
4335                 // Because we have exclusive ownership of the channel here we can release the peer_state
4336                 // lock before watch_channel
4337                 match self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor) {
4338                         ChannelMonitorUpdateStatus::Completed => {},
4339                         ChannelMonitorUpdateStatus::PermanentFailure => {
4340                                 // Note that we reply with the new channel_id in error messages if we gave up on the
4341                                 // channel, not the temporary_channel_id. This is compatible with ourselves, but the
4342                                 // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
4343                                 // any messages referencing a previously-closed channel anyway.
4344                                 // We do not propagate the monitor update to the user as it would be for a monitor
4345                                 // that we didn't manage to store (and that we don't care about - we don't respond
4346                                 // with the funding_signed so the channel can never go on chain).
4347                                 let (_monitor_update, failed_htlcs) = chan.force_shutdown(false);
4348                                 assert!(failed_htlcs.is_empty());
4349                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("ChannelMonitor storage failure".to_owned(), funding_msg.channel_id));
4350                         },
4351                         ChannelMonitorUpdateStatus::InProgress => {
4352                                 // There's no problem signing a counterparty's funding transaction if our monitor
4353                                 // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
4354                                 // accepted payment from yet. We do, however, need to wait to send our channel_ready
4355                                 // until we have persisted our monitor.
4356                                 chan.monitor_updating_paused(false, false, channel_ready.is_some(), Vec::new(), Vec::new(), Vec::new());
4357                                 channel_ready = None; // Don't send the channel_ready now
4358                         },
4359                 }
4360                 // It's safe to unwrap as we've held the `per_peer_state` read lock since checking that the
4361                 // peer exists, despite the inner PeerState potentially having no channels after removing
4362                 // the channel above.
4363                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4364                 let peer_state = &mut *peer_state_lock;
4365                 match peer_state.channel_by_id.entry(funding_msg.channel_id) {
4366                         hash_map::Entry::Occupied(_) => {
4367                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
4368                         },
4369                         hash_map::Entry::Vacant(e) => {
4370                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
4371                                 match id_to_peer.entry(chan.channel_id()) {
4372                                         hash_map::Entry::Occupied(_) => {
4373                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(
4374                                                         "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
4375                                                         funding_msg.channel_id))
4376                                         },
4377                                         hash_map::Entry::Vacant(i_e) => {
4378                                                 i_e.insert(chan.get_counterparty_node_id());
4379                                         }
4380                                 }
4381                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
4382                                         node_id: counterparty_node_id.clone(),
4383                                         msg: funding_msg,
4384                                 });
4385                                 if let Some(msg) = channel_ready {
4386                                         send_channel_ready!(self, peer_state.pending_msg_events, chan, msg);
4387                                 }
4388                                 e.insert(chan);
4389                         }
4390                 }
4391                 Ok(())
4392         }
4393
4394         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
4395                 let funding_tx = {
4396                         let best_block = *self.best_block.read().unwrap();
4397                         let per_peer_state = self.per_peer_state.read().unwrap();
4398                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4399                         if let None = peer_state_mutex_opt {
4400                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id))
4401                         }
4402
4403                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4404                         let peer_state = &mut *peer_state_lock;
4405                         match peer_state.channel_by_id.entry(msg.channel_id) {
4406                                 hash_map::Entry::Occupied(mut chan) => {
4407                                         let (monitor, funding_tx, channel_ready) = match chan.get_mut().funding_signed(&msg, best_block, &self.signer_provider, &self.logger) {
4408                                                 Ok(update) => update,
4409                                                 Err(e) => try_chan_entry!(self, Err(e), chan),
4410                                         };
4411                                         match self.chain_monitor.watch_channel(chan.get().get_funding_txo().unwrap(), monitor) {
4412                                                 ChannelMonitorUpdateStatus::Completed => {},
4413                                                 e => {
4414                                                         let mut res = handle_monitor_update_res!(self, e, chan, RAACommitmentOrder::RevokeAndACKFirst, channel_ready.is_some(), OPTIONALLY_RESEND_FUNDING_LOCKED);
4415                                                         if let Err(MsgHandleErrInternal { ref mut shutdown_finish, .. }) = res {
4416                                                                 // We weren't able to watch the channel to begin with, so no updates should be made on
4417                                                                 // it. Previously, full_stack_target found an (unreachable) panic when the
4418                                                                 // monitor update contained within `shutdown_finish` was applied.
4419                                                                 if let Some((ref mut shutdown_finish, _)) = shutdown_finish {
4420                                                                         shutdown_finish.0.take();
4421                                                                 }
4422                                                         }
4423                                                         return res
4424                                                 },
4425                                         }
4426                                         if let Some(msg) = channel_ready {
4427                                                 send_channel_ready!(self, peer_state.pending_msg_events, chan.get(), msg);
4428                                         }
4429                                         funding_tx
4430                                 },
4431                                 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))
4432                         }
4433                 };
4434                 log_info!(self.logger, "Broadcasting funding transaction with txid {}", funding_tx.txid());
4435                 self.tx_broadcaster.broadcast_transaction(&funding_tx);
4436                 Ok(())
4437         }
4438
4439         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
4440                 let per_peer_state = self.per_peer_state.read().unwrap();
4441                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4442                 if let None = peer_state_mutex_opt {
4443                         return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id));
4444                 }
4445                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4446                 let peer_state = &mut *peer_state_lock;
4447                 match peer_state.channel_by_id.entry(msg.channel_id) {
4448                         hash_map::Entry::Occupied(mut chan) => {
4449                                 let announcement_sigs_opt = try_chan_entry!(self, chan.get_mut().channel_ready(&msg, &self.node_signer,
4450                                         self.genesis_hash.clone(), &self.default_configuration, &self.best_block.read().unwrap(), &self.logger), chan);
4451                                 if let Some(announcement_sigs) = announcement_sigs_opt {
4452                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", log_bytes!(chan.get().channel_id()));
4453                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
4454                                                 node_id: counterparty_node_id.clone(),
4455                                                 msg: announcement_sigs,
4456                                         });
4457                                 } else if chan.get().is_usable() {
4458                                         // If we're sending an announcement_signatures, we'll send the (public)
4459                                         // channel_update after sending a channel_announcement when we receive our
4460                                         // counterparty's announcement_signatures. Thus, we only bother to send a
4461                                         // channel_update here if the channel is not public, i.e. we're not sending an
4462                                         // announcement_signatures.
4463                                         log_trace!(self.logger, "Sending private initial channel_update for our counterparty on channel {}", log_bytes!(chan.get().channel_id()));
4464                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan.get()) {
4465                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
4466                                                         node_id: counterparty_node_id.clone(),
4467                                                         msg,
4468                                                 });
4469                                         }
4470                                 }
4471
4472                                 emit_channel_ready_event!(self, chan.get_mut());
4473
4474                                 Ok(())
4475                         },
4476                         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))
4477                 }
4478         }
4479
4480         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
4481                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)>;
4482                 let result: Result<(), _> = loop {
4483                         let per_peer_state = self.per_peer_state.read().unwrap();
4484                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4485                         if let None = peer_state_mutex_opt {
4486                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id))
4487                         }
4488                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4489                         let peer_state = &mut *peer_state_lock;
4490                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
4491                                 hash_map::Entry::Occupied(mut chan_entry) => {
4492
4493                                         if !chan_entry.get().received_shutdown() {
4494                                                 log_info!(self.logger, "Received a shutdown message from our counterparty for channel {}{}.",
4495                                                         log_bytes!(msg.channel_id),
4496                                                         if chan_entry.get().sent_shutdown() { " after we initiated shutdown" } else { "" });
4497                                         }
4498
4499                                         let (shutdown, monitor_update, htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_entry);
4500                                         dropped_htlcs = htlcs;
4501
4502                                         // Update the monitor with the shutdown script if necessary.
4503                                         if let Some(monitor_update) = monitor_update {
4504                                                 let update_res = self.chain_monitor.update_channel(chan_entry.get().get_funding_txo().unwrap(), &monitor_update);
4505                                                 let (result, is_permanent) =
4506                                                         handle_monitor_update_res!(self, update_res, chan_entry.get_mut(), RAACommitmentOrder::CommitmentFirst, chan_entry.key(), NO_UPDATE);
4507                                                 if is_permanent {
4508                                                         remove_channel!(self, chan_entry);
4509                                                         break result;
4510                                                 }
4511                                         }
4512
4513                                         if let Some(msg) = shutdown {
4514                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
4515                                                         node_id: *counterparty_node_id,
4516                                                         msg,
4517                                                 });
4518                                         }
4519
4520                                         break Ok(());
4521                                 },
4522                                 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))
4523                         }
4524                 };
4525                 for htlc_source in dropped_htlcs.drain(..) {
4526                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
4527                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
4528                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
4529                 }
4530
4531                 let _ = handle_error!(self, result, *counterparty_node_id);
4532                 Ok(())
4533         }
4534
4535         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
4536                 let per_peer_state = self.per_peer_state.read().unwrap();
4537                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4538                 if let None = peer_state_mutex_opt {
4539                         return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id))
4540                 }
4541                 let (tx, chan_option) = {
4542                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4543                         let peer_state = &mut *peer_state_lock;
4544                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
4545                                 hash_map::Entry::Occupied(mut chan_entry) => {
4546                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&self.fee_estimator, &msg), chan_entry);
4547                                         if let Some(msg) = closing_signed {
4548                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
4549                                                         node_id: counterparty_node_id.clone(),
4550                                                         msg,
4551                                                 });
4552                                         }
4553                                         if tx.is_some() {
4554                                                 // We're done with this channel, we've got a signed closing transaction and
4555                                                 // will send the closing_signed back to the remote peer upon return. This
4556                                                 // also implies there are no pending HTLCs left on the channel, so we can
4557                                                 // fully delete it from tracking (the channel monitor is still around to
4558                                                 // watch for old state broadcasts)!
4559                                                 (tx, Some(remove_channel!(self, chan_entry)))
4560                                         } else { (tx, None) }
4561                                 },
4562                                 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))
4563                         }
4564                 };
4565                 if let Some(broadcast_tx) = tx {
4566                         log_info!(self.logger, "Broadcasting {}", log_tx!(broadcast_tx));
4567                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
4568                 }
4569                 if let Some(chan) = chan_option {
4570                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4571                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4572                                 let peer_state = &mut *peer_state_lock;
4573                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4574                                         msg: update
4575                                 });
4576                         }
4577                         self.issue_channel_close_events(&chan, ClosureReason::CooperativeClosure);
4578                 }
4579                 Ok(())
4580         }
4581
4582         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
4583                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
4584                 //determine the state of the payment based on our response/if we forward anything/the time
4585                 //we take to respond. We should take care to avoid allowing such an attack.
4586                 //
4587                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
4588                 //us repeatedly garbled in different ways, and compare our error messages, which are
4589                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
4590                 //but we should prevent it anyway.
4591
4592                 let pending_forward_info = self.decode_update_add_htlc_onion(msg);
4593                 let per_peer_state = self.per_peer_state.read().unwrap();
4594                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4595                 if let None = peer_state_mutex_opt {
4596                         return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id))
4597                 }
4598                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4599                 let peer_state = &mut *peer_state_lock;
4600                 match peer_state.channel_by_id.entry(msg.channel_id) {
4601                         hash_map::Entry::Occupied(mut chan) => {
4602
4603                                 let create_pending_htlc_status = |chan: &Channel<<SP::Target as SignerProvider>::Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
4604                                         // If the update_add is completely bogus, the call will Err and we will close,
4605                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
4606                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
4607                                         match pending_forward_info {
4608                                                 PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
4609                                                         let reason = if (error_code & 0x1000) != 0 {
4610                                                                 let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
4611                                                                 HTLCFailReason::reason(real_code, error_data)
4612                                                         } else {
4613                                                                 HTLCFailReason::from_failure_code(error_code)
4614                                                         }.get_encrypted_failure_packet(incoming_shared_secret, &None);
4615                                                         let msg = msgs::UpdateFailHTLC {
4616                                                                 channel_id: msg.channel_id,
4617                                                                 htlc_id: msg.htlc_id,
4618                                                                 reason
4619                                                         };
4620                                                         PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
4621                                                 },
4622                                                 _ => pending_forward_info
4623                                         }
4624                                 };
4625                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.logger), chan);
4626                         },
4627                         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))
4628                 }
4629                 Ok(())
4630         }
4631
4632         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
4633                 let (htlc_source, forwarded_htlc_value) = {
4634                         let per_peer_state = self.per_peer_state.read().unwrap();
4635                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4636                         if let None = peer_state_mutex_opt {
4637                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id));
4638                         }
4639                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4640                         let peer_state = &mut *peer_state_lock;
4641                         match peer_state.channel_by_id.entry(msg.channel_id) {
4642                                 hash_map::Entry::Occupied(mut chan) => {
4643                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), chan)
4644                                 },
4645                                 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))
4646                         }
4647                 };
4648                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, msg.channel_id);
4649                 Ok(())
4650         }
4651
4652         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
4653                 let per_peer_state = self.per_peer_state.read().unwrap();
4654                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4655                 if let None = peer_state_mutex_opt {
4656                         return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id));
4657                 }
4658                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4659                 let peer_state = &mut *peer_state_lock;
4660                 match peer_state.channel_by_id.entry(msg.channel_id) {
4661                         hash_map::Entry::Occupied(mut chan) => {
4662                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan);
4663                         },
4664                         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))
4665                 }
4666                 Ok(())
4667         }
4668
4669         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
4670                 let per_peer_state = self.per_peer_state.read().unwrap();
4671                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4672                 if let None = peer_state_mutex_opt {
4673                         return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id))
4674                 }
4675                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4676                 let peer_state = &mut *peer_state_lock;
4677                 match peer_state.channel_by_id.entry(msg.channel_id) {
4678                         hash_map::Entry::Occupied(mut chan) => {
4679                                 if (msg.failure_code & 0x8000) == 0 {
4680                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
4681                                         try_chan_entry!(self, Err(chan_err), chan);
4682                                 }
4683                                 try_chan_entry!(self, chan.get_mut().update_fail_malformed_htlc(&msg, HTLCFailReason::reason(msg.failure_code, msg.sha256_of_onion.to_vec())), chan);
4684                                 Ok(())
4685                         },
4686                         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))
4687                 }
4688         }
4689
4690         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
4691                 let per_peer_state = self.per_peer_state.read().unwrap();
4692                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4693                 if let None = peer_state_mutex_opt {
4694                         return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id))
4695                 }
4696                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4697                 let peer_state = &mut *peer_state_lock;
4698                 match peer_state.channel_by_id.entry(msg.channel_id) {
4699                         hash_map::Entry::Occupied(mut chan) => {
4700                                 let (revoke_and_ack, commitment_signed, monitor_update) =
4701                                         match chan.get_mut().commitment_signed(&msg, &self.logger) {
4702                                                 Err((None, e)) => try_chan_entry!(self, Err(e), chan),
4703                                                 Err((Some(update), e)) => {
4704                                                         assert!(chan.get().is_awaiting_monitor_update());
4705                                                         let _ = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), &update);
4706                                                         try_chan_entry!(self, Err(e), chan);
4707                                                         unreachable!();
4708                                                 },
4709                                                 Ok(res) => res
4710                                         };
4711                                 let update_res = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), &monitor_update);
4712                                 if let Err(e) = handle_monitor_update_res!(self, update_res, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some()) {
4713                                         return Err(e);
4714                                 }
4715
4716                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
4717                                         node_id: counterparty_node_id.clone(),
4718                                         msg: revoke_and_ack,
4719                                 });
4720                                 if let Some(msg) = commitment_signed {
4721                                         peer_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
4722                                                 node_id: counterparty_node_id.clone(),
4723                                                 updates: msgs::CommitmentUpdate {
4724                                                         update_add_htlcs: Vec::new(),
4725                                                         update_fulfill_htlcs: Vec::new(),
4726                                                         update_fail_htlcs: Vec::new(),
4727                                                         update_fail_malformed_htlcs: Vec::new(),
4728                                                         update_fee: None,
4729                                                         commitment_signed: msg,
4730                                                 },
4731                                         });
4732                                 }
4733                                 Ok(())
4734                         },
4735                         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))
4736                 }
4737         }
4738
4739         #[inline]
4740         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
4741                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
4742                         let mut forward_event = None;
4743                         let mut new_intercept_events = Vec::new();
4744                         let mut failed_intercept_forwards = Vec::new();
4745                         if !pending_forwards.is_empty() {
4746                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
4747                                         let scid = match forward_info.routing {
4748                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
4749                                                 PendingHTLCRouting::Receive { .. } => 0,
4750                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
4751                                         };
4752                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
4753                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
4754
4755                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
4756                                         let forward_htlcs_empty = forward_htlcs.is_empty();
4757                                         match forward_htlcs.entry(scid) {
4758                                                 hash_map::Entry::Occupied(mut entry) => {
4759                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4760                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
4761                                                 },
4762                                                 hash_map::Entry::Vacant(entry) => {
4763                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
4764                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.genesis_hash)
4765                                                         {
4766                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).into_inner());
4767                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
4768                                                                 match pending_intercepts.entry(intercept_id) {
4769                                                                         hash_map::Entry::Vacant(entry) => {
4770                                                                                 new_intercept_events.push(events::Event::HTLCIntercepted {
4771                                                                                         requested_next_hop_scid: scid,
4772                                                                                         payment_hash: forward_info.payment_hash,
4773                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
4774                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
4775                                                                                         intercept_id
4776                                                                                 });
4777                                                                                 entry.insert(PendingAddHTLCInfo {
4778                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
4779                                                                         },
4780                                                                         hash_map::Entry::Occupied(_) => {
4781                                                                                 log_info!(self.logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
4782                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4783                                                                                         short_channel_id: prev_short_channel_id,
4784                                                                                         outpoint: prev_funding_outpoint,
4785                                                                                         htlc_id: prev_htlc_id,
4786                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
4787                                                                                         phantom_shared_secret: None,
4788                                                                                 });
4789
4790                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
4791                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
4792                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
4793                                                                                 ));
4794                                                                         }
4795                                                                 }
4796                                                         } else {
4797                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
4798                                                                 // payments are being processed.
4799                                                                 if forward_htlcs_empty {
4800                                                                         forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
4801                                                                 }
4802                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4803                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
4804                                                         }
4805                                                 }
4806                                         }
4807                                 }
4808                         }
4809
4810                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
4811                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4812                         }
4813
4814                         if !new_intercept_events.is_empty() {
4815                                 let mut events = self.pending_events.lock().unwrap();
4816                                 events.append(&mut new_intercept_events);
4817                         }
4818
4819                         match forward_event {
4820                                 Some(time) => {
4821                                         let mut pending_events = self.pending_events.lock().unwrap();
4822                                         pending_events.push(events::Event::PendingHTLCsForwardable {
4823                                                 time_forwardable: time
4824                                         });
4825                                 }
4826                                 None => {},
4827                         }
4828                 }
4829         }
4830
4831         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
4832                 let mut htlcs_to_fail = Vec::new();
4833                 let res = loop {
4834                         let per_peer_state = self.per_peer_state.read().unwrap();
4835                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4836                         if let None = peer_state_mutex_opt {
4837                                 break Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id))
4838                         }
4839                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4840                         let peer_state = &mut *peer_state_lock;
4841                         match peer_state.channel_by_id.entry(msg.channel_id) {
4842                                 hash_map::Entry::Occupied(mut chan) => {
4843                                         let was_paused_for_mon_update = chan.get().is_awaiting_monitor_update();
4844                                         let raa_updates = break_chan_entry!(self,
4845                                                 chan.get_mut().revoke_and_ack(&msg, &self.logger), chan);
4846                                         htlcs_to_fail = raa_updates.holding_cell_failed_htlcs;
4847                                         let update_res = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), &raa_updates.monitor_update);
4848                                         if was_paused_for_mon_update {
4849                                                 assert!(update_res != ChannelMonitorUpdateStatus::Completed);
4850                                                 assert!(raa_updates.commitment_update.is_none());
4851                                                 assert!(raa_updates.accepted_htlcs.is_empty());
4852                                                 assert!(raa_updates.failed_htlcs.is_empty());
4853                                                 assert!(raa_updates.finalized_claimed_htlcs.is_empty());
4854                                                 break Err(MsgHandleErrInternal::ignore_no_close("Existing pending monitor update prevented responses to RAA".to_owned()));
4855                                         }
4856                                         if update_res != ChannelMonitorUpdateStatus::Completed {
4857                                                 if let Err(e) = handle_monitor_update_res!(self, update_res, chan,
4858                                                                 RAACommitmentOrder::CommitmentFirst, false,
4859                                                                 raa_updates.commitment_update.is_some(), false,
4860                                                                 raa_updates.accepted_htlcs, raa_updates.failed_htlcs,
4861                                                                 raa_updates.finalized_claimed_htlcs) {
4862                                                         break Err(e);
4863                                                 } else { unreachable!(); }
4864                                         }
4865                                         if let Some(updates) = raa_updates.commitment_update {
4866                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
4867                                                         node_id: counterparty_node_id.clone(),
4868                                                         updates,
4869                                                 });
4870                                         }
4871                                         break Ok((raa_updates.accepted_htlcs, raa_updates.failed_htlcs,
4872                                                         raa_updates.finalized_claimed_htlcs,
4873                                                         chan.get().get_short_channel_id()
4874                                                                 .unwrap_or(chan.get().outbound_scid_alias()),
4875                                                         chan.get().get_funding_txo().unwrap(),
4876                                                         chan.get().get_user_id()))
4877                                 },
4878                                 hash_map::Entry::Vacant(_) => break 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))
4879                         }
4880                 };
4881                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
4882                 match res {
4883                         Ok((pending_forwards, mut pending_failures, finalized_claim_htlcs,
4884                                 short_channel_id, channel_outpoint, user_channel_id)) =>
4885                         {
4886                                 for failure in pending_failures.drain(..) {
4887                                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: channel_outpoint.to_channel_id() };
4888                                         self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
4889                                 }
4890                                 self.forward_htlcs(&mut [(short_channel_id, channel_outpoint, user_channel_id, pending_forwards)]);
4891                                 self.finalize_claims(finalized_claim_htlcs);
4892                                 Ok(())
4893                         },
4894                         Err(e) => Err(e)
4895                 }
4896         }
4897
4898         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
4899                 let per_peer_state = self.per_peer_state.read().unwrap();
4900                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4901                 if let None = peer_state_mutex_opt {
4902                         return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id));
4903                 }
4904                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4905                 let peer_state = &mut *peer_state_lock;
4906                 match peer_state.channel_by_id.entry(msg.channel_id) {
4907                         hash_map::Entry::Occupied(mut chan) => {
4908                                 try_chan_entry!(self, chan.get_mut().update_fee(&self.fee_estimator, &msg, &self.logger), chan);
4909                         },
4910                         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))
4911                 }
4912                 Ok(())
4913         }
4914
4915         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
4916                 let per_peer_state = self.per_peer_state.read().unwrap();
4917                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4918                 if let None = peer_state_mutex_opt {
4919                         return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id));
4920                 }
4921                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4922                 let peer_state = &mut *peer_state_lock;
4923                 match peer_state.channel_by_id.entry(msg.channel_id) {
4924                         hash_map::Entry::Occupied(mut chan) => {
4925                                 if !chan.get().is_usable() {
4926                                         return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
4927                                 }
4928
4929                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
4930                                         msg: try_chan_entry!(self, chan.get_mut().announcement_signatures(
4931                                                 &self.node_signer, self.genesis_hash.clone(), self.best_block.read().unwrap().height(),
4932                                                 msg, &self.default_configuration
4933                                         ), chan),
4934                                         // Note that announcement_signatures fails if the channel cannot be announced,
4935                                         // so get_channel_update_for_broadcast will never fail by the time we get here.
4936                                         update_msg: self.get_channel_update_for_broadcast(chan.get()).unwrap(),
4937                                 });
4938                         },
4939                         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))
4940                 }
4941                 Ok(())
4942         }
4943
4944         /// Returns ShouldPersist if anything changed, otherwise either SkipPersist or an Err.
4945         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
4946                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
4947                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
4948                         None => {
4949                                 // It's not a local channel
4950                                 return Ok(NotifyOption::SkipPersist)
4951                         }
4952                 };
4953                 let per_peer_state = self.per_peer_state.read().unwrap();
4954                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
4955                 if let None = peer_state_mutex_opt {
4956                         return Ok(NotifyOption::SkipPersist)
4957                 }
4958                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4959                 let peer_state = &mut *peer_state_lock;
4960                 match peer_state.channel_by_id.entry(chan_id) {
4961                         hash_map::Entry::Occupied(mut chan) => {
4962                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4963                                         if chan.get().should_announce() {
4964                                                 // If the announcement is about a channel of ours which is public, some
4965                                                 // other peer may simply be forwarding all its gossip to us. Don't provide
4966                                                 // a scary-looking error message and return Ok instead.
4967                                                 return Ok(NotifyOption::SkipPersist);
4968                                         }
4969                                         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));
4970                                 }
4971                                 let were_node_one = self.get_our_node_id().serialize()[..] < chan.get().get_counterparty_node_id().serialize()[..];
4972                                 let msg_from_node_one = msg.contents.flags & 1 == 0;
4973                                 if were_node_one == msg_from_node_one {
4974                                         return Ok(NotifyOption::SkipPersist);
4975                                 } else {
4976                                         log_debug!(self.logger, "Received channel_update for channel {}.", log_bytes!(chan_id));
4977                                         try_chan_entry!(self, chan.get_mut().channel_update(&msg), chan);
4978                                 }
4979                         },
4980                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersist)
4981                 }
4982                 Ok(NotifyOption::DoPersist)
4983         }
4984
4985         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
4986                 let htlc_forwards;
4987                 let need_lnd_workaround = {
4988                         let per_peer_state = self.per_peer_state.read().unwrap();
4989
4990                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
4991                         if let None = peer_state_mutex_opt {
4992                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id));
4993                         }
4994                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4995                         let peer_state = &mut *peer_state_lock;
4996                         match peer_state.channel_by_id.entry(msg.channel_id) {
4997                                 hash_map::Entry::Occupied(mut chan) => {
4998                                         // Currently, we expect all holding cell update_adds to be dropped on peer
4999                                         // disconnect, so Channel's reestablish will never hand us any holding cell
5000                                         // freed HTLCs to fail backwards. If in the future we no longer drop pending
5001                                         // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
5002                                         let responses = try_chan_entry!(self, chan.get_mut().channel_reestablish(
5003                                                 msg, &self.logger, &self.node_signer, self.genesis_hash,
5004                                                 &self.default_configuration, &*self.best_block.read().unwrap()), chan);
5005                                         let mut channel_update = None;
5006                                         if let Some(msg) = responses.shutdown_msg {
5007                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
5008                                                         node_id: counterparty_node_id.clone(),
5009                                                         msg,
5010                                                 });
5011                                         } else if chan.get().is_usable() {
5012                                                 // If the channel is in a usable state (ie the channel is not being shut
5013                                                 // down), send a unicast channel_update to our counterparty to make sure
5014                                                 // they have the latest channel parameters.
5015                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan.get()) {
5016                                                         channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
5017                                                                 node_id: chan.get().get_counterparty_node_id(),
5018                                                                 msg,
5019                                                         });
5020                                                 }
5021                                         }
5022                                         let need_lnd_workaround = chan.get_mut().workaround_lnd_bug_4006.take();
5023                                         htlc_forwards = self.handle_channel_resumption(
5024                                                 &mut peer_state.pending_msg_events, chan.get_mut(), responses.raa, responses.commitment_update, responses.order,
5025                                                 Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
5026                                         if let Some(upd) = channel_update {
5027                                                 peer_state.pending_msg_events.push(upd);
5028                                         }
5029                                         need_lnd_workaround
5030                                 },
5031                                 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))
5032                         }
5033                 };
5034
5035                 if let Some(forwards) = htlc_forwards {
5036                         self.forward_htlcs(&mut [forwards][..]);
5037                 }
5038
5039                 if let Some(channel_ready_msg) = need_lnd_workaround {
5040                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
5041                 }
5042                 Ok(())
5043         }
5044
5045         /// Process pending events from the `chain::Watch`, returning whether any events were processed.
5046         fn process_pending_monitor_events(&self) -> bool {
5047                 let mut failed_channels = Vec::new();
5048                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
5049                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
5050                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
5051                         for monitor_event in monitor_events.drain(..) {
5052                                 match monitor_event {
5053                                         MonitorEvent::HTLCEvent(htlc_update) => {
5054                                                 if let Some(preimage) = htlc_update.payment_preimage {
5055                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
5056                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, funding_outpoint.to_channel_id());
5057                                                 } else {
5058                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
5059                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
5060                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
5061                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
5062                                                 }
5063                                         },
5064                                         MonitorEvent::CommitmentTxConfirmed(funding_outpoint) |
5065                                         MonitorEvent::UpdateFailed(funding_outpoint) => {
5066                                                 let counterparty_node_id_opt = match counterparty_node_id {
5067                                                         Some(cp_id) => Some(cp_id),
5068                                                         None => {
5069                                                                 // TODO: Once we can rely on the counterparty_node_id from the
5070                                                                 // monitor event, this and the id_to_peer map should be removed.
5071                                                                 let id_to_peer = self.id_to_peer.lock().unwrap();
5072                                                                 id_to_peer.get(&funding_outpoint.to_channel_id()).cloned()
5073                                                         }
5074                                                 };
5075                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
5076                                                         let per_peer_state = self.per_peer_state.read().unwrap();
5077                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
5078                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5079                                                                 let peer_state = &mut *peer_state_lock;
5080                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
5081                                                                 if let hash_map::Entry::Occupied(chan_entry) = peer_state.channel_by_id.entry(funding_outpoint.to_channel_id()) {
5082                                                                         let mut chan = remove_channel!(self, chan_entry);
5083                                                                         failed_channels.push(chan.force_shutdown(false));
5084                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
5085                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
5086                                                                                         msg: update
5087                                                                                 });
5088                                                                         }
5089                                                                         let reason = if let MonitorEvent::UpdateFailed(_) = monitor_event {
5090                                                                                 ClosureReason::ProcessingError { err: "Failed to persist ChannelMonitor update during chain sync".to_string() }
5091                                                                         } else {
5092                                                                                 ClosureReason::CommitmentTxConfirmed
5093                                                                         };
5094                                                                         self.issue_channel_close_events(&chan, reason);
5095                                                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
5096                                                                                 node_id: chan.get_counterparty_node_id(),
5097                                                                                 action: msgs::ErrorAction::SendErrorMessage {
5098                                                                                         msg: msgs::ErrorMessage { channel_id: chan.channel_id(), data: "Channel force-closed".to_owned() }
5099                                                                                 },
5100                                                                         });
5101                                                                 }
5102                                                         }
5103                                                 }
5104                                         },
5105                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
5106                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id, counterparty_node_id.as_ref());
5107                                         },
5108                                 }
5109                         }
5110                 }
5111
5112                 for failure in failed_channels.drain(..) {
5113                         self.finish_force_close_channel(failure);
5114                 }
5115
5116                 has_pending_monitor_events
5117         }
5118
5119         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
5120         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
5121         /// update events as a separate process method here.
5122         #[cfg(fuzzing)]
5123         pub fn process_monitor_events(&self) {
5124                 self.process_pending_monitor_events();
5125         }
5126
5127         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
5128         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
5129         /// update was applied.
5130         fn check_free_holding_cells(&self) -> bool {
5131                 let mut has_monitor_update = false;
5132                 let mut failed_htlcs = Vec::new();
5133                 let mut handle_errors = Vec::new();
5134                 {
5135                         let per_peer_state = self.per_peer_state.read().unwrap();
5136
5137                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
5138                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5139                                 let peer_state = &mut *peer_state_lock;
5140                                 let pending_msg_events = &mut peer_state.pending_msg_events;
5141                                 peer_state.channel_by_id.retain(|channel_id, chan| {
5142                                         match chan.maybe_free_holding_cell_htlcs(&self.logger) {
5143                                                 Ok((commitment_opt, holding_cell_failed_htlcs)) => {
5144                                                         if !holding_cell_failed_htlcs.is_empty() {
5145                                                                 failed_htlcs.push((
5146                                                                         holding_cell_failed_htlcs,
5147                                                                         *channel_id,
5148                                                                         chan.get_counterparty_node_id()
5149                                                                 ));
5150                                                         }
5151                                                         if let Some((commitment_update, monitor_update)) = commitment_opt {
5152                                                                 match self.chain_monitor.update_channel(chan.get_funding_txo().unwrap(), &monitor_update) {
5153                                                                         ChannelMonitorUpdateStatus::Completed => {
5154                                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
5155                                                                                         node_id: chan.get_counterparty_node_id(),
5156                                                                                         updates: commitment_update,
5157                                                                                 });
5158                                                                         },
5159                                                                         e => {
5160                                                                                 has_monitor_update = true;
5161                                                                                 let (res, close_channel) = handle_monitor_update_res!(self, e, chan, RAACommitmentOrder::CommitmentFirst, channel_id, COMMITMENT_UPDATE_ONLY);
5162                                                                                 handle_errors.push((chan.get_counterparty_node_id(), res));
5163                                                                                 if close_channel { return false; }
5164                                                                         },
5165                                                                 }
5166                                                         }
5167                                                         true
5168                                                 },
5169                                                 Err(e) => {
5170                                                         let (close_channel, res) = convert_chan_err!(self, e, chan, channel_id);
5171                                                         handle_errors.push((chan.get_counterparty_node_id(), Err(res)));
5172                                                         // ChannelClosed event is generated by handle_error for us
5173                                                         !close_channel
5174                                                 }
5175                                         }
5176                                 });
5177                         }
5178                 }
5179
5180                 let has_update = has_monitor_update || !failed_htlcs.is_empty() || !handle_errors.is_empty();
5181                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
5182                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
5183                 }
5184
5185                 for (counterparty_node_id, err) in handle_errors.drain(..) {
5186                         let _ = handle_error!(self, err, counterparty_node_id);
5187                 }
5188
5189                 has_update
5190         }
5191
5192         /// Check whether any channels have finished removing all pending updates after a shutdown
5193         /// exchange and can now send a closing_signed.
5194         /// Returns whether any closing_signed messages were generated.
5195         fn maybe_generate_initial_closing_signed(&self) -> bool {
5196                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
5197                 let mut has_update = false;
5198                 {
5199                         let per_peer_state = self.per_peer_state.read().unwrap();
5200
5201                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
5202                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5203                                 let peer_state = &mut *peer_state_lock;
5204                                 let pending_msg_events = &mut peer_state.pending_msg_events;
5205                                 peer_state.channel_by_id.retain(|channel_id, chan| {
5206                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &self.logger) {
5207                                                 Ok((msg_opt, tx_opt)) => {
5208                                                         if let Some(msg) = msg_opt {
5209                                                                 has_update = true;
5210                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
5211                                                                         node_id: chan.get_counterparty_node_id(), msg,
5212                                                                 });
5213                                                         }
5214                                                         if let Some(tx) = tx_opt {
5215                                                                 // We're done with this channel. We got a closing_signed and sent back
5216                                                                 // a closing_signed with a closing transaction to broadcast.
5217                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
5218                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
5219                                                                                 msg: update
5220                                                                         });
5221                                                                 }
5222
5223                                                                 self.issue_channel_close_events(chan, ClosureReason::CooperativeClosure);
5224
5225                                                                 log_info!(self.logger, "Broadcasting {}", log_tx!(tx));
5226                                                                 self.tx_broadcaster.broadcast_transaction(&tx);
5227                                                                 update_maps_on_chan_removal!(self, chan);
5228                                                                 false
5229                                                         } else { true }
5230                                                 },
5231                                                 Err(e) => {
5232                                                         has_update = true;
5233                                                         let (close_channel, res) = convert_chan_err!(self, e, chan, channel_id);
5234                                                         handle_errors.push((chan.get_counterparty_node_id(), Err(res)));
5235                                                         !close_channel
5236                                                 }
5237                                         }
5238                                 });
5239                         }
5240                 }
5241
5242                 for (counterparty_node_id, err) in handle_errors.drain(..) {
5243                         let _ = handle_error!(self, err, counterparty_node_id);
5244                 }
5245
5246                 has_update
5247         }
5248
5249         /// Handle a list of channel failures during a block_connected or block_disconnected call,
5250         /// pushing the channel monitor update (if any) to the background events queue and removing the
5251         /// Channel object.
5252         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
5253                 for mut failure in failed_channels.drain(..) {
5254                         // Either a commitment transactions has been confirmed on-chain or
5255                         // Channel::block_disconnected detected that the funding transaction has been
5256                         // reorganized out of the main chain.
5257                         // We cannot broadcast our latest local state via monitor update (as
5258                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
5259                         // so we track the update internally and handle it when the user next calls
5260                         // timer_tick_occurred, guaranteeing we're running normally.
5261                         if let Some((funding_txo, update)) = failure.0.take() {
5262                                 assert_eq!(update.updates.len(), 1);
5263                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
5264                                         assert!(should_broadcast);
5265                                 } else { unreachable!(); }
5266                                 self.pending_background_events.lock().unwrap().push(BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)));
5267                         }
5268                         self.finish_force_close_channel(failure);
5269                 }
5270         }
5271
5272         fn set_payment_hash_secret_map(&self, payment_hash: PaymentHash, payment_preimage: Option<PaymentPreimage>, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32) -> Result<PaymentSecret, APIError> {
5273                 assert!(invoice_expiry_delta_secs <= 60*60*24*365); // Sadly bitcoin timestamps are u32s, so panic before 2106
5274
5275                 if min_value_msat.is_some() && min_value_msat.unwrap() > MAX_VALUE_MSAT {
5276                         return Err(APIError::APIMisuseError { err: format!("min_value_msat of {} greater than total 21 million bitcoin supply", min_value_msat.unwrap()) });
5277                 }
5278
5279                 let payment_secret = PaymentSecret(self.entropy_source.get_secure_random_bytes());
5280
5281                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5282                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
5283                 match payment_secrets.entry(payment_hash) {
5284                         hash_map::Entry::Vacant(e) => {
5285                                 e.insert(PendingInboundPayment {
5286                                         payment_secret, min_value_msat, payment_preimage,
5287                                         user_payment_id: 0, // For compatibility with version 0.0.103 and earlier
5288                                         // We assume that highest_seen_timestamp is pretty close to the current time -
5289                                         // it's updated when we receive a new block with the maximum time we've seen in
5290                                         // a header. It should never be more than two hours in the future.
5291                                         // Thus, we add two hours here as a buffer to ensure we absolutely
5292                                         // never fail a payment too early.
5293                                         // Note that we assume that received blocks have reasonably up-to-date
5294                                         // timestamps.
5295                                         expiry_time: self.highest_seen_timestamp.load(Ordering::Acquire) as u64 + invoice_expiry_delta_secs as u64 + 7200,
5296                                 });
5297                         },
5298                         hash_map::Entry::Occupied(_) => return Err(APIError::APIMisuseError { err: "Duplicate payment hash".to_owned() }),
5299                 }
5300                 Ok(payment_secret)
5301         }
5302
5303         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
5304         /// to pay us.
5305         ///
5306         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
5307         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
5308         ///
5309         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
5310         /// will have the [`PaymentClaimable::payment_preimage`] field filled in. That should then be
5311         /// passed directly to [`claim_funds`].
5312         ///
5313         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
5314         ///
5315         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
5316         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
5317         ///
5318         /// # Note
5319         ///
5320         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
5321         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
5322         ///
5323         /// Errors if `min_value_msat` is greater than total bitcoin supply.
5324         ///
5325         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
5326         /// on versions of LDK prior to 0.0.114.
5327         ///
5328         /// [`claim_funds`]: Self::claim_funds
5329         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
5330         /// [`PaymentClaimable::payment_preimage`]: events::Event::PaymentClaimable::payment_preimage
5331         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5332         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
5333                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
5334                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
5335                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
5336                         min_final_cltv_expiry_delta)
5337         }
5338
5339         /// Legacy version of [`create_inbound_payment`]. Use this method if you wish to share
5340         /// serialized state with LDK node(s) running 0.0.103 and earlier.
5341         ///
5342         /// May panic if `invoice_expiry_delta_secs` is greater than one year.
5343         ///
5344         /// # Note
5345         /// This method is deprecated and will be removed soon.
5346         ///
5347         /// [`create_inbound_payment`]: Self::create_inbound_payment
5348         #[deprecated]
5349         pub fn create_inbound_payment_legacy(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32) -> Result<(PaymentHash, PaymentSecret), APIError> {
5350                 let payment_preimage = PaymentPreimage(self.entropy_source.get_secure_random_bytes());
5351                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
5352                 let payment_secret = self.set_payment_hash_secret_map(payment_hash, Some(payment_preimage), min_value_msat, invoice_expiry_delta_secs)?;
5353                 Ok((payment_hash, payment_secret))
5354         }
5355
5356         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
5357         /// stored external to LDK.
5358         ///
5359         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
5360         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
5361         /// the `min_value_msat` provided here, if one is provided.
5362         ///
5363         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
5364         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
5365         /// payments.
5366         ///
5367         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
5368         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
5369         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
5370         /// sender "proof-of-payment" unless they have paid the required amount.
5371         ///
5372         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
5373         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
5374         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
5375         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
5376         /// invoices when no timeout is set.
5377         ///
5378         /// Note that we use block header time to time-out pending inbound payments (with some margin
5379         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
5380         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
5381         /// If you need exact expiry semantics, you should enforce them upon receipt of
5382         /// [`PaymentClaimable`].
5383         ///
5384         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
5385         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
5386         ///
5387         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
5388         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
5389         ///
5390         /// # Note
5391         ///
5392         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
5393         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
5394         ///
5395         /// Errors if `min_value_msat` is greater than total bitcoin supply.
5396         ///
5397         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
5398         /// on versions of LDK prior to 0.0.114.
5399         ///
5400         /// [`create_inbound_payment`]: Self::create_inbound_payment
5401         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
5402         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
5403                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
5404                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
5405                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
5406                         min_final_cltv_expiry)
5407         }
5408
5409         /// Legacy version of [`create_inbound_payment_for_hash`]. Use this method if you wish to share
5410         /// serialized state with LDK node(s) running 0.0.103 and earlier.
5411         ///
5412         /// May panic if `invoice_expiry_delta_secs` is greater than one year.
5413         ///
5414         /// # Note
5415         /// This method is deprecated and will be removed soon.
5416         ///
5417         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5418         #[deprecated]
5419         pub fn create_inbound_payment_for_hash_legacy(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32) -> Result<PaymentSecret, APIError> {
5420                 self.set_payment_hash_secret_map(payment_hash, None, min_value_msat, invoice_expiry_delta_secs)
5421         }
5422
5423         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
5424         /// previously returned from [`create_inbound_payment`].
5425         ///
5426         /// [`create_inbound_payment`]: Self::create_inbound_payment
5427         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
5428                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
5429         }
5430
5431         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
5432         /// are used when constructing the phantom invoice's route hints.
5433         ///
5434         /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
5435         pub fn get_phantom_scid(&self) -> u64 {
5436                 let best_block_height = self.best_block.read().unwrap().height();
5437                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
5438                 loop {
5439                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
5440                         // Ensure the generated scid doesn't conflict with a real channel.
5441                         match short_to_chan_info.get(&scid_candidate) {
5442                                 Some(_) => continue,
5443                                 None => return scid_candidate
5444                         }
5445                 }
5446         }
5447
5448         /// Gets route hints for use in receiving [phantom node payments].
5449         ///
5450         /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
5451         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
5452                 PhantomRouteHints {
5453                         channels: self.list_usable_channels(),
5454                         phantom_scid: self.get_phantom_scid(),
5455                         real_node_pubkey: self.get_our_node_id(),
5456                 }
5457         }
5458
5459         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
5460         /// used when constructing the route hints for HTLCs intended to be intercepted. See
5461         /// [`ChannelManager::forward_intercepted_htlc`].
5462         ///
5463         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
5464         /// times to get a unique scid.
5465         pub fn get_intercept_scid(&self) -> u64 {
5466                 let best_block_height = self.best_block.read().unwrap().height();
5467                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
5468                 loop {
5469                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
5470                         // Ensure the generated scid doesn't conflict with a real channel.
5471                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
5472                         return scid_candidate
5473                 }
5474         }
5475
5476         /// Gets inflight HTLC information by processing pending outbound payments that are in
5477         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
5478         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
5479                 let mut inflight_htlcs = InFlightHtlcs::new();
5480
5481                 let per_peer_state = self.per_peer_state.read().unwrap();
5482                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
5483                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5484                         let peer_state = &mut *peer_state_lock;
5485                         for chan in peer_state.channel_by_id.values() {
5486                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
5487                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
5488                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
5489                                         }
5490                                 }
5491                         }
5492                 }
5493
5494                 inflight_htlcs
5495         }
5496
5497         #[cfg(any(test, fuzzing, feature = "_test_utils"))]
5498         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
5499                 let events = core::cell::RefCell::new(Vec::new());
5500                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
5501                 self.process_pending_events(&event_handler);
5502                 events.into_inner()
5503         }
5504
5505         #[cfg(test)]
5506         pub fn pop_pending_event(&self) -> Option<events::Event> {
5507                 let mut events = self.pending_events.lock().unwrap();
5508                 if events.is_empty() { None } else { Some(events.remove(0)) }
5509         }
5510
5511         #[cfg(test)]
5512         pub fn has_pending_payments(&self) -> bool {
5513                 self.pending_outbound_payments.has_pending_payments()
5514         }
5515
5516         #[cfg(test)]
5517         pub fn clear_pending_payments(&self) {
5518                 self.pending_outbound_payments.clear_pending_payments()
5519         }
5520
5521         /// Processes any events asynchronously in the order they were generated since the last call
5522         /// using the given event handler.
5523         ///
5524         /// See the trait-level documentation of [`EventsProvider`] for requirements.
5525         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
5526                 &self, handler: H
5527         ) {
5528                 // We'll acquire our total consistency lock until the returned future completes so that
5529                 // we can be sure no other persists happen while processing events.
5530                 let _read_guard = self.total_consistency_lock.read().unwrap();
5531
5532                 let mut result = NotifyOption::SkipPersist;
5533
5534                 // TODO: This behavior should be documented. It's unintuitive that we query
5535                 // ChannelMonitors when clearing other events.
5536                 if self.process_pending_monitor_events() {
5537                         result = NotifyOption::DoPersist;
5538                 }
5539
5540                 let pending_events = mem::replace(&mut *self.pending_events.lock().unwrap(), vec![]);
5541                 if !pending_events.is_empty() {
5542                         result = NotifyOption::DoPersist;
5543                 }
5544
5545                 for event in pending_events {
5546                         handler(event).await;
5547                 }
5548
5549                 if result == NotifyOption::DoPersist {
5550                         self.persistence_notifier.notify();
5551                 }
5552         }
5553 }
5554
5555 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>
5556 where
5557         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
5558         T::Target: BroadcasterInterface,
5559         ES::Target: EntropySource,
5560         NS::Target: NodeSigner,
5561         SP::Target: SignerProvider,
5562         F::Target: FeeEstimator,
5563         R::Target: Router,
5564         L::Target: Logger,
5565 {
5566         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
5567         /// The returned array will contain `MessageSendEvent`s for different peers if
5568         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
5569         /// is always placed next to each other.
5570         ///
5571         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
5572         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
5573         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
5574         /// will randomly be placed first or last in the returned array.
5575         ///
5576         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
5577         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
5578         /// the `MessageSendEvent`s to the specific peer they were generated under.
5579         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
5580                 let events = RefCell::new(Vec::new());
5581                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
5582                         let mut result = NotifyOption::SkipPersist;
5583
5584                         // TODO: This behavior should be documented. It's unintuitive that we query
5585                         // ChannelMonitors when clearing other events.
5586                         if self.process_pending_monitor_events() {
5587                                 result = NotifyOption::DoPersist;
5588                         }
5589
5590                         if self.check_free_holding_cells() {
5591                                 result = NotifyOption::DoPersist;
5592                         }
5593                         if self.maybe_generate_initial_closing_signed() {
5594                                 result = NotifyOption::DoPersist;
5595                         }
5596
5597                         let mut pending_events = Vec::new();
5598                         let per_peer_state = self.per_peer_state.read().unwrap();
5599                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
5600                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5601                                 let peer_state = &mut *peer_state_lock;
5602                                 if peer_state.pending_msg_events.len() > 0 {
5603                                         let mut peer_pending_events = Vec::new();
5604                                         mem::swap(&mut peer_pending_events, &mut peer_state.pending_msg_events);
5605                                         pending_events.append(&mut peer_pending_events);
5606                                 }
5607                         }
5608
5609                         if !pending_events.is_empty() {
5610                                 events.replace(pending_events);
5611                         }
5612
5613                         result
5614                 });
5615                 events.into_inner()
5616         }
5617 }
5618
5619 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>
5620 where
5621         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
5622         T::Target: BroadcasterInterface,
5623         ES::Target: EntropySource,
5624         NS::Target: NodeSigner,
5625         SP::Target: SignerProvider,
5626         F::Target: FeeEstimator,
5627         R::Target: Router,
5628         L::Target: Logger,
5629 {
5630         /// Processes events that must be periodically handled.
5631         ///
5632         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
5633         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
5634         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
5635                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
5636                         let mut result = NotifyOption::SkipPersist;
5637
5638                         // TODO: This behavior should be documented. It's unintuitive that we query
5639                         // ChannelMonitors when clearing other events.
5640                         if self.process_pending_monitor_events() {
5641                                 result = NotifyOption::DoPersist;
5642                         }
5643
5644                         let pending_events = mem::replace(&mut *self.pending_events.lock().unwrap(), vec![]);
5645                         if !pending_events.is_empty() {
5646                                 result = NotifyOption::DoPersist;
5647                         }
5648
5649                         for event in pending_events {
5650                                 handler.handle_event(event);
5651                         }
5652
5653                         result
5654                 });
5655         }
5656 }
5657
5658 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>
5659 where
5660         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
5661         T::Target: BroadcasterInterface,
5662         ES::Target: EntropySource,
5663         NS::Target: NodeSigner,
5664         SP::Target: SignerProvider,
5665         F::Target: FeeEstimator,
5666         R::Target: Router,
5667         L::Target: Logger,
5668 {
5669         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
5670                 {
5671                         let best_block = self.best_block.read().unwrap();
5672                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
5673                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
5674                         assert_eq!(best_block.height(), height - 1,
5675                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
5676                 }
5677
5678                 self.transactions_confirmed(header, txdata, height);
5679                 self.best_block_updated(header, height);
5680         }
5681
5682         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
5683                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5684                 let new_height = height - 1;
5685                 {
5686                         let mut best_block = self.best_block.write().unwrap();
5687                         assert_eq!(best_block.block_hash(), header.block_hash(),
5688                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
5689                         assert_eq!(best_block.height(), height,
5690                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
5691                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
5692                 }
5693
5694                 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));
5695         }
5696 }
5697
5698 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>
5699 where
5700         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
5701         T::Target: BroadcasterInterface,
5702         ES::Target: EntropySource,
5703         NS::Target: NodeSigner,
5704         SP::Target: SignerProvider,
5705         F::Target: FeeEstimator,
5706         R::Target: Router,
5707         L::Target: Logger,
5708 {
5709         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
5710                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5711                 // during initialization prior to the chain_monitor being fully configured in some cases.
5712                 // See the docs for `ChannelManagerReadArgs` for more.
5713
5714                 let block_hash = header.block_hash();
5715                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
5716
5717                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5718                 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)
5719                         .map(|(a, b)| (a, Vec::new(), b)));
5720
5721                 let last_best_block_height = self.best_block.read().unwrap().height();
5722                 if height < last_best_block_height {
5723                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
5724                         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));
5725                 }
5726         }
5727
5728         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
5729                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5730                 // during initialization prior to the chain_monitor being fully configured in some cases.
5731                 // See the docs for `ChannelManagerReadArgs` for more.
5732
5733                 let block_hash = header.block_hash();
5734                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
5735
5736                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5737
5738                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
5739
5740                 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));
5741
5742                 macro_rules! max_time {
5743                         ($timestamp: expr) => {
5744                                 loop {
5745                                         // Update $timestamp to be the max of its current value and the block
5746                                         // timestamp. This should keep us close to the current time without relying on
5747                                         // having an explicit local time source.
5748                                         // Just in case we end up in a race, we loop until we either successfully
5749                                         // update $timestamp or decide we don't need to.
5750                                         let old_serial = $timestamp.load(Ordering::Acquire);
5751                                         if old_serial >= header.time as usize { break; }
5752                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
5753                                                 break;
5754                                         }
5755                                 }
5756                         }
5757                 }
5758                 max_time!(self.highest_seen_timestamp);
5759                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
5760                 payment_secrets.retain(|_, inbound_payment| {
5761                         inbound_payment.expiry_time > header.time as u64
5762                 });
5763         }
5764
5765         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
5766                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
5767                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
5768                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5769                         let peer_state = &mut *peer_state_lock;
5770                         for chan in peer_state.channel_by_id.values() {
5771                                 if let (Some(funding_txo), block_hash) = (chan.get_funding_txo(), chan.get_funding_tx_confirmed_in()) {
5772                                         res.push((funding_txo.txid, block_hash));
5773                                 }
5774                         }
5775                 }
5776                 res
5777         }
5778
5779         fn transaction_unconfirmed(&self, txid: &Txid) {
5780                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5781                 self.do_chain_event(None, |channel| {
5782                         if let Some(funding_txo) = channel.get_funding_txo() {
5783                                 if funding_txo.txid == *txid {
5784                                         channel.funding_transaction_unconfirmed(&self.logger).map(|()| (None, Vec::new(), None))
5785                                 } else { Ok((None, Vec::new(), None)) }
5786                         } else { Ok((None, Vec::new(), None)) }
5787                 });
5788         }
5789 }
5790
5791 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>
5792 where
5793         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
5794         T::Target: BroadcasterInterface,
5795         ES::Target: EntropySource,
5796         NS::Target: NodeSigner,
5797         SP::Target: SignerProvider,
5798         F::Target: FeeEstimator,
5799         R::Target: Router,
5800         L::Target: Logger,
5801 {
5802         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
5803         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
5804         /// the function.
5805         fn do_chain_event<FN: Fn(&mut Channel<<SP::Target as SignerProvider>::Signer>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
5806                         (&self, height_opt: Option<u32>, f: FN) {
5807                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5808                 // during initialization prior to the chain_monitor being fully configured in some cases.
5809                 // See the docs for `ChannelManagerReadArgs` for more.
5810
5811                 let mut failed_channels = Vec::new();
5812                 let mut timed_out_htlcs = Vec::new();
5813                 {
5814                         let per_peer_state = self.per_peer_state.read().unwrap();
5815                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
5816                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5817                                 let peer_state = &mut *peer_state_lock;
5818                                 let pending_msg_events = &mut peer_state.pending_msg_events;
5819                                 peer_state.channel_by_id.retain(|_, channel| {
5820                                         let res = f(channel);
5821                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
5822                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
5823                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
5824                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
5825                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.get_counterparty_node_id()), channel_id: channel.channel_id() }));
5826                                                 }
5827                                                 if let Some(channel_ready) = channel_ready_opt {
5828                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
5829                                                         if channel.is_usable() {
5830                                                                 log_trace!(self.logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", log_bytes!(channel.channel_id()));
5831                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
5832                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
5833                                                                                 node_id: channel.get_counterparty_node_id(),
5834                                                                                 msg,
5835                                                                         });
5836                                                                 }
5837                                                         } else {
5838                                                                 log_trace!(self.logger, "Sending channel_ready WITHOUT channel_update for {}", log_bytes!(channel.channel_id()));
5839                                                         }
5840                                                 }
5841
5842                                                 emit_channel_ready_event!(self, channel);
5843
5844                                                 if let Some(announcement_sigs) = announcement_sigs {
5845                                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", log_bytes!(channel.channel_id()));
5846                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5847                                                                 node_id: channel.get_counterparty_node_id(),
5848                                                                 msg: announcement_sigs,
5849                                                         });
5850                                                         if let Some(height) = height_opt {
5851                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.genesis_hash, height, &self.default_configuration) {
5852                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
5853                                                                                 msg: announcement,
5854                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
5855                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
5856                                                                                 update_msg: self.get_channel_update_for_broadcast(channel).unwrap(),
5857                                                                         });
5858                                                                 }
5859                                                         }
5860                                                 }
5861                                                 if channel.is_our_channel_ready() {
5862                                                         if let Some(real_scid) = channel.get_short_channel_id() {
5863                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
5864                                                                 // to the short_to_chan_info map here. Note that we check whether we
5865                                                                 // can relay using the real SCID at relay-time (i.e.
5866                                                                 // enforce option_scid_alias then), and if the funding tx is ever
5867                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
5868                                                                 // is always consistent.
5869                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
5870                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.get_counterparty_node_id(), channel.channel_id()));
5871                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.get_counterparty_node_id(), channel.channel_id()),
5872                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
5873                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
5874                                                         }
5875                                                 }
5876                                         } else if let Err(reason) = res {
5877                                                 update_maps_on_chan_removal!(self, channel);
5878                                                 // It looks like our counterparty went on-chain or funding transaction was
5879                                                 // reorged out of the main chain. Close the channel.
5880                                                 failed_channels.push(channel.force_shutdown(true));
5881                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
5882                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
5883                                                                 msg: update
5884                                                         });
5885                                                 }
5886                                                 let reason_message = format!("{}", reason);
5887                                                 self.issue_channel_close_events(channel, reason);
5888                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
5889                                                         node_id: channel.get_counterparty_node_id(),
5890                                                         action: msgs::ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage {
5891                                                                 channel_id: channel.channel_id(),
5892                                                                 data: reason_message,
5893                                                         } },
5894                                                 });
5895                                                 return false;
5896                                         }
5897                                         true
5898                                 });
5899                         }
5900                 }
5901
5902                 if let Some(height) = height_opt {
5903                         self.claimable_payments.lock().unwrap().claimable_htlcs.retain(|payment_hash, (_, htlcs)| {
5904                                 htlcs.retain(|htlc| {
5905                                         // If height is approaching the number of blocks we think it takes us to get
5906                                         // our commitment transaction confirmed before the HTLC expires, plus the
5907                                         // number of blocks we generally consider it to take to do a commitment update,
5908                                         // just give up on it and fail the HTLC.
5909                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
5910                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5911                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
5912
5913                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
5914                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
5915                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
5916                                                 false
5917                                         } else { true }
5918                                 });
5919                                 !htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
5920                         });
5921
5922                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
5923                         intercepted_htlcs.retain(|_, htlc| {
5924                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
5925                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
5926                                                 short_channel_id: htlc.prev_short_channel_id,
5927                                                 htlc_id: htlc.prev_htlc_id,
5928                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
5929                                                 phantom_shared_secret: None,
5930                                                 outpoint: htlc.prev_funding_outpoint,
5931                                         });
5932
5933                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
5934                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
5935                                                 _ => unreachable!(),
5936                                         };
5937                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
5938                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
5939                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
5940                                         log_trace!(self.logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
5941                                         false
5942                                 } else { true }
5943                         });
5944                 }
5945
5946                 self.handle_init_event_channel_failures(failed_channels);
5947
5948                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
5949                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
5950                 }
5951         }
5952
5953         /// Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool
5954         /// indicating whether persistence is necessary. Only one listener on
5955         /// [`await_persistable_update`], [`await_persistable_update_timeout`], or a future returned by
5956         /// [`get_persistable_update_future`] is guaranteed to be woken up.
5957         ///
5958         /// Note that this method is not available with the `no-std` feature.
5959         ///
5960         /// [`await_persistable_update`]: Self::await_persistable_update
5961         /// [`await_persistable_update_timeout`]: Self::await_persistable_update_timeout
5962         /// [`get_persistable_update_future`]: Self::get_persistable_update_future
5963         #[cfg(any(test, feature = "std"))]
5964         pub fn await_persistable_update_timeout(&self, max_wait: Duration) -> bool {
5965                 self.persistence_notifier.wait_timeout(max_wait)
5966         }
5967
5968         /// Blocks until ChannelManager needs to be persisted. Only one listener on
5969         /// [`await_persistable_update`], `await_persistable_update_timeout`, or a future returned by
5970         /// [`get_persistable_update_future`] is guaranteed to be woken up.
5971         ///
5972         /// [`await_persistable_update`]: Self::await_persistable_update
5973         /// [`get_persistable_update_future`]: Self::get_persistable_update_future
5974         pub fn await_persistable_update(&self) {
5975                 self.persistence_notifier.wait()
5976         }
5977
5978         /// Gets a [`Future`] that completes when a persistable update is available. Note that
5979         /// callbacks registered on the [`Future`] MUST NOT call back into this [`ChannelManager`] and
5980         /// should instead register actions to be taken later.
5981         pub fn get_persistable_update_future(&self) -> Future {
5982                 self.persistence_notifier.get_future()
5983         }
5984
5985         #[cfg(any(test, feature = "_test_utils"))]
5986         pub fn get_persistence_condvar_value(&self) -> bool {
5987                 self.persistence_notifier.notify_pending()
5988         }
5989
5990         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
5991         /// [`chain::Confirm`] interfaces.
5992         pub fn current_best_block(&self) -> BestBlock {
5993                 self.best_block.read().unwrap().clone()
5994         }
5995
5996         /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
5997         /// [`ChannelManager`].
5998         pub fn node_features(&self) -> NodeFeatures {
5999                 provided_node_features(&self.default_configuration)
6000         }
6001
6002         /// Fetches the set of [`InvoiceFeatures`] flags which are provided by or required by
6003         /// [`ChannelManager`].
6004         ///
6005         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
6006         /// or not. Thus, this method is not public.
6007         #[cfg(any(feature = "_test_utils", test))]
6008         pub fn invoice_features(&self) -> InvoiceFeatures {
6009                 provided_invoice_features(&self.default_configuration)
6010         }
6011
6012         /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
6013         /// [`ChannelManager`].
6014         pub fn channel_features(&self) -> ChannelFeatures {
6015                 provided_channel_features(&self.default_configuration)
6016         }
6017
6018         /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
6019         /// [`ChannelManager`].
6020         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
6021                 provided_channel_type_features(&self.default_configuration)
6022         }
6023
6024         /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
6025         /// [`ChannelManager`].
6026         pub fn init_features(&self) -> InitFeatures {
6027                 provided_init_features(&self.default_configuration)
6028         }
6029 }
6030
6031 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
6032         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
6033 where
6034         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6035         T::Target: BroadcasterInterface,
6036         ES::Target: EntropySource,
6037         NS::Target: NodeSigner,
6038         SP::Target: SignerProvider,
6039         F::Target: FeeEstimator,
6040         R::Target: Router,
6041         L::Target: Logger,
6042 {
6043         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
6044                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6045                 let _ = handle_error!(self, self.internal_open_channel(counterparty_node_id, msg), *counterparty_node_id);
6046         }
6047
6048         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
6049                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6050                 let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
6051         }
6052
6053         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
6054                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6055                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
6056         }
6057
6058         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
6059                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6060                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
6061         }
6062
6063         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
6064                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6065                 let _ = handle_error!(self, self.internal_channel_ready(counterparty_node_id, msg), *counterparty_node_id);
6066         }
6067
6068         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
6069                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6070                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
6071         }
6072
6073         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
6074                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6075                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
6076         }
6077
6078         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
6079                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6080                 let _ = handle_error!(self, self.internal_update_add_htlc(counterparty_node_id, msg), *counterparty_node_id);
6081         }
6082
6083         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
6084                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6085                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
6086         }
6087
6088         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
6089                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6090                 let _ = handle_error!(self, self.internal_update_fail_htlc(counterparty_node_id, msg), *counterparty_node_id);
6091         }
6092
6093         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
6094                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6095                 let _ = handle_error!(self, self.internal_update_fail_malformed_htlc(counterparty_node_id, msg), *counterparty_node_id);
6096         }
6097
6098         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
6099                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6100                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
6101         }
6102
6103         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
6104                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6105                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
6106         }
6107
6108         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
6109                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6110                 let _ = handle_error!(self, self.internal_update_fee(counterparty_node_id, msg), *counterparty_node_id);
6111         }
6112
6113         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
6114                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6115                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
6116         }
6117
6118         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
6119                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
6120                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
6121                                 persist
6122                         } else {
6123                                 NotifyOption::SkipPersist
6124                         }
6125                 });
6126         }
6127
6128         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
6129                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6130                 let _ = handle_error!(self, self.internal_channel_reestablish(counterparty_node_id, msg), *counterparty_node_id);
6131         }
6132
6133         fn peer_disconnected(&self, counterparty_node_id: &PublicKey, no_connection_possible: bool) {
6134                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6135                 let mut failed_channels = Vec::new();
6136                 let mut no_channels_remain = true;
6137                 let mut per_peer_state = self.per_peer_state.write().unwrap();
6138                 {
6139                         log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates. We believe we {} make future connections to this peer.",
6140                                 log_pubkey!(counterparty_node_id), if no_connection_possible { "cannot" } else { "can" });
6141                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
6142                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6143                                 let peer_state = &mut *peer_state_lock;
6144                                 let pending_msg_events = &mut peer_state.pending_msg_events;
6145                                 peer_state.channel_by_id.retain(|_, chan| {
6146                                         chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger);
6147                                         if chan.is_shutdown() {
6148                                                 update_maps_on_chan_removal!(self, chan);
6149                                                 self.issue_channel_close_events(chan, ClosureReason::DisconnectedPeer);
6150                                                 return false;
6151                                         } else {
6152                                                 no_channels_remain = false;
6153                                         }
6154                                         true
6155                                 });
6156                                 pending_msg_events.retain(|msg| {
6157                                         match msg {
6158                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
6159                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
6160                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
6161                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
6162                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
6163                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
6164                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
6165                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
6166                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
6167                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
6168                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
6169                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
6170                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
6171                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
6172                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
6173                                                 &events::MessageSendEvent::HandleError { .. } => false,
6174                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
6175                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
6176                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
6177                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
6178                                         }
6179                                 });
6180                         }
6181                 }
6182                 if no_channels_remain {
6183                         per_peer_state.remove(counterparty_node_id);
6184                 }
6185                 mem::drop(per_peer_state);
6186
6187                 for failure in failed_channels.drain(..) {
6188                         self.finish_force_close_channel(failure);
6189                 }
6190         }
6191
6192         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init) -> Result<(), ()> {
6193                 if !init_msg.features.supports_static_remote_key() {
6194                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(counterparty_node_id));
6195                         return Err(());
6196                 }
6197
6198                 log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
6199
6200                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6201
6202                 {
6203                         let mut peer_state_lock = self.per_peer_state.write().unwrap();
6204                         match peer_state_lock.entry(counterparty_node_id.clone()) {
6205                                 hash_map::Entry::Vacant(e) => {
6206                                         e.insert(Mutex::new(PeerState {
6207                                                 channel_by_id: HashMap::new(),
6208                                                 latest_features: init_msg.features.clone(),
6209                                                 pending_msg_events: Vec::new(),
6210                                         }));
6211                                 },
6212                                 hash_map::Entry::Occupied(e) => {
6213                                         e.get().lock().unwrap().latest_features = init_msg.features.clone();
6214                                 },
6215                         }
6216                 }
6217
6218                 let per_peer_state = self.per_peer_state.read().unwrap();
6219
6220                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6221                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6222                         let peer_state = &mut *peer_state_lock;
6223                         let pending_msg_events = &mut peer_state.pending_msg_events;
6224                         peer_state.channel_by_id.retain(|_, chan| {
6225                                 let retain = if chan.get_counterparty_node_id() == *counterparty_node_id {
6226                                         if !chan.have_received_message() {
6227                                                 // If we created this (outbound) channel while we were disconnected from the
6228                                                 // peer we probably failed to send the open_channel message, which is now
6229                                                 // lost. We can't have had anything pending related to this channel, so we just
6230                                                 // drop it.
6231                                                 false
6232                                         } else {
6233                                                 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
6234                                                         node_id: chan.get_counterparty_node_id(),
6235                                                         msg: chan.get_channel_reestablish(&self.logger),
6236                                                 });
6237                                                 true
6238                                         }
6239                                 } else { true };
6240                                 if retain && chan.get_counterparty_node_id() != *counterparty_node_id {
6241                                         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) {
6242                                                 if let Ok(update_msg) = self.get_channel_update_for_broadcast(chan) {
6243                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelAnnouncement {
6244                                                                 node_id: *counterparty_node_id,
6245                                                                 msg, update_msg,
6246                                                         });
6247                                                 }
6248                                         }
6249                                 }
6250                                 retain
6251                         });
6252                 }
6253                 //TODO: Also re-broadcast announcement_signatures
6254                 Ok(())
6255         }
6256
6257         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
6258                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
6259
6260                 if msg.channel_id == [0; 32] {
6261                         let channel_ids: Vec<[u8; 32]> = {
6262                                 let per_peer_state = self.per_peer_state.read().unwrap();
6263                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
6264                                 if let None = peer_state_mutex_opt { return; }
6265                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
6266                                 let peer_state = &mut *peer_state_lock;
6267                                 peer_state.channel_by_id.keys().cloned().collect()
6268                         };
6269                         for channel_id in channel_ids {
6270                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
6271                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
6272                         }
6273                 } else {
6274                         {
6275                                 // First check if we can advance the channel type and try again.
6276                                 let per_peer_state = self.per_peer_state.read().unwrap();
6277                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
6278                                 if let None = peer_state_mutex_opt { return; }
6279                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
6280                                 let peer_state = &mut *peer_state_lock;
6281                                 if let Some(chan) = peer_state.channel_by_id.get_mut(&msg.channel_id) {
6282                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.genesis_hash) {
6283                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
6284                                                         node_id: *counterparty_node_id,
6285                                                         msg,
6286                                                 });
6287                                                 return;
6288                                         }
6289                                 }
6290                         }
6291
6292                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
6293                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
6294                 }
6295         }
6296
6297         fn provided_node_features(&self) -> NodeFeatures {
6298                 provided_node_features(&self.default_configuration)
6299         }
6300
6301         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
6302                 provided_init_features(&self.default_configuration)
6303         }
6304 }
6305
6306 /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
6307 /// [`ChannelManager`].
6308 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
6309         provided_init_features(config).to_context()
6310 }
6311
6312 /// Fetches the set of [`InvoiceFeatures`] flags which are provided by or required by
6313 /// [`ChannelManager`].
6314 ///
6315 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
6316 /// or not. Thus, this method is not public.
6317 #[cfg(any(feature = "_test_utils", test))]
6318 pub(crate) fn provided_invoice_features(config: &UserConfig) -> InvoiceFeatures {
6319         provided_init_features(config).to_context()
6320 }
6321
6322 /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
6323 /// [`ChannelManager`].
6324 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
6325         provided_init_features(config).to_context()
6326 }
6327
6328 /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
6329 /// [`ChannelManager`].
6330 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
6331         ChannelTypeFeatures::from_init(&provided_init_features(config))
6332 }
6333
6334 /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
6335 /// [`ChannelManager`].
6336 pub fn provided_init_features(_config: &UserConfig) -> InitFeatures {
6337         // Note that if new features are added here which other peers may (eventually) require, we
6338         // should also add the corresponding (optional) bit to the ChannelMessageHandler impl for
6339         // ErroringMessageHandler.
6340         let mut features = InitFeatures::empty();
6341         features.set_data_loss_protect_optional();
6342         features.set_upfront_shutdown_script_optional();
6343         features.set_variable_length_onion_required();
6344         features.set_static_remote_key_required();
6345         features.set_payment_secret_required();
6346         features.set_basic_mpp_optional();
6347         features.set_wumbo_optional();
6348         features.set_shutdown_any_segwit_optional();
6349         features.set_channel_type_optional();
6350         features.set_scid_privacy_optional();
6351         features.set_zero_conf_optional();
6352         #[cfg(anchors)]
6353         { // Attributes are not allowed on if expressions on our current MSRV of 1.41.
6354                 if _config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
6355                         features.set_anchors_zero_fee_htlc_tx_optional();
6356                 }
6357         }
6358         features
6359 }
6360
6361 const SERIALIZATION_VERSION: u8 = 1;
6362 const MIN_SERIALIZATION_VERSION: u8 = 1;
6363
6364 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
6365         (2, fee_base_msat, required),
6366         (4, fee_proportional_millionths, required),
6367         (6, cltv_expiry_delta, required),
6368 });
6369
6370 impl_writeable_tlv_based!(ChannelCounterparty, {
6371         (2, node_id, required),
6372         (4, features, required),
6373         (6, unspendable_punishment_reserve, required),
6374         (8, forwarding_info, option),
6375         (9, outbound_htlc_minimum_msat, option),
6376         (11, outbound_htlc_maximum_msat, option),
6377 });
6378
6379 impl Writeable for ChannelDetails {
6380         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
6381                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
6382                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
6383                 let user_channel_id_low = self.user_channel_id as u64;
6384                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
6385                 write_tlv_fields!(writer, {
6386                         (1, self.inbound_scid_alias, option),
6387                         (2, self.channel_id, required),
6388                         (3, self.channel_type, option),
6389                         (4, self.counterparty, required),
6390                         (5, self.outbound_scid_alias, option),
6391                         (6, self.funding_txo, option),
6392                         (7, self.config, option),
6393                         (8, self.short_channel_id, option),
6394                         (9, self.confirmations, option),
6395                         (10, self.channel_value_satoshis, required),
6396                         (12, self.unspendable_punishment_reserve, option),
6397                         (14, user_channel_id_low, required),
6398                         (16, self.balance_msat, required),
6399                         (18, self.outbound_capacity_msat, required),
6400                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
6401                         // filled in, so we can safely unwrap it here.
6402                         (19, self.next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
6403                         (20, self.inbound_capacity_msat, required),
6404                         (22, self.confirmations_required, option),
6405                         (24, self.force_close_spend_delay, option),
6406                         (26, self.is_outbound, required),
6407                         (28, self.is_channel_ready, required),
6408                         (30, self.is_usable, required),
6409                         (32, self.is_public, required),
6410                         (33, self.inbound_htlc_minimum_msat, option),
6411                         (35, self.inbound_htlc_maximum_msat, option),
6412                         (37, user_channel_id_high_opt, option),
6413                 });
6414                 Ok(())
6415         }
6416 }
6417
6418 impl Readable for ChannelDetails {
6419         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
6420                 _init_and_read_tlv_fields!(reader, {
6421                         (1, inbound_scid_alias, option),
6422                         (2, channel_id, required),
6423                         (3, channel_type, option),
6424                         (4, counterparty, required),
6425                         (5, outbound_scid_alias, option),
6426                         (6, funding_txo, option),
6427                         (7, config, option),
6428                         (8, short_channel_id, option),
6429                         (9, confirmations, option),
6430                         (10, channel_value_satoshis, required),
6431                         (12, unspendable_punishment_reserve, option),
6432                         (14, user_channel_id_low, required),
6433                         (16, balance_msat, required),
6434                         (18, outbound_capacity_msat, required),
6435                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
6436                         // filled in, so we can safely unwrap it here.
6437                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
6438                         (20, inbound_capacity_msat, required),
6439                         (22, confirmations_required, option),
6440                         (24, force_close_spend_delay, option),
6441                         (26, is_outbound, required),
6442                         (28, is_channel_ready, required),
6443                         (30, is_usable, required),
6444                         (32, is_public, required),
6445                         (33, inbound_htlc_minimum_msat, option),
6446                         (35, inbound_htlc_maximum_msat, option),
6447                         (37, user_channel_id_high_opt, option),
6448                 });
6449
6450                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
6451                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
6452                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
6453                 let user_channel_id = user_channel_id_low as u128 +
6454                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
6455
6456                 Ok(Self {
6457                         inbound_scid_alias,
6458                         channel_id: channel_id.0.unwrap(),
6459                         channel_type,
6460                         counterparty: counterparty.0.unwrap(),
6461                         outbound_scid_alias,
6462                         funding_txo,
6463                         config,
6464                         short_channel_id,
6465                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
6466                         unspendable_punishment_reserve,
6467                         user_channel_id,
6468                         balance_msat: balance_msat.0.unwrap(),
6469                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
6470                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
6471                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
6472                         confirmations_required,
6473                         confirmations,
6474                         force_close_spend_delay,
6475                         is_outbound: is_outbound.0.unwrap(),
6476                         is_channel_ready: is_channel_ready.0.unwrap(),
6477                         is_usable: is_usable.0.unwrap(),
6478                         is_public: is_public.0.unwrap(),
6479                         inbound_htlc_minimum_msat,
6480                         inbound_htlc_maximum_msat,
6481                 })
6482         }
6483 }
6484
6485 impl_writeable_tlv_based!(PhantomRouteHints, {
6486         (2, channels, vec_type),
6487         (4, phantom_scid, required),
6488         (6, real_node_pubkey, required),
6489 });
6490
6491 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
6492         (0, Forward) => {
6493                 (0, onion_packet, required),
6494                 (2, short_channel_id, required),
6495         },
6496         (1, Receive) => {
6497                 (0, payment_data, required),
6498                 (1, phantom_shared_secret, option),
6499                 (2, incoming_cltv_expiry, required),
6500         },
6501         (2, ReceiveKeysend) => {
6502                 (0, payment_preimage, required),
6503                 (2, incoming_cltv_expiry, required),
6504         },
6505 ;);
6506
6507 impl_writeable_tlv_based!(PendingHTLCInfo, {
6508         (0, routing, required),
6509         (2, incoming_shared_secret, required),
6510         (4, payment_hash, required),
6511         (6, outgoing_amt_msat, required),
6512         (8, outgoing_cltv_value, required),
6513         (9, incoming_amt_msat, option),
6514 });
6515
6516
6517 impl Writeable for HTLCFailureMsg {
6518         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
6519                 match self {
6520                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
6521                                 0u8.write(writer)?;
6522                                 channel_id.write(writer)?;
6523                                 htlc_id.write(writer)?;
6524                                 reason.write(writer)?;
6525                         },
6526                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
6527                                 channel_id, htlc_id, sha256_of_onion, failure_code
6528                         }) => {
6529                                 1u8.write(writer)?;
6530                                 channel_id.write(writer)?;
6531                                 htlc_id.write(writer)?;
6532                                 sha256_of_onion.write(writer)?;
6533                                 failure_code.write(writer)?;
6534                         },
6535                 }
6536                 Ok(())
6537         }
6538 }
6539
6540 impl Readable for HTLCFailureMsg {
6541         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
6542                 let id: u8 = Readable::read(reader)?;
6543                 match id {
6544                         0 => {
6545                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
6546                                         channel_id: Readable::read(reader)?,
6547                                         htlc_id: Readable::read(reader)?,
6548                                         reason: Readable::read(reader)?,
6549                                 }))
6550                         },
6551                         1 => {
6552                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
6553                                         channel_id: Readable::read(reader)?,
6554                                         htlc_id: Readable::read(reader)?,
6555                                         sha256_of_onion: Readable::read(reader)?,
6556                                         failure_code: Readable::read(reader)?,
6557                                 }))
6558                         },
6559                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
6560                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
6561                         // messages contained in the variants.
6562                         // In version 0.0.101, support for reading the variants with these types was added, and
6563                         // we should migrate to writing these variants when UpdateFailHTLC or
6564                         // UpdateFailMalformedHTLC get TLV fields.
6565                         2 => {
6566                                 let length: BigSize = Readable::read(reader)?;
6567                                 let mut s = FixedLengthReader::new(reader, length.0);
6568                                 let res = Readable::read(&mut s)?;
6569                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
6570                                 Ok(HTLCFailureMsg::Relay(res))
6571                         },
6572                         3 => {
6573                                 let length: BigSize = Readable::read(reader)?;
6574                                 let mut s = FixedLengthReader::new(reader, length.0);
6575                                 let res = Readable::read(&mut s)?;
6576                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
6577                                 Ok(HTLCFailureMsg::Malformed(res))
6578                         },
6579                         _ => Err(DecodeError::UnknownRequiredFeature),
6580                 }
6581         }
6582 }
6583
6584 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
6585         (0, Forward),
6586         (1, Fail),
6587 );
6588
6589 impl_writeable_tlv_based!(HTLCPreviousHopData, {
6590         (0, short_channel_id, required),
6591         (1, phantom_shared_secret, option),
6592         (2, outpoint, required),
6593         (4, htlc_id, required),
6594         (6, incoming_packet_shared_secret, required)
6595 });
6596
6597 impl Writeable for ClaimableHTLC {
6598         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
6599                 let (payment_data, keysend_preimage) = match &self.onion_payload {
6600                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
6601                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
6602                 };
6603                 write_tlv_fields!(writer, {
6604                         (0, self.prev_hop, required),
6605                         (1, self.total_msat, required),
6606                         (2, self.value, required),
6607                         (4, payment_data, option),
6608                         (6, self.cltv_expiry, required),
6609                         (8, keysend_preimage, option),
6610                 });
6611                 Ok(())
6612         }
6613 }
6614
6615 impl Readable for ClaimableHTLC {
6616         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
6617                 let mut prev_hop = crate::util::ser::OptionDeserWrapper(None);
6618                 let mut value = 0;
6619                 let mut payment_data: Option<msgs::FinalOnionHopData> = None;
6620                 let mut cltv_expiry = 0;
6621                 let mut total_msat = None;
6622                 let mut keysend_preimage: Option<PaymentPreimage> = None;
6623                 read_tlv_fields!(reader, {
6624                         (0, prev_hop, required),
6625                         (1, total_msat, option),
6626                         (2, value, required),
6627                         (4, payment_data, option),
6628                         (6, cltv_expiry, required),
6629                         (8, keysend_preimage, option)
6630                 });
6631                 let onion_payload = match keysend_preimage {
6632                         Some(p) => {
6633                                 if payment_data.is_some() {
6634                                         return Err(DecodeError::InvalidValue)
6635                                 }
6636                                 if total_msat.is_none() {
6637                                         total_msat = Some(value);
6638                                 }
6639                                 OnionPayload::Spontaneous(p)
6640                         },
6641                         None => {
6642                                 if total_msat.is_none() {
6643                                         if payment_data.is_none() {
6644                                                 return Err(DecodeError::InvalidValue)
6645                                         }
6646                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
6647                                 }
6648                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
6649                         },
6650                 };
6651                 Ok(Self {
6652                         prev_hop: prev_hop.0.unwrap(),
6653                         timer_ticks: 0,
6654                         value,
6655                         total_msat: total_msat.unwrap(),
6656                         onion_payload,
6657                         cltv_expiry,
6658                 })
6659         }
6660 }
6661
6662 impl Readable for HTLCSource {
6663         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
6664                 let id: u8 = Readable::read(reader)?;
6665                 match id {
6666                         0 => {
6667                                 let mut session_priv: crate::util::ser::OptionDeserWrapper<SecretKey> = crate::util::ser::OptionDeserWrapper(None);
6668                                 let mut first_hop_htlc_msat: u64 = 0;
6669                                 let mut path = Some(Vec::new());
6670                                 let mut payment_id = None;
6671                                 let mut payment_secret = None;
6672                                 let mut payment_params = None;
6673                                 read_tlv_fields!(reader, {
6674                                         (0, session_priv, required),
6675                                         (1, payment_id, option),
6676                                         (2, first_hop_htlc_msat, required),
6677                                         (3, payment_secret, option),
6678                                         (4, path, vec_type),
6679                                         (5, payment_params, option),
6680                                 });
6681                                 if payment_id.is_none() {
6682                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
6683                                         // instead.
6684                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
6685                                 }
6686                                 Ok(HTLCSource::OutboundRoute {
6687                                         session_priv: session_priv.0.unwrap(),
6688                                         first_hop_htlc_msat,
6689                                         path: path.unwrap(),
6690                                         payment_id: payment_id.unwrap(),
6691                                         payment_secret,
6692                                         payment_params,
6693                                 })
6694                         }
6695                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
6696                         _ => Err(DecodeError::UnknownRequiredFeature),
6697                 }
6698         }
6699 }
6700
6701 impl Writeable for HTLCSource {
6702         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
6703                 match self {
6704                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id, payment_secret, payment_params } => {
6705                                 0u8.write(writer)?;
6706                                 let payment_id_opt = Some(payment_id);
6707                                 write_tlv_fields!(writer, {
6708                                         (0, session_priv, required),
6709                                         (1, payment_id_opt, option),
6710                                         (2, first_hop_htlc_msat, required),
6711                                         (3, payment_secret, option),
6712                                         (4, *path, vec_type),
6713                                         (5, payment_params, option),
6714                                  });
6715                         }
6716                         HTLCSource::PreviousHopData(ref field) => {
6717                                 1u8.write(writer)?;
6718                                 field.write(writer)?;
6719                         }
6720                 }
6721                 Ok(())
6722         }
6723 }
6724
6725 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
6726         (0, forward_info, required),
6727         (1, prev_user_channel_id, (default_value, 0)),
6728         (2, prev_short_channel_id, required),
6729         (4, prev_htlc_id, required),
6730         (6, prev_funding_outpoint, required),
6731 });
6732
6733 impl_writeable_tlv_based_enum!(HTLCForwardInfo,
6734         (1, FailHTLC) => {
6735                 (0, htlc_id, required),
6736                 (2, err_packet, required),
6737         };
6738         (0, AddHTLC)
6739 );
6740
6741 impl_writeable_tlv_based!(PendingInboundPayment, {
6742         (0, payment_secret, required),
6743         (2, expiry_time, required),
6744         (4, user_payment_id, required),
6745         (6, payment_preimage, required),
6746         (8, min_value_msat, required),
6747 });
6748
6749 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>
6750 where
6751         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6752         T::Target: BroadcasterInterface,
6753         ES::Target: EntropySource,
6754         NS::Target: NodeSigner,
6755         SP::Target: SignerProvider,
6756         F::Target: FeeEstimator,
6757         R::Target: Router,
6758         L::Target: Logger,
6759 {
6760         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
6761                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
6762
6763                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
6764
6765                 self.genesis_hash.write(writer)?;
6766                 {
6767                         let best_block = self.best_block.read().unwrap();
6768                         best_block.height().write(writer)?;
6769                         best_block.block_hash().write(writer)?;
6770                 }
6771
6772                 {
6773                         let per_peer_state = self.per_peer_state.read().unwrap();
6774                         let mut unfunded_channels = 0;
6775                         let mut number_of_channels = 0;
6776                         for (_, peer_state_mutex) in per_peer_state.iter() {
6777                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6778                                 let peer_state = &mut *peer_state_lock;
6779                                 number_of_channels += peer_state.channel_by_id.len();
6780                                 for (_, channel) in peer_state.channel_by_id.iter() {
6781                                         if !channel.is_funding_initiated() {
6782                                                 unfunded_channels += 1;
6783                                         }
6784                                 }
6785                         }
6786
6787                         ((number_of_channels - unfunded_channels) as u64).write(writer)?;
6788
6789                         for (_, peer_state_mutex) in per_peer_state.iter() {
6790                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6791                                 let peer_state = &mut *peer_state_lock;
6792                                 for (_, channel) in peer_state.channel_by_id.iter() {
6793                                         if channel.is_funding_initiated() {
6794                                                 channel.write(writer)?;
6795                                         }
6796                                 }
6797                         }
6798                 }
6799
6800                 {
6801                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
6802                         (forward_htlcs.len() as u64).write(writer)?;
6803                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
6804                                 short_channel_id.write(writer)?;
6805                                 (pending_forwards.len() as u64).write(writer)?;
6806                                 for forward in pending_forwards {
6807                                         forward.write(writer)?;
6808                                 }
6809                         }
6810                 }
6811
6812                 let per_peer_state = self.per_peer_state.write().unwrap();
6813
6814                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
6815                 let claimable_payments = self.claimable_payments.lock().unwrap();
6816                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
6817
6818                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
6819                 (claimable_payments.claimable_htlcs.len() as u64).write(writer)?;
6820                 for (payment_hash, (purpose, previous_hops)) in claimable_payments.claimable_htlcs.iter() {
6821                         payment_hash.write(writer)?;
6822                         (previous_hops.len() as u64).write(writer)?;
6823                         for htlc in previous_hops.iter() {
6824                                 htlc.write(writer)?;
6825                         }
6826                         htlc_purposes.push(purpose);
6827                 }
6828
6829                 (per_peer_state.len() as u64).write(writer)?;
6830                 for (peer_pubkey, peer_state_mutex) in per_peer_state.iter() {
6831                         peer_pubkey.write(writer)?;
6832                         let peer_state = peer_state_mutex.lock().unwrap();
6833                         peer_state.latest_features.write(writer)?;
6834                 }
6835
6836                 let events = self.pending_events.lock().unwrap();
6837                 (events.len() as u64).write(writer)?;
6838                 for event in events.iter() {
6839                         event.write(writer)?;
6840                 }
6841
6842                 let background_events = self.pending_background_events.lock().unwrap();
6843                 (background_events.len() as u64).write(writer)?;
6844                 for event in background_events.iter() {
6845                         match event {
6846                                 BackgroundEvent::ClosingMonitorUpdate((funding_txo, monitor_update)) => {
6847                                         0u8.write(writer)?;
6848                                         funding_txo.write(writer)?;
6849                                         monitor_update.write(writer)?;
6850                                 },
6851                         }
6852                 }
6853
6854                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
6855                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
6856                 // likely to be identical.
6857                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
6858                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
6859
6860                 (pending_inbound_payments.len() as u64).write(writer)?;
6861                 for (hash, pending_payment) in pending_inbound_payments.iter() {
6862                         hash.write(writer)?;
6863                         pending_payment.write(writer)?;
6864                 }
6865
6866                 // For backwards compat, write the session privs and their total length.
6867                 let mut num_pending_outbounds_compat: u64 = 0;
6868                 for (_, outbound) in pending_outbound_payments.iter() {
6869                         if !outbound.is_fulfilled() && !outbound.abandoned() {
6870                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
6871                         }
6872                 }
6873                 num_pending_outbounds_compat.write(writer)?;
6874                 for (_, outbound) in pending_outbound_payments.iter() {
6875                         match outbound {
6876                                 PendingOutboundPayment::Legacy { session_privs } |
6877                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
6878                                         for session_priv in session_privs.iter() {
6879                                                 session_priv.write(writer)?;
6880                                         }
6881                                 }
6882                                 PendingOutboundPayment::Fulfilled { .. } => {},
6883                                 PendingOutboundPayment::Abandoned { .. } => {},
6884                         }
6885                 }
6886
6887                 // Encode without retry info for 0.0.101 compatibility.
6888                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
6889                 for (id, outbound) in pending_outbound_payments.iter() {
6890                         match outbound {
6891                                 PendingOutboundPayment::Legacy { session_privs } |
6892                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
6893                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
6894                                 },
6895                                 _ => {},
6896                         }
6897                 }
6898
6899                 let mut pending_intercepted_htlcs = None;
6900                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6901                 if our_pending_intercepts.len() != 0 {
6902                         pending_intercepted_htlcs = Some(our_pending_intercepts);
6903                 }
6904
6905                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
6906                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
6907                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
6908                         // map. Thus, if there are no entries we skip writing a TLV for it.
6909                         pending_claiming_payments = None;
6910                 } else {
6911                         debug_assert!(false, "While we have code to serialize pending_claiming_payments, the map should always be empty until a later PR");
6912                 }
6913
6914                 write_tlv_fields!(writer, {
6915                         (1, pending_outbound_payments_no_retry, required),
6916                         (2, pending_intercepted_htlcs, option),
6917                         (3, pending_outbound_payments, required),
6918                         (4, pending_claiming_payments, option),
6919                         (5, self.our_network_pubkey, required),
6920                         (7, self.fake_scid_rand_bytes, required),
6921                         (9, htlc_purposes, vec_type),
6922                         (11, self.probing_cookie_secret, required),
6923                 });
6924
6925                 Ok(())
6926         }
6927 }
6928
6929 /// Arguments for the creation of a ChannelManager that are not deserialized.
6930 ///
6931 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
6932 /// is:
6933 /// 1) Deserialize all stored [`ChannelMonitor`]s.
6934 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
6935 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
6936 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
6937 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
6938 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
6939 ///    same way you would handle a [`chain::Filter`] call using
6940 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
6941 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
6942 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
6943 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
6944 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
6945 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
6946 ///    the next step.
6947 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
6948 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
6949 ///
6950 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
6951 /// call any other methods on the newly-deserialized [`ChannelManager`].
6952 ///
6953 /// Note that because some channels may be closed during deserialization, it is critical that you
6954 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
6955 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
6956 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
6957 /// not force-close the same channels but consider them live), you may end up revoking a state for
6958 /// which you've already broadcasted the transaction.
6959 ///
6960 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
6961 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
6962 where
6963         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6964         T::Target: BroadcasterInterface,
6965         ES::Target: EntropySource,
6966         NS::Target: NodeSigner,
6967         SP::Target: SignerProvider,
6968         F::Target: FeeEstimator,
6969         R::Target: Router,
6970         L::Target: Logger,
6971 {
6972         /// A cryptographically secure source of entropy.
6973         pub entropy_source: ES,
6974
6975         /// A signer that is able to perform node-scoped cryptographic operations.
6976         pub node_signer: NS,
6977
6978         /// The keys provider which will give us relevant keys. Some keys will be loaded during
6979         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
6980         /// signing data.
6981         pub signer_provider: SP,
6982
6983         /// The fee_estimator for use in the ChannelManager in the future.
6984         ///
6985         /// No calls to the FeeEstimator will be made during deserialization.
6986         pub fee_estimator: F,
6987         /// The chain::Watch for use in the ChannelManager in the future.
6988         ///
6989         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
6990         /// you have deserialized ChannelMonitors separately and will add them to your
6991         /// chain::Watch after deserializing this ChannelManager.
6992         pub chain_monitor: M,
6993
6994         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
6995         /// used to broadcast the latest local commitment transactions of channels which must be
6996         /// force-closed during deserialization.
6997         pub tx_broadcaster: T,
6998         /// The router which will be used in the ChannelManager in the future for finding routes
6999         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
7000         ///
7001         /// No calls to the router will be made during deserialization.
7002         pub router: R,
7003         /// The Logger for use in the ChannelManager and which may be used to log information during
7004         /// deserialization.
7005         pub logger: L,
7006         /// Default settings used for new channels. Any existing channels will continue to use the
7007         /// runtime settings which were stored when the ChannelManager was serialized.
7008         pub default_config: UserConfig,
7009
7010         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
7011         /// value.get_funding_txo() should be the key).
7012         ///
7013         /// If a monitor is inconsistent with the channel state during deserialization the channel will
7014         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
7015         /// is true for missing channels as well. If there is a monitor missing for which we find
7016         /// channel data Err(DecodeError::InvalidValue) will be returned.
7017         ///
7018         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
7019         /// this struct.
7020         ///
7021         /// (C-not exported) because we have no HashMap bindings
7022         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>,
7023 }
7024
7025 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
7026                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
7027 where
7028         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7029         T::Target: BroadcasterInterface,
7030         ES::Target: EntropySource,
7031         NS::Target: NodeSigner,
7032         SP::Target: SignerProvider,
7033         F::Target: FeeEstimator,
7034         R::Target: Router,
7035         L::Target: Logger,
7036 {
7037         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
7038         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
7039         /// populate a HashMap directly from C.
7040         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,
7041                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>) -> Self {
7042                 Self {
7043                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
7044                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
7045                 }
7046         }
7047 }
7048
7049 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
7050 // SipmleArcChannelManager type:
7051 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
7052         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
7053 where
7054         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7055         T::Target: BroadcasterInterface,
7056         ES::Target: EntropySource,
7057         NS::Target: NodeSigner,
7058         SP::Target: SignerProvider,
7059         F::Target: FeeEstimator,
7060         R::Target: Router,
7061         L::Target: Logger,
7062 {
7063         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
7064                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
7065                 Ok((blockhash, Arc::new(chan_manager)))
7066         }
7067 }
7068
7069 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
7070         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
7071 where
7072         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7073         T::Target: BroadcasterInterface,
7074         ES::Target: EntropySource,
7075         NS::Target: NodeSigner,
7076         SP::Target: SignerProvider,
7077         F::Target: FeeEstimator,
7078         R::Target: Router,
7079         L::Target: Logger,
7080 {
7081         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
7082                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
7083
7084                 let genesis_hash: BlockHash = Readable::read(reader)?;
7085                 let best_block_height: u32 = Readable::read(reader)?;
7086                 let best_block_hash: BlockHash = Readable::read(reader)?;
7087
7088                 let mut failed_htlcs = Vec::new();
7089
7090                 let channel_count: u64 = Readable::read(reader)?;
7091                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
7092                 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));
7093                 let mut id_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
7094                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
7095                 let mut channel_closures = Vec::new();
7096                 for _ in 0..channel_count {
7097                         let mut channel: Channel<<SP::Target as SignerProvider>::Signer> = Channel::read(reader, (
7098                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
7099                         ))?;
7100                         let funding_txo = channel.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
7101                         funding_txo_set.insert(funding_txo.clone());
7102                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
7103                                 if channel.get_cur_holder_commitment_transaction_number() < monitor.get_cur_holder_commitment_number() ||
7104                                                 channel.get_revoked_counterparty_commitment_transaction_number() < monitor.get_min_seen_secret() ||
7105                                                 channel.get_cur_counterparty_commitment_transaction_number() < monitor.get_cur_counterparty_commitment_number() ||
7106                                                 channel.get_latest_monitor_update_id() > monitor.get_latest_update_id() {
7107                                         // If the channel is ahead of the monitor, return InvalidValue:
7108                                         log_error!(args.logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
7109                                         log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
7110                                                 log_bytes!(channel.channel_id()), monitor.get_latest_update_id(), channel.get_latest_monitor_update_id());
7111                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
7112                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
7113                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
7114                                         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");
7115                                         return Err(DecodeError::InvalidValue);
7116                                 } else if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
7117                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
7118                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
7119                                                 channel.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
7120                                         // But if the channel is behind of the monitor, close the channel:
7121                                         log_error!(args.logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
7122                                         log_error!(args.logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
7123                                         log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
7124                                                 log_bytes!(channel.channel_id()), monitor.get_latest_update_id(), channel.get_latest_monitor_update_id());
7125                                         let (_, mut new_failed_htlcs) = channel.force_shutdown(true);
7126                                         failed_htlcs.append(&mut new_failed_htlcs);
7127                                         monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
7128                                         channel_closures.push(events::Event::ChannelClosed {
7129                                                 channel_id: channel.channel_id(),
7130                                                 user_channel_id: channel.get_user_id(),
7131                                                 reason: ClosureReason::OutdatedChannelManager
7132                                         });
7133                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
7134                                                 let mut found_htlc = false;
7135                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
7136                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
7137                                                 }
7138                                                 if !found_htlc {
7139                                                         // If we have some HTLCs in the channel which are not present in the newer
7140                                                         // ChannelMonitor, they have been removed and should be failed back to
7141                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
7142                                                         // were actually claimed we'd have generated and ensured the previous-hop
7143                                                         // claim update ChannelMonitor updates were persisted prior to persising
7144                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
7145                                                         // backwards leg of the HTLC will simply be rejected.
7146                                                         log_info!(args.logger,
7147                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
7148                                                                 log_bytes!(channel.channel_id()), log_bytes!(payment_hash.0));
7149                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.get_counterparty_node_id(), channel.channel_id()));
7150                                                 }
7151                                         }
7152                                 } else {
7153                                         log_info!(args.logger, "Successfully loaded channel {}", log_bytes!(channel.channel_id()));
7154                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
7155                                                 short_to_chan_info.insert(short_channel_id, (channel.get_counterparty_node_id(), channel.channel_id()));
7156                                         }
7157                                         if channel.is_funding_initiated() {
7158                                                 id_to_peer.insert(channel.channel_id(), channel.get_counterparty_node_id());
7159                                         }
7160                                         match peer_channels.entry(channel.get_counterparty_node_id()) {
7161                                                 hash_map::Entry::Occupied(mut entry) => {
7162                                                         let by_id_map = entry.get_mut();
7163                                                         by_id_map.insert(channel.channel_id(), channel);
7164                                                 },
7165                                                 hash_map::Entry::Vacant(entry) => {
7166                                                         let mut by_id_map = HashMap::new();
7167                                                         by_id_map.insert(channel.channel_id(), channel);
7168                                                         entry.insert(by_id_map);
7169                                                 }
7170                                         }
7171                                 }
7172                         } else if channel.is_awaiting_initial_mon_persist() {
7173                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
7174                                 // was in-progress, we never broadcasted the funding transaction and can still
7175                                 // safely discard the channel.
7176                                 let _ = channel.force_shutdown(false);
7177                                 channel_closures.push(events::Event::ChannelClosed {
7178                                         channel_id: channel.channel_id(),
7179                                         user_channel_id: channel.get_user_id(),
7180                                         reason: ClosureReason::DisconnectedPeer,
7181                                 });
7182                         } else {
7183                                 log_error!(args.logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", log_bytes!(channel.channel_id()));
7184                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
7185                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
7186                                 log_error!(args.logger, " Without the ChannelMonitor we cannot continue without risking funds.");
7187                                 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");
7188                                 return Err(DecodeError::InvalidValue);
7189                         }
7190                 }
7191
7192                 for (funding_txo, monitor) in args.channel_monitors.iter_mut() {
7193                         if !funding_txo_set.contains(funding_txo) {
7194                                 log_info!(args.logger, "Broadcasting latest holder commitment transaction for closed channel {}", log_bytes!(funding_txo.to_channel_id()));
7195                                 monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
7196                         }
7197                 }
7198
7199                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
7200                 let forward_htlcs_count: u64 = Readable::read(reader)?;
7201                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
7202                 for _ in 0..forward_htlcs_count {
7203                         let short_channel_id = Readable::read(reader)?;
7204                         let pending_forwards_count: u64 = Readable::read(reader)?;
7205                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
7206                         for _ in 0..pending_forwards_count {
7207                                 pending_forwards.push(Readable::read(reader)?);
7208                         }
7209                         forward_htlcs.insert(short_channel_id, pending_forwards);
7210                 }
7211
7212                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
7213                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
7214                 for _ in 0..claimable_htlcs_count {
7215                         let payment_hash = Readable::read(reader)?;
7216                         let previous_hops_len: u64 = Readable::read(reader)?;
7217                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
7218                         for _ in 0..previous_hops_len {
7219                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
7220                         }
7221                         claimable_htlcs_list.push((payment_hash, previous_hops));
7222                 }
7223
7224                 let peer_count: u64 = Readable::read(reader)?;
7225                 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>>)>()));
7226                 for _ in 0..peer_count {
7227                         let peer_pubkey = Readable::read(reader)?;
7228                         let peer_state = PeerState {
7229                                 channel_by_id: peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new()),
7230                                 latest_features: Readable::read(reader)?,
7231                                 pending_msg_events: Vec::new(),
7232                         };
7233                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
7234                 }
7235
7236                 let event_count: u64 = Readable::read(reader)?;
7237                 let mut pending_events_read: Vec<events::Event> = Vec::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<events::Event>()));
7238                 for _ in 0..event_count {
7239                         match MaybeReadable::read(reader)? {
7240                                 Some(event) => pending_events_read.push(event),
7241                                 None => continue,
7242                         }
7243                 }
7244
7245                 let background_event_count: u64 = Readable::read(reader)?;
7246                 let mut pending_background_events_read: Vec<BackgroundEvent> = Vec::with_capacity(cmp::min(background_event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<BackgroundEvent>()));
7247                 for _ in 0..background_event_count {
7248                         match <u8 as Readable>::read(reader)? {
7249                                 0 => pending_background_events_read.push(BackgroundEvent::ClosingMonitorUpdate((Readable::read(reader)?, Readable::read(reader)?))),
7250                                 _ => return Err(DecodeError::InvalidValue),
7251                         }
7252                 }
7253
7254                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
7255                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
7256
7257                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
7258                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
7259                 for _ in 0..pending_inbound_payment_count {
7260                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
7261                                 return Err(DecodeError::InvalidValue);
7262                         }
7263                 }
7264
7265                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
7266                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
7267                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
7268                 for _ in 0..pending_outbound_payments_count_compat {
7269                         let session_priv = Readable::read(reader)?;
7270                         let payment = PendingOutboundPayment::Legacy {
7271                                 session_privs: [session_priv].iter().cloned().collect()
7272                         };
7273                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
7274                                 return Err(DecodeError::InvalidValue)
7275                         };
7276                 }
7277
7278                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
7279                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
7280                 let mut pending_outbound_payments = None;
7281                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
7282                 let mut received_network_pubkey: Option<PublicKey> = None;
7283                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
7284                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
7285                 let mut claimable_htlc_purposes = None;
7286                 let mut pending_claiming_payments = Some(HashMap::new());
7287                 read_tlv_fields!(reader, {
7288                         (1, pending_outbound_payments_no_retry, option),
7289                         (2, pending_intercepted_htlcs, option),
7290                         (3, pending_outbound_payments, option),
7291                         (4, pending_claiming_payments, option),
7292                         (5, received_network_pubkey, option),
7293                         (7, fake_scid_rand_bytes, option),
7294                         (9, claimable_htlc_purposes, vec_type),
7295                         (11, probing_cookie_secret, option),
7296                 });
7297                 if fake_scid_rand_bytes.is_none() {
7298                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
7299                 }
7300
7301                 if probing_cookie_secret.is_none() {
7302                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
7303                 }
7304
7305                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
7306                         pending_outbound_payments = Some(pending_outbound_payments_compat);
7307                 } else if pending_outbound_payments.is_none() {
7308                         let mut outbounds = HashMap::new();
7309                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
7310                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
7311                         }
7312                         pending_outbound_payments = Some(outbounds);
7313                 } else {
7314                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
7315                         // ChannelMonitor data for any channels for which we do not have authorative state
7316                         // (i.e. those for which we just force-closed above or we otherwise don't have a
7317                         // corresponding `Channel` at all).
7318                         // This avoids several edge-cases where we would otherwise "forget" about pending
7319                         // payments which are still in-flight via their on-chain state.
7320                         // We only rebuild the pending payments map if we were most recently serialized by
7321                         // 0.0.102+
7322                         for (_, monitor) in args.channel_monitors.iter() {
7323                                 if id_to_peer.get(&monitor.get_funding_txo().0.to_channel_id()).is_none() {
7324                                         for (htlc_source, htlc) in monitor.get_pending_outbound_htlcs() {
7325                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, payment_secret, .. } = htlc_source {
7326                                                         if path.is_empty() {
7327                                                                 log_error!(args.logger, "Got an empty path for a pending payment");
7328                                                                 return Err(DecodeError::InvalidValue);
7329                                                         }
7330                                                         let path_amt = path.last().unwrap().fee_msat;
7331                                                         let mut session_priv_bytes = [0; 32];
7332                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
7333                                                         match pending_outbound_payments.as_mut().unwrap().entry(payment_id) {
7334                                                                 hash_map::Entry::Occupied(mut entry) => {
7335                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
7336                                                                         log_info!(args.logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
7337                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), log_bytes!(htlc.payment_hash.0));
7338                                                                 },
7339                                                                 hash_map::Entry::Vacant(entry) => {
7340                                                                         let path_fee = path.get_path_fees();
7341                                                                         entry.insert(PendingOutboundPayment::Retryable {
7342                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
7343                                                                                 payment_hash: htlc.payment_hash,
7344                                                                                 payment_secret,
7345                                                                                 pending_amt_msat: path_amt,
7346                                                                                 pending_fee_msat: Some(path_fee),
7347                                                                                 total_msat: path_amt,
7348                                                                                 starting_block_height: best_block_height,
7349                                                                         });
7350                                                                         log_info!(args.logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
7351                                                                                 path_amt, log_bytes!(htlc.payment_hash.0),  log_bytes!(session_priv_bytes));
7352                                                                 }
7353                                                         }
7354                                                 }
7355                                         }
7356                                         for (htlc_source, htlc) in monitor.get_all_current_outbound_htlcs() {
7357                                                 if let HTLCSource::PreviousHopData(prev_hop_data) = htlc_source {
7358                                                         let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
7359                                                                 info.prev_funding_outpoint == prev_hop_data.outpoint &&
7360                                                                         info.prev_htlc_id == prev_hop_data.htlc_id
7361                                                         };
7362                                                         // The ChannelMonitor is now responsible for this HTLC's
7363                                                         // failure/success and will let us know what its outcome is. If we
7364                                                         // still have an entry for this HTLC in `forward_htlcs` or
7365                                                         // `pending_intercepted_htlcs`, we were apparently not persisted after
7366                                                         // the monitor was when forwarding the payment.
7367                                                         forward_htlcs.retain(|_, forwards| {
7368                                                                 forwards.retain(|forward| {
7369                                                                         if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
7370                                                                                 if pending_forward_matches_htlc(&htlc_info) {
7371                                                                                         log_info!(args.logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
7372                                                                                                 log_bytes!(htlc.payment_hash.0), log_bytes!(monitor.get_funding_txo().0.to_channel_id()));
7373                                                                                         false
7374                                                                                 } else { true }
7375                                                                         } else { true }
7376                                                                 });
7377                                                                 !forwards.is_empty()
7378                                                         });
7379                                                         pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
7380                                                                 if pending_forward_matches_htlc(&htlc_info) {
7381                                                                         log_info!(args.logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
7382                                                                                 log_bytes!(htlc.payment_hash.0), log_bytes!(monitor.get_funding_txo().0.to_channel_id()));
7383                                                                         pending_events_read.retain(|event| {
7384                                                                                 if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
7385                                                                                         intercepted_id != ev_id
7386                                                                                 } else { true }
7387                                                                         });
7388                                                                         false
7389                                                                 } else { true }
7390                                                         });
7391                                                 }
7392                                         }
7393                                 }
7394                         }
7395                 }
7396
7397                 if !forward_htlcs.is_empty() {
7398                         // If we have pending HTLCs to forward, assume we either dropped a
7399                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
7400                         // shut down before the timer hit. Either way, set the time_forwardable to a small
7401                         // constant as enough time has likely passed that we should simply handle the forwards
7402                         // now, or at least after the user gets a chance to reconnect to our peers.
7403                         pending_events_read.push(events::Event::PendingHTLCsForwardable {
7404                                 time_forwardable: Duration::from_secs(2),
7405                         });
7406                 }
7407
7408                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
7409                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
7410
7411                 let mut claimable_htlcs = HashMap::with_capacity(claimable_htlcs_list.len());
7412                 if let Some(mut purposes) = claimable_htlc_purposes {
7413                         if purposes.len() != claimable_htlcs_list.len() {
7414                                 return Err(DecodeError::InvalidValue);
7415                         }
7416                         for (purpose, (payment_hash, previous_hops)) in purposes.drain(..).zip(claimable_htlcs_list.drain(..)) {
7417                                 claimable_htlcs.insert(payment_hash, (purpose, previous_hops));
7418                         }
7419                 } else {
7420                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
7421                         // include a `_legacy_hop_data` in the `OnionPayload`.
7422                         for (payment_hash, previous_hops) in claimable_htlcs_list.drain(..) {
7423                                 if previous_hops.is_empty() {
7424                                         return Err(DecodeError::InvalidValue);
7425                                 }
7426                                 let purpose = match &previous_hops[0].onion_payload {
7427                                         OnionPayload::Invoice { _legacy_hop_data } => {
7428                                                 if let Some(hop_data) = _legacy_hop_data {
7429                                                         events::PaymentPurpose::InvoicePayment {
7430                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
7431                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
7432                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
7433                                                                                 Ok((payment_preimage, _)) => payment_preimage,
7434                                                                                 Err(()) => {
7435                                                                                         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));
7436                                                                                         return Err(DecodeError::InvalidValue);
7437                                                                                 }
7438                                                                         }
7439                                                                 },
7440                                                                 payment_secret: hop_data.payment_secret,
7441                                                         }
7442                                                 } else { return Err(DecodeError::InvalidValue); }
7443                                         },
7444                                         OnionPayload::Spontaneous(payment_preimage) =>
7445                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
7446                                 };
7447                                 claimable_htlcs.insert(payment_hash, (purpose, previous_hops));
7448                         }
7449                 }
7450
7451                 let mut secp_ctx = Secp256k1::new();
7452                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
7453
7454                 if !channel_closures.is_empty() {
7455                         pending_events_read.append(&mut channel_closures);
7456                 }
7457
7458                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
7459                         Ok(key) => key,
7460                         Err(()) => return Err(DecodeError::InvalidValue)
7461                 };
7462                 if let Some(network_pubkey) = received_network_pubkey {
7463                         if network_pubkey != our_network_pubkey {
7464                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
7465                                 return Err(DecodeError::InvalidValue);
7466                         }
7467                 }
7468
7469                 let mut outbound_scid_aliases = HashSet::new();
7470                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
7471                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7472                         let peer_state = &mut *peer_state_lock;
7473                         for (chan_id, chan) in peer_state.channel_by_id.iter_mut() {
7474                                 if chan.outbound_scid_alias() == 0 {
7475                                         let mut outbound_scid_alias;
7476                                         loop {
7477                                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias
7478                                                         .get_fake_scid(best_block_height, &genesis_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
7479                                                 if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
7480                                         }
7481                                         chan.set_outbound_scid_alias(outbound_scid_alias);
7482                                 } else if !outbound_scid_aliases.insert(chan.outbound_scid_alias()) {
7483                                         // Note that in rare cases its possible to hit this while reading an older
7484                                         // channel if we just happened to pick a colliding outbound alias above.
7485                                         log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.outbound_scid_alias());
7486                                         return Err(DecodeError::InvalidValue);
7487                                 }
7488                                 if chan.is_usable() {
7489                                         if short_to_chan_info.insert(chan.outbound_scid_alias(), (chan.get_counterparty_node_id(), *chan_id)).is_some() {
7490                                                 // Note that in rare cases its possible to hit this while reading an older
7491                                                 // channel if we just happened to pick a colliding outbound alias above.
7492                                                 log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.outbound_scid_alias());
7493                                                 return Err(DecodeError::InvalidValue);
7494                                         }
7495                                 }
7496                         }
7497                 }
7498
7499                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
7500
7501                 for (_, monitor) in args.channel_monitors.iter() {
7502                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
7503                                 if let Some((payment_purpose, claimable_htlcs)) = claimable_htlcs.remove(&payment_hash) {
7504                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", log_bytes!(payment_hash.0));
7505                                         let mut claimable_amt_msat = 0;
7506                                         let mut receiver_node_id = Some(our_network_pubkey);
7507                                         let phantom_shared_secret = claimable_htlcs[0].prev_hop.phantom_shared_secret;
7508                                         if phantom_shared_secret.is_some() {
7509                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
7510                                                         .expect("Failed to get node_id for phantom node recipient");
7511                                                 receiver_node_id = Some(phantom_pubkey)
7512                                         }
7513                                         for claimable_htlc in claimable_htlcs {
7514                                                 claimable_amt_msat += claimable_htlc.value;
7515
7516                                                 // Add a holding-cell claim of the payment to the Channel, which should be
7517                                                 // applied ~immediately on peer reconnection. Because it won't generate a
7518                                                 // new commitment transaction we can just provide the payment preimage to
7519                                                 // the corresponding ChannelMonitor and nothing else.
7520                                                 //
7521                                                 // We do so directly instead of via the normal ChannelMonitor update
7522                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
7523                                                 // we're not allowed to call it directly yet. Further, we do the update
7524                                                 // without incrementing the ChannelMonitor update ID as there isn't any
7525                                                 // reason to.
7526                                                 // If we were to generate a new ChannelMonitor update ID here and then
7527                                                 // crash before the user finishes block connect we'd end up force-closing
7528                                                 // this channel as well. On the flip side, there's no harm in restarting
7529                                                 // without the new monitor persisted - we'll end up right back here on
7530                                                 // restart.
7531                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
7532                                                 if let Some(peer_node_id) = id_to_peer.get(&previous_channel_id){
7533                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
7534                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7535                                                         let peer_state = &mut *peer_state_lock;
7536                                                         if let Some(channel) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
7537                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &args.logger);
7538                                                         }
7539                                                 }
7540                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
7541                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
7542                                                 }
7543                                         }
7544                                         pending_events_read.push(events::Event::PaymentClaimed {
7545                                                 receiver_node_id,
7546                                                 payment_hash,
7547                                                 purpose: payment_purpose,
7548                                                 amount_msat: claimable_amt_msat,
7549                                         });
7550                                 }
7551                         }
7552                 }
7553
7554                 let channel_manager = ChannelManager {
7555                         genesis_hash,
7556                         fee_estimator: bounded_fee_estimator,
7557                         chain_monitor: args.chain_monitor,
7558                         tx_broadcaster: args.tx_broadcaster,
7559                         router: args.router,
7560
7561                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
7562
7563                         inbound_payment_key: expanded_inbound_key,
7564                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
7565                         pending_outbound_payments: OutboundPayments { pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()) },
7566                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
7567
7568                         forward_htlcs: Mutex::new(forward_htlcs),
7569                         claimable_payments: Mutex::new(ClaimablePayments { claimable_htlcs, pending_claiming_payments: pending_claiming_payments.unwrap() }),
7570                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
7571                         id_to_peer: Mutex::new(id_to_peer),
7572                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
7573                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
7574
7575                         probing_cookie_secret: probing_cookie_secret.unwrap(),
7576
7577                         our_network_pubkey,
7578                         secp_ctx,
7579
7580                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
7581
7582                         per_peer_state: FairRwLock::new(per_peer_state),
7583
7584                         pending_events: Mutex::new(pending_events_read),
7585                         pending_background_events: Mutex::new(pending_background_events_read),
7586                         total_consistency_lock: RwLock::new(()),
7587                         persistence_notifier: Notifier::new(),
7588
7589                         entropy_source: args.entropy_source,
7590                         node_signer: args.node_signer,
7591                         signer_provider: args.signer_provider,
7592
7593                         logger: args.logger,
7594                         default_configuration: args.default_config,
7595                 };
7596
7597                 for htlc_source in failed_htlcs.drain(..) {
7598                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
7599                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
7600                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
7601                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
7602                 }
7603
7604                 //TODO: Broadcast channel update for closed channels, but only after we've made a
7605                 //connection or two.
7606
7607                 Ok((best_block_hash.clone(), channel_manager))
7608         }
7609 }
7610
7611 #[cfg(test)]
7612 mod tests {
7613         use bitcoin::hashes::Hash;
7614         use bitcoin::hashes::sha256::Hash as Sha256;
7615         use bitcoin::hashes::hex::FromHex;
7616         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
7617         use bitcoin::secp256k1::ecdsa::Signature;
7618         use bitcoin::secp256k1::ffi::Signature as FFISignature;
7619         use bitcoin::blockdata::script::Script;
7620         use bitcoin::Txid;
7621         use core::time::Duration;
7622         use core::sync::atomic::Ordering;
7623         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
7624         use crate::ln::channelmanager::{inbound_payment, PaymentId, PaymentSendFailure, InterceptId};
7625         use crate::ln::functional_test_utils::*;
7626         use crate::ln::msgs;
7627         use crate::ln::msgs::{ChannelMessageHandler, OptionalField};
7628         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
7629         use crate::util::errors::APIError;
7630         use crate::util::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
7631         use crate::util::test_utils;
7632         use crate::util::config::ChannelConfig;
7633         use crate::chain::keysinterface::EntropySource;
7634
7635         #[test]
7636         fn test_notify_limits() {
7637                 // Check that a few cases which don't require the persistence of a new ChannelManager,
7638                 // indeed, do not cause the persistence of a new ChannelManager.
7639                 let chanmon_cfgs = create_chanmon_cfgs(3);
7640                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7641                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7642                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7643
7644                 // All nodes start with a persistable update pending as `create_network` connects each node
7645                 // with all other nodes to make most tests simpler.
7646                 assert!(nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7647                 assert!(nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7648                 assert!(nodes[2].node.await_persistable_update_timeout(Duration::from_millis(1)));
7649
7650                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7651
7652                 // We check that the channel info nodes have doesn't change too early, even though we try
7653                 // to connect messages with new values
7654                 chan.0.contents.fee_base_msat *= 2;
7655                 chan.1.contents.fee_base_msat *= 2;
7656                 let node_a_chan_info = nodes[0].node.list_channels()[0].clone();
7657                 let node_b_chan_info = nodes[1].node.list_channels()[0].clone();
7658
7659                 // The first two nodes (which opened a channel) should now require fresh persistence
7660                 assert!(nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7661                 assert!(nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7662                 // ... but the last node should not.
7663                 assert!(!nodes[2].node.await_persistable_update_timeout(Duration::from_millis(1)));
7664                 // After persisting the first two nodes they should no longer need fresh persistence.
7665                 assert!(!nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7666                 assert!(!nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7667
7668                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
7669                 // about the channel.
7670                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
7671                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
7672                 assert!(!nodes[2].node.await_persistable_update_timeout(Duration::from_millis(1)));
7673
7674                 // The nodes which are a party to the channel should also ignore messages from unrelated
7675                 // parties.
7676                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
7677                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
7678                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
7679                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
7680                 assert!(!nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7681                 assert!(!nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7682
7683                 // At this point the channel info given by peers should still be the same.
7684                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
7685                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
7686
7687                 // An earlier version of handle_channel_update didn't check the directionality of the
7688                 // update message and would always update the local fee info, even if our peer was
7689                 // (spuriously) forwarding us our own channel_update.
7690                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
7691                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
7692                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
7693
7694                 // First deliver each peers' own message, checking that the node doesn't need to be
7695                 // persisted and that its channel info remains the same.
7696                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
7697                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
7698                 assert!(!nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7699                 assert!(!nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7700                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
7701                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
7702
7703                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
7704                 // the channel info has updated.
7705                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
7706                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
7707                 assert!(nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7708                 assert!(nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7709                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
7710                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
7711         }
7712
7713         #[test]
7714         fn test_keysend_dup_hash_partial_mpp() {
7715                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
7716                 // expected.
7717                 let chanmon_cfgs = create_chanmon_cfgs(2);
7718                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7719                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7720                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7721                 create_announced_chan_between_nodes(&nodes, 0, 1);
7722
7723                 // First, send a partial MPP payment.
7724                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
7725                 let mut mpp_route = route.clone();
7726                 mpp_route.paths.push(mpp_route.paths[0].clone());
7727
7728                 let payment_id = PaymentId([42; 32]);
7729                 // Use the utility function send_payment_along_path to send the payment with MPP data which
7730                 // indicates there are more HTLCs coming.
7731                 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.
7732                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &mpp_route).unwrap();
7733                 nodes[0].node.send_payment_along_path(&mpp_route.paths[0], &route.payment_params, &our_payment_hash, &Some(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
7734                 check_added_monitors!(nodes[0], 1);
7735                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7736                 assert_eq!(events.len(), 1);
7737                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
7738
7739                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
7740                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), PaymentId(payment_preimage.0)).unwrap();
7741                 check_added_monitors!(nodes[0], 1);
7742                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7743                 assert_eq!(events.len(), 1);
7744                 let ev = events.drain(..).next().unwrap();
7745                 let payment_event = SendEvent::from_event(ev);
7746                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7747                 check_added_monitors!(nodes[1], 0);
7748                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7749                 expect_pending_htlcs_forwardable!(nodes[1]);
7750                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7751                 check_added_monitors!(nodes[1], 1);
7752                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7753                 assert!(updates.update_add_htlcs.is_empty());
7754                 assert!(updates.update_fulfill_htlcs.is_empty());
7755                 assert_eq!(updates.update_fail_htlcs.len(), 1);
7756                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7757                 assert!(updates.update_fee.is_none());
7758                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7759                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
7760                 expect_payment_failed!(nodes[0], our_payment_hash, true);
7761
7762                 // Send the second half of the original MPP payment.
7763                 nodes[0].node.send_payment_along_path(&mpp_route.paths[1], &route.payment_params, &our_payment_hash, &Some(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
7764                 check_added_monitors!(nodes[0], 1);
7765                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7766                 assert_eq!(events.len(), 1);
7767                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
7768
7769                 // Claim the full MPP payment. Note that we can't use a test utility like
7770                 // claim_funds_along_route because the ordering of the messages causes the second half of the
7771                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
7772                 // lightning messages manually.
7773                 nodes[1].node.claim_funds(payment_preimage);
7774                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
7775                 check_added_monitors!(nodes[1], 2);
7776
7777                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7778                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
7779                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
7780                 check_added_monitors!(nodes[0], 1);
7781                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7782                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
7783                 check_added_monitors!(nodes[1], 1);
7784                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7785                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
7786                 check_added_monitors!(nodes[1], 1);
7787                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7788                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
7789                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
7790                 check_added_monitors!(nodes[0], 1);
7791                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7792                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
7793                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7794                 check_added_monitors!(nodes[0], 1);
7795                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
7796                 check_added_monitors!(nodes[1], 1);
7797                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
7798                 check_added_monitors!(nodes[1], 1);
7799                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7800                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
7801                 check_added_monitors!(nodes[0], 1);
7802
7803                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
7804                 // path's success and a PaymentPathSuccessful event for each path's success.
7805                 let events = nodes[0].node.get_and_clear_pending_events();
7806                 assert_eq!(events.len(), 3);
7807                 match events[0] {
7808                         Event::PaymentSent { payment_id: ref id, payment_preimage: ref preimage, payment_hash: ref hash, .. } => {
7809                                 assert_eq!(Some(payment_id), *id);
7810                                 assert_eq!(payment_preimage, *preimage);
7811                                 assert_eq!(our_payment_hash, *hash);
7812                         },
7813                         _ => panic!("Unexpected event"),
7814                 }
7815                 match events[1] {
7816                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
7817                                 assert_eq!(payment_id, *actual_payment_id);
7818                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
7819                                 assert_eq!(route.paths[0], *path);
7820                         },
7821                         _ => panic!("Unexpected event"),
7822                 }
7823                 match events[2] {
7824                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
7825                                 assert_eq!(payment_id, *actual_payment_id);
7826                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
7827                                 assert_eq!(route.paths[0], *path);
7828                         },
7829                         _ => panic!("Unexpected event"),
7830                 }
7831         }
7832
7833         #[test]
7834         fn test_keysend_dup_payment_hash() {
7835                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
7836                 //      outbound regular payment fails as expected.
7837                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
7838                 //      fails as expected.
7839                 let chanmon_cfgs = create_chanmon_cfgs(2);
7840                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7841                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7842                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7843                 create_announced_chan_between_nodes(&nodes, 0, 1);
7844                 let scorer = test_utils::TestScorer::with_penalty(0);
7845                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7846
7847                 // To start (1), send a regular payment but don't claim it.
7848                 let expected_route = [&nodes[1]];
7849                 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &expected_route, 100_000);
7850
7851                 // Next, attempt a keysend payment and make sure it fails.
7852                 let route_params = RouteParameters {
7853                         payment_params: PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id()),
7854                         final_value_msat: 100_000,
7855                         final_cltv_expiry_delta: TEST_FINAL_CLTV,
7856                 };
7857                 let route = find_route(
7858                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
7859                         None, nodes[0].logger, &scorer, &random_seed_bytes
7860                 ).unwrap();
7861                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), PaymentId(payment_preimage.0)).unwrap();
7862                 check_added_monitors!(nodes[0], 1);
7863                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7864                 assert_eq!(events.len(), 1);
7865                 let ev = events.drain(..).next().unwrap();
7866                 let payment_event = SendEvent::from_event(ev);
7867                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7868                 check_added_monitors!(nodes[1], 0);
7869                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7870                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
7871                 // fails), the second will process the resulting failure and fail the HTLC backward
7872                 expect_pending_htlcs_forwardable!(nodes[1]);
7873                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
7874                 check_added_monitors!(nodes[1], 1);
7875                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7876                 assert!(updates.update_add_htlcs.is_empty());
7877                 assert!(updates.update_fulfill_htlcs.is_empty());
7878                 assert_eq!(updates.update_fail_htlcs.len(), 1);
7879                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7880                 assert!(updates.update_fee.is_none());
7881                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7882                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
7883                 expect_payment_failed!(nodes[0], payment_hash, true);
7884
7885                 // Finally, claim the original payment.
7886                 claim_payment(&nodes[0], &expected_route, payment_preimage);
7887
7888                 // To start (2), send a keysend payment but don't claim it.
7889                 let payment_preimage = PaymentPreimage([42; 32]);
7890                 let route = find_route(
7891                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
7892                         None, nodes[0].logger, &scorer, &random_seed_bytes
7893                 ).unwrap();
7894                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), PaymentId(payment_preimage.0)).unwrap();
7895                 check_added_monitors!(nodes[0], 1);
7896                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7897                 assert_eq!(events.len(), 1);
7898                 let event = events.pop().unwrap();
7899                 let path = vec![&nodes[1]];
7900                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
7901
7902                 // Next, attempt a regular payment and make sure it fails.
7903                 let payment_secret = PaymentSecret([43; 32]);
7904                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
7905                 check_added_monitors!(nodes[0], 1);
7906                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7907                 assert_eq!(events.len(), 1);
7908                 let ev = events.drain(..).next().unwrap();
7909                 let payment_event = SendEvent::from_event(ev);
7910                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7911                 check_added_monitors!(nodes[1], 0);
7912                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7913                 expect_pending_htlcs_forwardable!(nodes[1]);
7914                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
7915                 check_added_monitors!(nodes[1], 1);
7916                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7917                 assert!(updates.update_add_htlcs.is_empty());
7918                 assert!(updates.update_fulfill_htlcs.is_empty());
7919                 assert_eq!(updates.update_fail_htlcs.len(), 1);
7920                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7921                 assert!(updates.update_fee.is_none());
7922                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7923                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
7924                 expect_payment_failed!(nodes[0], payment_hash, true);
7925
7926                 // Finally, succeed the keysend payment.
7927                 claim_payment(&nodes[0], &expected_route, payment_preimage);
7928         }
7929
7930         #[test]
7931         fn test_keysend_hash_mismatch() {
7932                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
7933                 // preimage doesn't match the msg's payment hash.
7934                 let chanmon_cfgs = create_chanmon_cfgs(2);
7935                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7936                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7937                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7938
7939                 let payer_pubkey = nodes[0].node.get_our_node_id();
7940                 let payee_pubkey = nodes[1].node.get_our_node_id();
7941                 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }).unwrap();
7942                 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
7943
7944                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
7945                 let route_params = RouteParameters {
7946                         payment_params: PaymentParameters::for_keysend(payee_pubkey),
7947                         final_value_msat: 10_000,
7948                         final_cltv_expiry_delta: 40,
7949                 };
7950                 let network_graph = nodes[0].network_graph.clone();
7951                 let first_hops = nodes[0].node.list_usable_channels();
7952                 let scorer = test_utils::TestScorer::with_penalty(0);
7953                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7954                 let route = find_route(
7955                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
7956                         nodes[0].logger, &scorer, &random_seed_bytes
7957                 ).unwrap();
7958
7959                 let test_preimage = PaymentPreimage([42; 32]);
7960                 let mismatch_payment_hash = PaymentHash([43; 32]);
7961                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash, None, PaymentId(mismatch_payment_hash.0), &route).unwrap();
7962                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash, &None, Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
7963                 check_added_monitors!(nodes[0], 1);
7964
7965                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7966                 assert_eq!(updates.update_add_htlcs.len(), 1);
7967                 assert!(updates.update_fulfill_htlcs.is_empty());
7968                 assert!(updates.update_fail_htlcs.is_empty());
7969                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7970                 assert!(updates.update_fee.is_none());
7971                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7972
7973                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Payment preimage didn't match payment hash".to_string(), 1);
7974         }
7975
7976         #[test]
7977         fn test_keysend_msg_with_secret_err() {
7978                 // Test that we error as expected if we receive a keysend payment that includes a payment secret.
7979                 let chanmon_cfgs = create_chanmon_cfgs(2);
7980                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7981                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7982                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7983
7984                 let payer_pubkey = nodes[0].node.get_our_node_id();
7985                 let payee_pubkey = nodes[1].node.get_our_node_id();
7986                 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }).unwrap();
7987                 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
7988
7989                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
7990                 let route_params = RouteParameters {
7991                         payment_params: PaymentParameters::for_keysend(payee_pubkey),
7992                         final_value_msat: 10_000,
7993                         final_cltv_expiry_delta: 40,
7994                 };
7995                 let network_graph = nodes[0].network_graph.clone();
7996                 let first_hops = nodes[0].node.list_usable_channels();
7997                 let scorer = test_utils::TestScorer::with_penalty(0);
7998                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7999                 let route = find_route(
8000                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
8001                         nodes[0].logger, &scorer, &random_seed_bytes
8002                 ).unwrap();
8003
8004                 let test_preimage = PaymentPreimage([42; 32]);
8005                 let test_secret = PaymentSecret([43; 32]);
8006                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).into_inner());
8007                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash, Some(test_secret), PaymentId(payment_hash.0), &route).unwrap();
8008                 nodes[0].node.test_send_payment_internal(&route, payment_hash, &Some(test_secret), Some(test_preimage), PaymentId(payment_hash.0), None, session_privs).unwrap();
8009                 check_added_monitors!(nodes[0], 1);
8010
8011                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8012                 assert_eq!(updates.update_add_htlcs.len(), 1);
8013                 assert!(updates.update_fulfill_htlcs.is_empty());
8014                 assert!(updates.update_fail_htlcs.is_empty());
8015                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8016                 assert!(updates.update_fee.is_none());
8017                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8018
8019                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "We don't support MPP keysend payments".to_string(), 1);
8020         }
8021
8022         #[test]
8023         fn test_multi_hop_missing_secret() {
8024                 let chanmon_cfgs = create_chanmon_cfgs(4);
8025                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8026                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8027                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8028
8029                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8030                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8031                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8032                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8033
8034                 // Marshall an MPP route.
8035                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8036                 let path = route.paths[0].clone();
8037                 route.paths.push(path);
8038                 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8039                 route.paths[0][0].short_channel_id = chan_1_id;
8040                 route.paths[0][1].short_channel_id = chan_3_id;
8041                 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8042                 route.paths[1][0].short_channel_id = chan_2_id;
8043                 route.paths[1][1].short_channel_id = chan_4_id;
8044
8045                 match nodes[0].node.send_payment(&route, payment_hash, &None, PaymentId(payment_hash.0)).unwrap_err() {
8046                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
8047                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))                        },
8048                         _ => panic!("unexpected error")
8049                 }
8050         }
8051
8052         #[test]
8053         fn bad_inbound_payment_hash() {
8054                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
8055                 let chanmon_cfgs = create_chanmon_cfgs(2);
8056                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8057                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8058                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8059
8060                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
8061                 let payment_data = msgs::FinalOnionHopData {
8062                         payment_secret,
8063                         total_msat: 100_000,
8064                 };
8065
8066                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
8067                 // payment verification fails as expected.
8068                 let mut bad_payment_hash = payment_hash.clone();
8069                 bad_payment_hash.0[0] += 1;
8070                 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) {
8071                         Ok(_) => panic!("Unexpected ok"),
8072                         Err(()) => {
8073                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment".to_string(), "Failing HTLC with user-generated payment_hash".to_string(), 1);
8074                         }
8075                 }
8076
8077                 // Check that using the original payment hash succeeds.
8078                 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());
8079         }
8080
8081         #[test]
8082         fn test_id_to_peer_coverage() {
8083                 // Test that the `ChannelManager:id_to_peer` contains channels which have been assigned
8084                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
8085                 // the channel is successfully closed.
8086                 let chanmon_cfgs = create_chanmon_cfgs(2);
8087                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8088                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8089                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8090
8091                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
8092                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8093                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
8094                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8095                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
8096
8097                 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
8098                 let channel_id = &tx.txid().into_inner();
8099                 {
8100                         // Ensure that the `id_to_peer` map is empty until either party has received the
8101                         // funding transaction, and have the real `channel_id`.
8102                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
8103                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
8104                 }
8105
8106                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8107                 {
8108                         // Assert that `nodes[0]`'s `id_to_peer` map is populated with the channel as soon as
8109                         // as it has the funding transaction.
8110                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
8111                         assert_eq!(nodes_0_lock.len(), 1);
8112                         assert!(nodes_0_lock.contains_key(channel_id));
8113
8114                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
8115                 }
8116
8117                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8118
8119                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8120                 {
8121                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
8122                         assert_eq!(nodes_0_lock.len(), 1);
8123                         assert!(nodes_0_lock.contains_key(channel_id));
8124
8125                         // Assert that `nodes[1]`'s `id_to_peer` map is populated with the channel as soon as
8126                         // as it has the funding transaction.
8127                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
8128                         assert_eq!(nodes_1_lock.len(), 1);
8129                         assert!(nodes_1_lock.contains_key(channel_id));
8130                 }
8131                 check_added_monitors!(nodes[1], 1);
8132                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8133                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
8134                 check_added_monitors!(nodes[0], 1);
8135                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8136                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8137                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
8138
8139                 nodes[0].node.close_channel(channel_id, &nodes[1].node.get_our_node_id()).unwrap();
8140                 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()));
8141                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
8142                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
8143
8144                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
8145                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
8146                 {
8147                         // Assert that the channel is kept in the `id_to_peer` map for both nodes until the
8148                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
8149                         // fee for the closing transaction has been negotiated and the parties has the other
8150                         // party's signature for the fee negotiated closing transaction.)
8151                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
8152                         assert_eq!(nodes_0_lock.len(), 1);
8153                         assert!(nodes_0_lock.contains_key(channel_id));
8154
8155                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
8156                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
8157                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
8158                         // kept in the `nodes[1]`'s `id_to_peer` map.
8159                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
8160                         assert_eq!(nodes_1_lock.len(), 1);
8161                         assert!(nodes_1_lock.contains_key(channel_id));
8162                 }
8163
8164                 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()));
8165                 {
8166                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
8167                         // therefore has all it needs to fully close the channel (both signatures for the
8168                         // closing transaction).
8169                         // Assert that the channel is removed from `nodes[0]`'s `id_to_peer` map as it can be
8170                         // fully closed by `nodes[0]`.
8171                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
8172
8173                         // Assert that the channel is still in `nodes[1]`'s  `id_to_peer` map, as `nodes[1]`
8174                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
8175                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
8176                         assert_eq!(nodes_1_lock.len(), 1);
8177                         assert!(nodes_1_lock.contains_key(channel_id));
8178                 }
8179
8180                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
8181
8182                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
8183                 {
8184                         // Assert that the channel has now been removed from both parties `id_to_peer` map once
8185                         // they both have everything required to fully close the channel.
8186                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
8187                 }
8188                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
8189
8190                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
8191                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
8192         }
8193
8194         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
8195                 let expected_message = format!("Not connected to node: {}", expected_public_key);
8196                 check_api_misuse_error_message(expected_message, res_err)
8197         }
8198
8199         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
8200                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
8201                 check_api_misuse_error_message(expected_message, res_err)
8202         }
8203
8204         fn check_api_misuse_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
8205                 match res_err {
8206                         Err(APIError::APIMisuseError { err }) => {
8207                                 assert_eq!(err, expected_err_message);
8208                         },
8209                         Ok(_) => panic!("Unexpected Ok"),
8210                         Err(_) => panic!("Unexpected Error"),
8211                 }
8212         }
8213
8214         #[test]
8215         fn test_api_calls_with_unkown_counterparty_node() {
8216                 // Tests that our API functions and message handlers that expects a `counterparty_node_id`
8217                 // as input, behaves as expected if the `counterparty_node_id` is an unkown peer in the
8218                 // `ChannelManager::per_peer_state` map.
8219                 let chanmon_cfg = create_chanmon_cfgs(2);
8220                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8221                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8222                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8223
8224                 // Boilerplate code to produce `open_channel` and `accept_channel` msgs more densly than
8225                 // creating dummy ones.
8226                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
8227                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8228                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
8229                 let accept_channel_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8230
8231                 // Dummy values
8232                 let channel_id = [4; 32];
8233                 let signature = Signature::from(unsafe { FFISignature::new() });
8234                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
8235                 let intercept_id = InterceptId([0; 32]);
8236
8237                 // Dummy msgs
8238                 let funding_created_msg = msgs::FundingCreated {
8239                         temporary_channel_id: open_channel_msg.temporary_channel_id,
8240                         funding_txid: Txid::from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap(),
8241                         funding_output_index: 0,
8242                         signature: signature,
8243                 };
8244
8245                 let funding_signed_msg = msgs::FundingSigned {
8246                         channel_id: channel_id,
8247                         signature: signature,
8248                 };
8249
8250                 let channel_ready_msg = msgs::ChannelReady {
8251                         channel_id: channel_id,
8252                         next_per_commitment_point: unkown_public_key,
8253                         short_channel_id_alias: None,
8254                 };
8255
8256                 let announcement_signatures_msg = msgs::AnnouncementSignatures {
8257                         channel_id: channel_id,
8258                         short_channel_id: 0,
8259                         node_signature: signature,
8260                         bitcoin_signature: signature,
8261                 };
8262
8263                 let channel_reestablish_msg = msgs::ChannelReestablish {
8264                         channel_id: channel_id,
8265                         next_local_commitment_number: 0,
8266                         next_remote_commitment_number: 0,
8267                         data_loss_protect: OptionalField::Absent,
8268                 };
8269
8270                 let closing_signed_msg = msgs::ClosingSigned {
8271                         channel_id: channel_id,
8272                         fee_satoshis: 1000,
8273                         signature: signature,
8274                         fee_range: None,
8275                 };
8276
8277                 let shutdown_msg = msgs::Shutdown {
8278                         channel_id: channel_id,
8279                         scriptpubkey: Script::new(),
8280                 };
8281
8282                 let onion_routing_packet = msgs::OnionPacket {
8283                         version: 255,
8284                         public_key: Ok(unkown_public_key),
8285                         hop_data: [1; 20*65],
8286                         hmac: [2; 32]
8287                 };
8288
8289                 let update_add_htlc_msg = msgs::UpdateAddHTLC {
8290                         channel_id: channel_id,
8291                         htlc_id: 0,
8292                         amount_msat: 1000000,
8293                         payment_hash: PaymentHash([1; 32]),
8294                         cltv_expiry: 821716,
8295                         onion_routing_packet
8296                 };
8297
8298                 let commitment_signed_msg = msgs::CommitmentSigned {
8299                         channel_id: channel_id,
8300                         signature: signature,
8301                         htlc_signatures: Vec::new(),
8302                 };
8303
8304                 let update_fee_msg = msgs::UpdateFee {
8305                         channel_id: channel_id,
8306                         feerate_per_kw: 1000,
8307                 };
8308
8309                 let malformed_update_msg = msgs::UpdateFailMalformedHTLC{
8310                         channel_id: channel_id,
8311                         htlc_id: 0,
8312                         sha256_of_onion: [1; 32],
8313                         failure_code: 0x8000,
8314                 };
8315
8316                 let fulfill_update_msg = msgs::UpdateFulfillHTLC{
8317                         channel_id: channel_id,
8318                         htlc_id: 0,
8319                         payment_preimage: PaymentPreimage([1; 32]),
8320                 };
8321
8322                 let fail_update_msg = msgs::UpdateFailHTLC{
8323                         channel_id: channel_id,
8324                         htlc_id: 0,
8325                         reason: msgs::OnionErrorPacket { data: Vec::new()},
8326                 };
8327
8328                 let revoke_and_ack_msg = msgs::RevokeAndACK {
8329                         channel_id: channel_id,
8330                         per_commitment_secret: [1; 32],
8331                         next_per_commitment_point: unkown_public_key,
8332                 };
8333
8334                 // Test the API functions and message handlers.
8335                 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);
8336
8337                 nodes[1].node.handle_open_channel(&unkown_public_key, &open_channel_msg);
8338
8339                 nodes[0].node.handle_accept_channel(&unkown_public_key, &accept_channel_msg);
8340
8341                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&open_channel_msg.temporary_channel_id, &unkown_public_key, 42), unkown_public_key);
8342
8343                 nodes[1].node.handle_funding_created(&unkown_public_key, &funding_created_msg);
8344
8345                 nodes[0].node.handle_funding_signed(&unkown_public_key, &funding_signed_msg);
8346
8347                 nodes[0].node.handle_channel_ready(&unkown_public_key, &channel_ready_msg);
8348
8349                 nodes[1].node.handle_announcement_signatures(&unkown_public_key, &announcement_signatures_msg);
8350
8351                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
8352
8353                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
8354
8355                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
8356
8357                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
8358
8359                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
8360
8361                 nodes[0].node.handle_shutdown(&unkown_public_key, &shutdown_msg);
8362
8363                 nodes[1].node.handle_closing_signed(&unkown_public_key, &closing_signed_msg);
8364
8365                 nodes[0].node.handle_channel_reestablish(&unkown_public_key, &channel_reestablish_msg);
8366
8367                 nodes[1].node.handle_update_add_htlc(&unkown_public_key, &update_add_htlc_msg);
8368
8369                 nodes[1].node.handle_commitment_signed(&unkown_public_key, &commitment_signed_msg);
8370
8371                 nodes[1].node.handle_update_fail_malformed_htlc(&unkown_public_key, &malformed_update_msg);
8372
8373                 nodes[1].node.handle_update_fail_htlc(&unkown_public_key, &fail_update_msg);
8374
8375                 nodes[1].node.handle_update_fulfill_htlc(&unkown_public_key, &fulfill_update_msg);
8376
8377                 nodes[1].node.handle_revoke_and_ack(&unkown_public_key, &revoke_and_ack_msg);
8378
8379                 nodes[1].node.handle_update_fee(&unkown_public_key, &update_fee_msg);
8380         }
8381
8382         #[cfg(anchors)]
8383         #[test]
8384         fn test_anchors_zero_fee_htlc_tx_fallback() {
8385                 // Tests that if both nodes support anchors, but the remote node does not want to accept
8386                 // anchor channels at the moment, an error it sent to the local node such that it can retry
8387                 // the channel without the anchors feature.
8388                 let chanmon_cfgs = create_chanmon_cfgs(2);
8389                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8390                 let mut anchors_config = test_default_channel_config();
8391                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
8392                 anchors_config.manually_accept_inbound_channels = true;
8393                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
8394                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8395
8396                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None).unwrap();
8397                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8398                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
8399
8400                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
8401                 let events = nodes[1].node.get_and_clear_pending_events();
8402                 match events[0] {
8403                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
8404                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8405                         }
8406                         _ => panic!("Unexpected event"),
8407                 }
8408
8409                 let error_msg = get_err_msg!(nodes[1], nodes[0].node.get_our_node_id());
8410                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
8411
8412                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8413                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
8414
8415                 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8416         }
8417 }
8418
8419 #[cfg(all(any(test, feature = "_test_utils"), feature = "_bench_unstable"))]
8420 pub mod bench {
8421         use crate::chain::Listen;
8422         use crate::chain::chainmonitor::{ChainMonitor, Persist};
8423         use crate::chain::keysinterface::{EntropySource, KeysManager, InMemorySigner};
8424         use crate::ln::channelmanager::{self, BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId};
8425         use crate::ln::functional_test_utils::*;
8426         use crate::ln::msgs::{ChannelMessageHandler, Init};
8427         use crate::routing::gossip::NetworkGraph;
8428         use crate::routing::router::{PaymentParameters, get_route};
8429         use crate::util::test_utils;
8430         use crate::util::config::UserConfig;
8431         use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
8432
8433         use bitcoin::hashes::Hash;
8434         use bitcoin::hashes::sha256::Hash as Sha256;
8435         use bitcoin::{Block, BlockHeader, PackedLockTime, Transaction, TxMerkleNode, TxOut};
8436
8437         use crate::sync::{Arc, Mutex};
8438
8439         use test::Bencher;
8440
8441         struct NodeHolder<'a, P: Persist<InMemorySigner>> {
8442                 node: &'a ChannelManager<
8443                         &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
8444                                 &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
8445                                 &'a test_utils::TestLogger, &'a P>,
8446                         &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
8447                         &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
8448                         &'a test_utils::TestLogger>,
8449         }
8450
8451         #[cfg(test)]
8452         #[bench]
8453         fn bench_sends(bench: &mut Bencher) {
8454                 bench_two_sends(bench, test_utils::TestPersister::new(), test_utils::TestPersister::new());
8455         }
8456
8457         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Bencher, persister_a: P, persister_b: P) {
8458                 // Do a simple benchmark of sending a payment back and forth between two nodes.
8459                 // Note that this is unrealistic as each payment send will require at least two fsync
8460                 // calls per node.
8461                 let network = bitcoin::Network::Testnet;
8462                 let genesis_hash = bitcoin::blockdata::constants::genesis_block(network).header.block_hash();
8463
8464                 let tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
8465                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
8466                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
8467                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(genesis_hash, &logger_a)));
8468
8469                 let mut config: UserConfig = Default::default();
8470                 config.channel_handshake_config.minimum_depth = 1;
8471
8472                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
8473                 let seed_a = [1u8; 32];
8474                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
8475                 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 {
8476                         network,
8477                         best_block: BestBlock::from_genesis(network),
8478                 });
8479                 let node_a_holder = NodeHolder { node: &node_a };
8480
8481                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
8482                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
8483                 let seed_b = [2u8; 32];
8484                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
8485                 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 {
8486                         network,
8487                         best_block: BestBlock::from_genesis(network),
8488                 });
8489                 let node_b_holder = NodeHolder { node: &node_b };
8490
8491                 node_a.peer_connected(&node_b.get_our_node_id(), &Init { features: node_b.init_features(), remote_network_address: None }).unwrap();
8492                 node_b.peer_connected(&node_a.get_our_node_id(), &Init { features: node_a.init_features(), remote_network_address: None }).unwrap();
8493                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
8494                 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()));
8495                 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()));
8496
8497                 let tx;
8498                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
8499                         tx = Transaction { version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
8500                                 value: 8_000_000, script_pubkey: output_script,
8501                         }]};
8502                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
8503                 } else { panic!(); }
8504
8505                 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()));
8506                 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()));
8507
8508                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
8509
8510                 let block = Block {
8511                         header: BlockHeader { version: 0x20000000, prev_blockhash: genesis_hash, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
8512                         txdata: vec![tx],
8513                 };
8514                 Listen::block_connected(&node_a, &block, 1);
8515                 Listen::block_connected(&node_b, &block, 1);
8516
8517                 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()));
8518                 let msg_events = node_a.get_and_clear_pending_msg_events();
8519                 assert_eq!(msg_events.len(), 2);
8520                 match msg_events[0] {
8521                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
8522                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
8523                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
8524                         },
8525                         _ => panic!(),
8526                 }
8527                 match msg_events[1] {
8528                         MessageSendEvent::SendChannelUpdate { .. } => {},
8529                         _ => panic!(),
8530                 }
8531
8532                 let events_a = node_a.get_and_clear_pending_events();
8533                 assert_eq!(events_a.len(), 1);
8534                 match events_a[0] {
8535                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
8536                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
8537                         },
8538                         _ => panic!("Unexpected event"),
8539                 }
8540
8541                 let events_b = node_b.get_and_clear_pending_events();
8542                 assert_eq!(events_b.len(), 1);
8543                 match events_b[0] {
8544                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
8545                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
8546                         },
8547                         _ => panic!("Unexpected event"),
8548                 }
8549
8550                 let dummy_graph = NetworkGraph::new(genesis_hash, &logger_a);
8551
8552                 let mut payment_count: u64 = 0;
8553                 macro_rules! send_payment {
8554                         ($node_a: expr, $node_b: expr) => {
8555                                 let usable_channels = $node_a.list_usable_channels();
8556                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id())
8557                                         .with_features($node_b.invoice_features());
8558                                 let scorer = test_utils::TestScorer::with_penalty(0);
8559                                 let seed = [3u8; 32];
8560                                 let keys_manager = KeysManager::new(&seed, 42, 42);
8561                                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8562                                 let route = get_route(&$node_a.get_our_node_id(), &payment_params, &dummy_graph.read_only(),
8563                                         Some(&usable_channels.iter().map(|r| r).collect::<Vec<_>>()), 10_000, TEST_FINAL_CLTV, &logger_a, &scorer, &random_seed_bytes).unwrap();
8564
8565                                 let mut payment_preimage = PaymentPreimage([0; 32]);
8566                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
8567                                 payment_count += 1;
8568                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
8569                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
8570
8571                                 $node_a.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8572                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
8573                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
8574                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
8575                                 let (raa, cs) = get_revoke_commit_msgs!(NodeHolder { node: &$node_b }, $node_a.get_our_node_id());
8576                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
8577                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
8578                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &get_event_msg!(NodeHolder { node: &$node_a }, MessageSendEvent::SendRevokeAndACK, $node_b.get_our_node_id()));
8579
8580                                 expect_pending_htlcs_forwardable!(NodeHolder { node: &$node_b });
8581                                 expect_payment_claimable!(NodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
8582                                 $node_b.claim_funds(payment_preimage);
8583                                 expect_payment_claimed!(NodeHolder { node: &$node_b }, payment_hash, 10_000);
8584
8585                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
8586                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8587                                                 assert_eq!(node_id, $node_a.get_our_node_id());
8588                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8589                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
8590                                         },
8591                                         _ => panic!("Failed to generate claim event"),
8592                                 }
8593
8594                                 let (raa, cs) = get_revoke_commit_msgs!(NodeHolder { node: &$node_a }, $node_b.get_our_node_id());
8595                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
8596                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
8597                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &get_event_msg!(NodeHolder { node: &$node_b }, MessageSendEvent::SendRevokeAndACK, $node_a.get_our_node_id()));
8598
8599                                 expect_payment_sent!(NodeHolder { node: &$node_a }, payment_preimage);
8600                         }
8601                 }
8602
8603                 bench.iter(|| {
8604                         send_payment!(node_a, node_b);
8605                         send_payment!(node_b, node_a);
8606                 });
8607         }
8608 }