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