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