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