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