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