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