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