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