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