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