]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/channelmanager.rs
Impl Base AMP in the receive pipeline and expose payment_secret
[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 our 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                                 chacha_stream.chacha.process_inline(&mut new_packet_data[read_pos..]);
1018
1019                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1020
1021                                 let blinding_factor = {
1022                                         let mut sha = Sha256::engine();
1023                                         sha.input(&new_pubkey.serialize()[..]);
1024                                         sha.input(&shared_secret);
1025                                         Sha256::from_engine(sha).into_inner()
1026                                 };
1027
1028                                 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor[..]) {
1029                                         Err(e)
1030                                 } else { Ok(new_pubkey) };
1031
1032                                 let outgoing_packet = msgs::OnionPacket {
1033                                         version: 0,
1034                                         public_key,
1035                                         hop_data: new_packet_data,
1036                                         hmac: next_hop_hmac.clone(),
1037                                 };
1038
1039                                 let short_channel_id = match next_hop_data.format {
1040                                         msgs::OnionHopDataFormat::Legacy { short_channel_id } => short_channel_id,
1041                                         msgs::OnionHopDataFormat::NonFinalNode { short_channel_id } => short_channel_id,
1042                                         msgs::OnionHopDataFormat::FinalNode { .. } => {
1043                                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0;0]);
1044                                         },
1045                                 };
1046
1047                                 PendingHTLCStatus::Forward(PendingHTLCInfo {
1048                                         type_data: PendingForwardReceiveHTLCInfo::Forward {
1049                                                 onion_packet: outgoing_packet,
1050                                                 short_channel_id: short_channel_id,
1051                                         },
1052                                         payment_hash: msg.payment_hash.clone(),
1053                                         incoming_shared_secret: shared_secret,
1054                                         amt_to_forward: next_hop_data.amt_to_forward,
1055                                         outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1056                                 })
1057                         };
1058
1059                 channel_state = Some(self.channel_state.lock().unwrap());
1060                 if let &PendingHTLCStatus::Forward(PendingHTLCInfo { ref type_data, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1061                         // If short_channel_id is 0 here, we'll reject them in the body here (which is
1062                         // important as various things later assume we are a ::Receive if short_channel_id is
1063                         // non-0.
1064                         if let &PendingForwardReceiveHTLCInfo::Forward { ref short_channel_id, .. } = type_data {
1065                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1066                                 let forwarding_id = match id_option {
1067                                         None => { // unknown_next_peer
1068                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1069                                         },
1070                                         Some(id) => id.clone(),
1071                                 };
1072                                 if let Some((err, code, chan_update)) = loop {
1073                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1074
1075                                         // Note that we could technically not return an error yet here and just hope
1076                                         // that the connection is reestablished or monitor updated by the time we get
1077                                         // around to doing the actual forward, but better to fail early if we can and
1078                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1079                                         // on a small/per-node/per-channel scale.
1080                                         if !chan.is_live() { // channel_disabled
1081                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1082                                         }
1083                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1084                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1085                                         }
1086                                         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) });
1087                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1088                                                 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())));
1089                                         }
1090                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1091                                                 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())));
1092                                         }
1093                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1094                                         // We want to have at least LATENCY_GRACE_PERIOD_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1095                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS as u32 { // expiry_too_soon
1096                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1097                                         }
1098                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1099                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1100                                         }
1101                                         break None;
1102                                 }
1103                                 {
1104                                         let mut res = Vec::with_capacity(8 + 128);
1105                                         if let Some(chan_update) = chan_update {
1106                                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1107                                                         res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1108                                                 }
1109                                                 else if code == 0x1000 | 13 {
1110                                                         res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1111                                                 }
1112                                                 else if code == 0x1000 | 20 {
1113                                                         res.extend_from_slice(&byte_utils::be16_to_array(chan_update.contents.flags));
1114                                                 }
1115                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1116                                         }
1117                                         return_err!(err, code, &res[..]);
1118                                 }
1119                         }
1120                 }
1121
1122                 (pending_forward_info, channel_state.unwrap())
1123         }
1124
1125         /// only fails if the channel does not yet have an assigned short_id
1126         /// May be called with channel_state already locked!
1127         fn get_channel_update(&self, chan: &Channel<ChanSigner>) -> Result<msgs::ChannelUpdate, LightningError> {
1128                 let short_channel_id = match chan.get_short_channel_id() {
1129                         None => return Err(LightningError{err: "Channel not yet established", action: msgs::ErrorAction::IgnoreError}),
1130                         Some(id) => id,
1131                 };
1132
1133                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1134
1135                 let unsigned = msgs::UnsignedChannelUpdate {
1136                         chain_hash: self.genesis_hash,
1137                         short_channel_id: short_channel_id,
1138                         timestamp: chan.get_channel_update_count(),
1139                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1140                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1141                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1142                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1143                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1144                         excess_data: Vec::new(),
1145                 };
1146
1147                 let msg_hash = Sha256dHash::hash(&unsigned.encode()[..]);
1148                 let sig = self.secp_ctx.sign(&hash_to_message!(&msg_hash[..]), &self.our_network_key);
1149
1150                 Ok(msgs::ChannelUpdate {
1151                         signature: sig,
1152                         contents: unsigned
1153                 })
1154         }
1155
1156         /// Sends a payment along a given route.
1157         ///
1158         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1159         /// fields for more info.
1160         ///
1161         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1162         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1163         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1164         /// specified in the last hop in the route! Thus, you should probably do your own
1165         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1166         /// payment") and prevent double-sends yourself.
1167         ///
1168         /// May generate a SendHTLCs message event on success, which should be relayed.
1169         ///
1170         /// Raises APIError::RoutError when invalid route or forward parameter
1171         /// (cltv_delta, fee, node public key) is specified.
1172         /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1173         /// (including due to previous monitor update failure or new permanent monitor update failure).
1174         /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1175         /// relevant updates.
1176         ///
1177         /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1178         /// and you may wish to retry via a different route immediately.
1179         /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1180         /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1181         /// the payment via a different route unless you intend to pay twice!
1182         ///
1183         /// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
1184         /// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
1185         /// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
1186         /// must not contain multiple paths as otherwise the multipath data cannot be sent.
1187         /// If a payment_secret *is* provided, we assume that the invoice had the basic_mpp feature bit
1188         /// set (either as required or as available).
1189         pub fn send_payment(&self, route: Route, payment_hash: PaymentHash, payment_secret: Option<&[u8; 32]>) -> Result<(), APIError> {
1190                 if route.hops.len() < 1 || route.hops.len() > 20 {
1191                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1192                 }
1193                 let our_node_id = self.get_our_node_id();
1194                 for (idx, hop) in route.hops.iter().enumerate() {
1195                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1196                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1197                         }
1198                 }
1199
1200                 let (session_priv, prng_seed) = self.keys_manager.get_onion_rand();
1201
1202                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1203
1204                 let onion_keys = secp_call!(onion_utils::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1205                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1206                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, payment_secret, cur_height)?;
1207                 if onion_utils::route_size_insane(&onion_payloads) {
1208                         return Err(APIError::RouteError{err: "Route had too large size once"});
1209                 }
1210                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, &payment_hash);
1211
1212                 let _ = self.total_consistency_lock.read().unwrap();
1213
1214                 let mut channel_lock = self.channel_state.lock().unwrap();
1215                 let err: Result<(), _> = loop {
1216
1217                         let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1218                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1219                                 Some(id) => id.clone(),
1220                         };
1221
1222                         let channel_state = &mut *channel_lock;
1223                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1224                                 match {
1225                                         if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1226                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1227                                         }
1228                                         if !chan.get().is_live() {
1229                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1230                                         }
1231                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1232                                                 route: route.clone(),
1233                                                 session_priv: session_priv.clone(),
1234                                                 first_hop_htlc_msat: htlc_msat,
1235                                         }, onion_packet), channel_state, chan)
1236                                 } {
1237                                         Some((update_add, commitment_signed, chan_monitor)) => {
1238                                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1239                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true);
1240                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1241                                                         // that we will resent the commitment update once we unfree monitor
1242                                                         // updating, so we have to take special care that we don't return
1243                                                         // something else in case we will resend later!
1244                                                         return Err(APIError::MonitorUpdateFailed);
1245                                                 }
1246
1247                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1248                                                         node_id: route.hops.first().unwrap().pubkey,
1249                                                         updates: msgs::CommitmentUpdate {
1250                                                                 update_add_htlcs: vec![update_add],
1251                                                                 update_fulfill_htlcs: Vec::new(),
1252                                                                 update_fail_htlcs: Vec::new(),
1253                                                                 update_fail_malformed_htlcs: Vec::new(),
1254                                                                 update_fee: None,
1255                                                                 commitment_signed,
1256                                                         },
1257                                                 });
1258                                         },
1259                                         None => {},
1260                                 }
1261                         } else { unreachable!(); }
1262                         return Ok(());
1263                 };
1264
1265                 match handle_error!(self, err, route.hops.first().unwrap().pubkey, channel_lock) {
1266                         Ok(_) => unreachable!(),
1267                         Err(e) => { Err(APIError::ChannelUnavailable { err: e.err }) }
1268                 }
1269         }
1270
1271         /// Call this upon creation of a funding transaction for the given channel.
1272         ///
1273         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1274         /// or your counterparty can steal your funds!
1275         ///
1276         /// Panics if a funding transaction has already been provided for this channel.
1277         ///
1278         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1279         /// be trivially prevented by using unique funding transaction keys per-channel).
1280         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1281                 let _ = self.total_consistency_lock.read().unwrap();
1282
1283                 let (mut chan, msg, chan_monitor) = {
1284                         let mut channel_state = self.channel_state.lock().unwrap();
1285                         let (res, chan) = match channel_state.by_id.remove(temporary_channel_id) {
1286                                 Some(mut chan) => {
1287                                         (chan.get_outbound_funding_created(funding_txo)
1288                                                 .map_err(|e| if let ChannelError::Close(msg) = e {
1289                                                         MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1290                                                 } else { unreachable!(); })
1291                                         , chan)
1292                                 },
1293                                 None => return
1294                         };
1295                         match handle_error!(self, res, chan.get_their_node_id(), channel_state) {
1296                                 Ok(funding_msg) => {
1297                                         (chan, funding_msg.0, funding_msg.1)
1298                                 },
1299                                 Err(_) => { return; }
1300                         }
1301                 };
1302                 // Because we have exclusive ownership of the channel here we can release the channel_state
1303                 // lock before add_update_monitor
1304                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1305                         match e {
1306                                 ChannelMonitorUpdateErr::PermanentFailure => {
1307                                         {
1308                                                 let mut channel_state = self.channel_state.lock().unwrap();
1309                                                 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) {
1310                                                         Err(_) => { return; },
1311                                                         Ok(()) => unreachable!(),
1312                                                 }
1313                                         }
1314                                 },
1315                                 ChannelMonitorUpdateErr::TemporaryFailure => {
1316                                         // Its completely fine to continue with a FundingCreated until the monitor
1317                                         // update is persisted, as long as we don't generate the FundingBroadcastSafe
1318                                         // until the monitor has been safely persisted (as funding broadcast is not,
1319                                         // in fact, safe).
1320                                         chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
1321                                 },
1322                         }
1323                 }
1324
1325                 let mut channel_state = self.channel_state.lock().unwrap();
1326                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1327                         node_id: chan.get_their_node_id(),
1328                         msg: msg,
1329                 });
1330                 match channel_state.by_id.entry(chan.channel_id()) {
1331                         hash_map::Entry::Occupied(_) => {
1332                                 panic!("Generated duplicate funding txid?");
1333                         },
1334                         hash_map::Entry::Vacant(e) => {
1335                                 e.insert(chan);
1336                         }
1337                 }
1338         }
1339
1340         fn get_announcement_sigs(&self, chan: &Channel<ChanSigner>) -> Option<msgs::AnnouncementSignatures> {
1341                 if !chan.should_announce() { return None }
1342
1343                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1344                         Ok(res) => res,
1345                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1346                 };
1347                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1348                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1349
1350                 Some(msgs::AnnouncementSignatures {
1351                         channel_id: chan.channel_id(),
1352                         short_channel_id: chan.get_short_channel_id().unwrap(),
1353                         node_signature: our_node_sig,
1354                         bitcoin_signature: our_bitcoin_sig,
1355                 })
1356         }
1357
1358         /// Generates a signed node_announcement from the given arguments and creates a
1359         /// BroadcastNodeAnnouncement event.
1360         ///
1361         /// RGB is a node "color" and alias a printable human-readable string to describe this node to
1362         /// humans. They carry no in-protocol meaning.
1363         ///
1364         /// addresses represent the set (possibly empty) of socket addresses on which this node accepts
1365         /// incoming connections.
1366         pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: msgs::NetAddressSet) {
1367                 let _ = self.total_consistency_lock.read().unwrap();
1368
1369                 let announcement = msgs::UnsignedNodeAnnouncement {
1370                         features: NodeFeatures::supported(),
1371                         timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1372                         node_id: self.get_our_node_id(),
1373                         rgb, alias,
1374                         addresses: addresses.to_vec(),
1375                         excess_address_data: Vec::new(),
1376                         excess_data: Vec::new(),
1377                 };
1378                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1379
1380                 let mut channel_state = self.channel_state.lock().unwrap();
1381                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
1382                         msg: msgs::NodeAnnouncement {
1383                                 signature: self.secp_ctx.sign(&msghash, &self.our_network_key),
1384                                 contents: announcement
1385                         },
1386                 });
1387         }
1388
1389         /// Processes HTLCs which are pending waiting on random forward delay.
1390         ///
1391         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
1392         /// Will likely generate further events.
1393         pub fn process_pending_htlc_forwards(&self) {
1394                 let _ = self.total_consistency_lock.read().unwrap();
1395
1396                 let mut new_events = Vec::new();
1397                 let mut failed_forwards = Vec::new();
1398                 let mut handle_errors = Vec::new();
1399                 {
1400                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1401                         let channel_state = &mut *channel_state_lock;
1402
1403                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1404                                 if short_chan_id != 0 {
1405                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1406                                                 Some(chan_id) => chan_id.clone(),
1407                                                 None => {
1408                                                         failed_forwards.reserve(pending_forwards.len());
1409                                                         for forward_info in pending_forwards.drain(..) {
1410                                                                 match forward_info {
1411                                                                         HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info } => {
1412                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1413                                                                                         short_channel_id: prev_short_channel_id,
1414                                                                                         htlc_id: prev_htlc_id,
1415                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1416                                                                                 });
1417                                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash,
1418                                                                                         HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: Vec::new() }
1419                                                                                 ));
1420                                                                         },
1421                                                                         HTLCForwardInfo::FailHTLC { .. } => {
1422                                                                                 // Channel went away before we could fail it. This implies
1423                                                                                 // the channel is now on chain and our counterparty is
1424                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
1425                                                                                 // problem, not ours.
1426                                                                         }
1427                                                                 }
1428                                                         }
1429                                                         continue;
1430                                                 }
1431                                         };
1432                                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(forward_chan_id) {
1433                                                 let mut add_htlc_msgs = Vec::new();
1434                                                 let mut fail_htlc_msgs = Vec::new();
1435                                                 for forward_info in pending_forwards.drain(..) {
1436                                                         match forward_info {
1437                                                                 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1438                                                                                 type_data: PendingForwardReceiveHTLCInfo::Forward {
1439                                                                                         onion_packet, ..
1440                                                                                 }, incoming_shared_secret, payment_hash, amt_to_forward, outgoing_cltv_value }, } => {
1441                                                                         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);
1442                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1443                                                                                 short_channel_id: prev_short_channel_id,
1444                                                                                 htlc_id: prev_htlc_id,
1445                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
1446                                                                         });
1447                                                                         match chan.get_mut().send_htlc(amt_to_forward, payment_hash, outgoing_cltv_value, htlc_source.clone(), onion_packet) {
1448                                                                                 Err(e) => {
1449                                                                                         if let ChannelError::Ignore(msg) = e {
1450                                                                                                 log_trace!(self, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
1451                                                                                         } else {
1452                                                                                                 panic!("Stated return value requirements in send_htlc() were not met");
1453                                                                                         }
1454                                                                                         let chan_update = self.get_channel_update(chan.get()).unwrap();
1455                                                                                         failed_forwards.push((htlc_source, payment_hash,
1456                                                                                                 HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.encode_with_len() }
1457                                                                                         ));
1458                                                                                         continue;
1459                                                                                 },
1460                                                                                 Ok(update_add) => {
1461                                                                                         match update_add {
1462                                                                                                 Some(msg) => { add_htlc_msgs.push(msg); },
1463                                                                                                 None => {
1464                                                                                                         // Nothing to do here...we're waiting on a remote
1465                                                                                                         // revoke_and_ack before we can add anymore HTLCs. The Channel
1466                                                                                                         // will automatically handle building the update_add_htlc and
1467                                                                                                         // commitment_signed messages when we can.
1468                                                                                                         // TODO: Do some kind of timer to set the channel as !is_live()
1469                                                                                                         // as we don't really want others relying on us relaying through
1470                                                                                                         // this channel currently :/.
1471                                                                                                 }
1472                                                                                         }
1473                                                                                 }
1474                                                                         }
1475                                                                 },
1476                                                                 HTLCForwardInfo::AddHTLC { .. } => {
1477                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
1478                                                                 },
1479                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
1480                                                                         log_trace!(self, "Failing HTLC back to channel with short id {} after delay", short_chan_id);
1481                                                                         match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet) {
1482                                                                                 Err(e) => {
1483                                                                                         if let ChannelError::Ignore(msg) = e {
1484                                                                                                 log_trace!(self, "Failed to fail backwards to short_id {}: {}", short_chan_id, msg);
1485                                                                                         } else {
1486                                                                                                 panic!("Stated return value requirements in get_update_fail_htlc() were not met");
1487                                                                                         }
1488                                                                                         // fail-backs are best-effort, we probably already have one
1489                                                                                         // pending, and if not that's OK, if not, the channel is on
1490                                                                                         // the chain and sending the HTLC-Timeout is their problem.
1491                                                                                         continue;
1492                                                                                 },
1493                                                                                 Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
1494                                                                                 Ok(None) => {
1495                                                                                         // Nothing to do here...we're waiting on a remote
1496                                                                                         // revoke_and_ack before we can update the commitment
1497                                                                                         // transaction. The Channel will automatically handle
1498                                                                                         // building the update_fail_htlc and commitment_signed
1499                                                                                         // messages when we can.
1500                                                                                         // We don't need any kind of timer here as they should fail
1501                                                                                         // the channel onto the chain if they can't get our
1502                                                                                         // update_fail_htlc in time, it's not our problem.
1503                                                                                 }
1504                                                                         }
1505                                                                 },
1506                                                         }
1507                                                 }
1508
1509                                                 if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
1510                                                         let (commitment_msg, monitor) = match chan.get_mut().send_commitment() {
1511                                                                 Ok(res) => res,
1512                                                                 Err(e) => {
1513                                                                         // We surely failed send_commitment due to bad keys, in that case
1514                                                                         // close channel and then send error message to peer.
1515                                                                         let their_node_id = chan.get().get_their_node_id();
1516                                                                         let err: Result<(), _>  = match e {
1517                                                                                 ChannelError::Ignore(_) => {
1518                                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1519                                                                                 },
1520                                                                                 ChannelError::Close(msg) => {
1521                                                                                         log_trace!(self, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
1522                                                                                         let (channel_id, mut channel) = chan.remove_entry();
1523                                                                                         if let Some(short_id) = channel.get_short_channel_id() {
1524                                                                                                 channel_state.short_to_id.remove(&short_id);
1525                                                                                         }
1526                                                                                         Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, channel.force_shutdown(), self.get_channel_update(&channel).ok()))
1527                                                                                 },
1528                                                                                 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"); }
1529                                                                         };
1530                                                                         match handle_error!(self, err, their_node_id, channel_state) {
1531                                                                                 Ok(_) => unreachable!(),
1532                                                                                 Err(_) => { continue; },
1533                                                                         }
1534                                                                 }
1535                                                         };
1536                                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1537                                                                 handle_errors.push((chan.get().get_their_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
1538                                                                 continue;
1539                                                         }
1540                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1541                                                                 node_id: chan.get().get_their_node_id(),
1542                                                                 updates: msgs::CommitmentUpdate {
1543                                                                         update_add_htlcs: add_htlc_msgs,
1544                                                                         update_fulfill_htlcs: Vec::new(),
1545                                                                         update_fail_htlcs: fail_htlc_msgs,
1546                                                                         update_fail_malformed_htlcs: Vec::new(),
1547                                                                         update_fee: None,
1548                                                                         commitment_signed: commitment_msg,
1549                                                                 },
1550                                                         });
1551                                                 }
1552                                         } else {
1553                                                 unreachable!();
1554                                         }
1555                                 } else {
1556                                         for forward_info in pending_forwards.drain(..) {
1557                                                 match forward_info {
1558                                                         HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1559                                                                         type_data: PendingForwardReceiveHTLCInfo::Receive { payment_data },
1560                                                                         incoming_shared_secret, payment_hash, amt_to_forward, .. }, } => {
1561                                                                 let prev_hop_data = HTLCPreviousHopData {
1562                                                                         short_channel_id: prev_short_channel_id,
1563                                                                         htlc_id: prev_htlc_id,
1564                                                                         incoming_packet_shared_secret: incoming_shared_secret,
1565                                                                 };
1566
1567                                                                 let mut total_value = 0;
1568                                                                 let htlcs = channel_state.claimable_htlcs.entry((payment_hash, if let &Some(ref data) = &payment_data {
1569                                                                         Some(data.payment_secret.clone()) } else { None }))
1570                                                                         .or_insert(Vec::new());
1571                                                                 htlcs.push(ClaimableHTLC {
1572                                                                         src: prev_hop_data,
1573                                                                         value: amt_to_forward,
1574                                                                         payment_data: payment_data.clone(),
1575                                                                 });
1576                                                                 if let &Some(ref data) = &payment_data {
1577                                                                         for htlc in htlcs.iter() {
1578                                                                                 total_value += htlc.value;
1579                                                                                 if htlc.payment_data.as_ref().unwrap().total_msat != data.total_msat {
1580                                                                                         total_value = msgs::MAX_VALUE_MSAT;
1581                                                                                 }
1582                                                                                 if total_value >= msgs::MAX_VALUE_MSAT { break; }
1583                                                                         }
1584                                                                         if total_value >= msgs::MAX_VALUE_MSAT {
1585                                                                                 for htlc in htlcs.iter() {
1586                                                                                         failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
1587                                                                                                         short_channel_id: htlc.src.short_channel_id,
1588                                                                                                         htlc_id: htlc.src.htlc_id,
1589                                                                                                         incoming_packet_shared_secret: htlc.src.incoming_packet_shared_secret,
1590                                                                                                 }), payment_hash,
1591                                                                                                 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(htlc.value).to_vec() }
1592                                                                                         ));
1593                                                                                 }
1594                                                                         } else if total_value >= data.total_msat {
1595                                                                                 new_events.push(events::Event::PaymentReceived {
1596                                                                                         payment_hash: payment_hash,
1597                                                                                         payment_secret: Some(data.payment_secret),
1598                                                                                         amt: total_value,
1599                                                                                 });
1600                                                                         }
1601                                                                 } else {
1602                                                                         new_events.push(events::Event::PaymentReceived {
1603                                                                                 payment_hash: payment_hash,
1604                                                                                 payment_secret: None,
1605                                                                                 amt: amt_to_forward,
1606                                                                         });
1607                                                                 }
1608                                                         },
1609                                                         HTLCForwardInfo::AddHTLC { .. } => {
1610                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
1611                                                         },
1612                                                         HTLCForwardInfo::FailHTLC { .. } => {
1613                                                                 panic!("Got pending fail of our own HTLC");
1614                                                         }
1615                                                 }
1616                                         }
1617                                 }
1618                         }
1619                 }
1620
1621                 for (htlc_source, payment_hash, failure_reason) in failed_forwards.drain(..) {
1622                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, failure_reason);
1623                 }
1624
1625                 if handle_errors.len() > 0 {
1626                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1627                         for (their_node_id, err) in handle_errors.drain(..) {
1628                                 let _ = handle_error!(self, err, their_node_id, channel_state_lock);
1629                         }
1630                 }
1631
1632                 if new_events.is_empty() { return }
1633                 let mut events = self.pending_events.lock().unwrap();
1634                 events.append(&mut new_events);
1635         }
1636
1637         /// If a peer is disconnected we mark any channels with that peer as 'disabled'.
1638         /// After some time, if channels are still disabled we need to broadcast a ChannelUpdate
1639         /// to inform the network about the uselessness of these channels.
1640         ///
1641         /// This method handles all the details, and must be called roughly once per minute.
1642         pub fn timer_chan_freshness_every_min(&self) {
1643                 let _ = self.total_consistency_lock.read().unwrap();
1644                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1645                 let channel_state = &mut *channel_state_lock;
1646                 for (_, chan) in channel_state.by_id.iter_mut() {
1647                         if chan.is_disabled_staged() && !chan.is_live() {
1648                                 if let Ok(update) = self.get_channel_update(&chan) {
1649                                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1650                                                 msg: update
1651                                         });
1652                                 }
1653                                 chan.to_fresh();
1654                         } else if chan.is_disabled_staged() && chan.is_live() {
1655                                 chan.to_fresh();
1656                         } else if chan.is_disabled_marked() {
1657                                 chan.to_disabled_staged();
1658                         }
1659                 }
1660         }
1661
1662         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1663         /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
1664         /// along the path (including in our own channel on which we received it).
1665         /// Returns false if no payment was found to fail backwards, true if the process of failing the
1666         /// HTLC backwards has been started.
1667         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, payment_secret: &Option<[u8; 32]>) -> bool {
1668                 let _ = self.total_consistency_lock.read().unwrap();
1669
1670                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1671                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(*payment_hash, *payment_secret));
1672                 if let Some(mut sources) = removed_source {
1673                         for htlc in sources.drain(..) {
1674                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1675                                 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1676                                                 HTLCSource::PreviousHopData(htlc.src), payment_hash,
1677                                                 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(htlc.value).to_vec() });
1678                         }
1679                         true
1680                 } else { false }
1681         }
1682
1683         /// Fails an HTLC backwards to the sender of it to us.
1684         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1685         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1686         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1687         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1688         /// still-available channels.
1689         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<ChanSigner>>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1690                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
1691                 //identify whether we sent it or not based on the (I presume) very different runtime
1692                 //between the branches here. We should make this async and move it into the forward HTLCs
1693                 //timer handling.
1694                 match source {
1695                         HTLCSource::OutboundRoute { ref route, .. } => {
1696                                 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1697                                 mem::drop(channel_state_lock);
1698                                 match &onion_error {
1699                                         &HTLCFailReason::LightningError { ref err } => {
1700 #[cfg(test)]
1701                                                 let (channel_update, payment_retryable, onion_error_code) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
1702 #[cfg(not(test))]
1703                                                 let (channel_update, payment_retryable, _) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
1704                                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1705                                                 // process_onion_failure we should close that channel as it implies our
1706                                                 // next-hop is needlessly blaming us!
1707                                                 if let Some(update) = channel_update {
1708                                                         self.channel_state.lock().unwrap().pending_msg_events.push(
1709                                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1710                                                                         update,
1711                                                                 }
1712                                                         );
1713                                                 }
1714                                                 self.pending_events.lock().unwrap().push(
1715                                                         events::Event::PaymentFailed {
1716                                                                 payment_hash: payment_hash.clone(),
1717                                                                 rejected_by_dest: !payment_retryable,
1718 #[cfg(test)]
1719                                                                 error_code: onion_error_code
1720                                                         }
1721                                                 );
1722                                         },
1723                                         &HTLCFailReason::Reason {
1724 #[cfg(test)]
1725                                                         ref failure_code,
1726                                                         .. } => {
1727                                                 // we get a fail_malformed_htlc from the first hop
1728                                                 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1729                                                 // failures here, but that would be insufficient as Router::get_route
1730                                                 // generally ignores its view of our own channels as we provide them via
1731                                                 // ChannelDetails.
1732                                                 // TODO: For non-temporary failures, we really should be closing the
1733                                                 // channel here as we apparently can't relay through them anyway.
1734                                                 self.pending_events.lock().unwrap().push(
1735                                                         events::Event::PaymentFailed {
1736                                                                 payment_hash: payment_hash.clone(),
1737                                                                 rejected_by_dest: route.hops.len() == 1,
1738 #[cfg(test)]
1739                                                                 error_code: Some(*failure_code),
1740                                                         }
1741                                                 );
1742                                         }
1743                                 }
1744                         },
1745                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1746                                 let err_packet = match onion_error {
1747                                         HTLCFailReason::Reason { failure_code, data } => {
1748                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1749                                                 let packet = onion_utils::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1750                                                 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1751                                         },
1752                                         HTLCFailReason::LightningError { err } => {
1753                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built LightningError", log_bytes!(payment_hash.0));
1754                                                 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1755                                         }
1756                                 };
1757
1758                                 let mut forward_event = None;
1759                                 if channel_state_lock.forward_htlcs.is_empty() {
1760                                         forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
1761                                 }
1762                                 match channel_state_lock.forward_htlcs.entry(short_channel_id) {
1763                                         hash_map::Entry::Occupied(mut entry) => {
1764                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id, err_packet });
1765                                         },
1766                                         hash_map::Entry::Vacant(entry) => {
1767                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id, err_packet }));
1768                                         }
1769                                 }
1770                                 mem::drop(channel_state_lock);
1771                                 if let Some(time) = forward_event {
1772                                         let mut pending_events = self.pending_events.lock().unwrap();
1773                                         pending_events.push(events::Event::PendingHTLCsForwardable {
1774                                                 time_forwardable: time
1775                                         });
1776                                 }
1777                         },
1778                 }
1779         }
1780
1781         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1782         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1783         /// should probably kick the net layer to go send messages if this returns true!
1784         ///
1785         /// You must specify the expected amounts for this HTLC, and we will only claim HTLCs
1786         /// available within a few percent of the expected amount. This is critical for several
1787         /// reasons : a) it avoids providing senders with `proof-of-payment` (in the form of the
1788         /// payment_preimage without having provided the full value and b) it avoids certain
1789         /// privacy-breaking recipient-probing attacks which may reveal payment activity to
1790         /// motivated attackers.
1791         ///
1792         /// May panic if called except in response to a PaymentReceived event.
1793         pub fn claim_funds(&self, payment_preimage: PaymentPreimage, payment_secret: &Option<[u8; 32]>, expected_amount: u64) -> bool {
1794                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1795
1796                 let _ = self.total_consistency_lock.read().unwrap();
1797
1798                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1799                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(payment_hash, *payment_secret));
1800                 if let Some(mut sources) = removed_source {
1801                         for htlc in sources.drain(..) {
1802                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1803                                 if htlc.value < expected_amount || htlc.value > expected_amount * 2 {
1804                                         let mut htlc_msat_data = byte_utils::be64_to_array(htlc.value).to_vec();
1805                                         let mut height_data = byte_utils::be32_to_array(self.latest_block_height.load(Ordering::Acquire) as u32).to_vec();
1806                                         htlc_msat_data.append(&mut height_data);
1807                                         self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1808                                                                          HTLCSource::PreviousHopData(htlc.src), &payment_hash,
1809                                                                          HTLCFailReason::Reason { failure_code: 0x4000|15, data: htlc_msat_data });
1810                                 } else {
1811                                         self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc.src), payment_preimage);
1812                                 }
1813                         }
1814                         true
1815                 } else { false }
1816         }
1817         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<ChanSigner>>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1818                 let (their_node_id, err) = loop {
1819                         match source {
1820                                 HTLCSource::OutboundRoute { .. } => {
1821                                         mem::drop(channel_state_lock);
1822                                         let mut pending_events = self.pending_events.lock().unwrap();
1823                                         pending_events.push(events::Event::PaymentSent {
1824                                                 payment_preimage
1825                                         });
1826                                 },
1827                                 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1828                                         //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1829                                         let channel_state = &mut *channel_state_lock;
1830
1831                                         let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1832                                                 Some(chan_id) => chan_id.clone(),
1833                                                 None => {
1834                                                         // TODO: There is probably a channel manager somewhere that needs to
1835                                                         // learn the preimage as the channel already hit the chain and that's
1836                                                         // why it's missing.
1837                                                         return
1838                                                 }
1839                                         };
1840
1841                                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(chan_id) {
1842                                                 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
1843                                                 match chan.get_mut().get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1844                                                         Ok((msgs, monitor_option)) => {
1845                                                                 if let Some(chan_monitor) = monitor_option {
1846                                                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1847                                                                                 if was_frozen_for_monitor {
1848                                                                                         assert!(msgs.is_none());
1849                                                                                 } else {
1850                                                                                         break (chan.get().get_their_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, msgs.is_some()));
1851                                                                                 }
1852                                                                         }
1853                                                                 }
1854                                                                 if let Some((msg, commitment_signed)) = msgs {
1855                                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1856                                                                                 node_id: chan.get().get_their_node_id(),
1857                                                                                 updates: msgs::CommitmentUpdate {
1858                                                                                         update_add_htlcs: Vec::new(),
1859                                                                                         update_fulfill_htlcs: vec![msg],
1860                                                                                         update_fail_htlcs: Vec::new(),
1861                                                                                         update_fail_malformed_htlcs: Vec::new(),
1862                                                                                         update_fee: None,
1863                                                                                         commitment_signed,
1864                                                                                 }
1865                                                                         });
1866                                                                 }
1867                                                         },
1868                                                         Err(_e) => {
1869                                                                 // TODO: There is probably a channel manager somewhere that needs to
1870                                                                 // learn the preimage as the channel may be about to hit the chain.
1871                                                                 //TODO: Do something with e?
1872                                                                 return
1873                                                         },
1874                                                 }
1875                                         } else { unreachable!(); }
1876                                 },
1877                         }
1878                         return;
1879                 };
1880
1881                 let _ = handle_error!(self, err, their_node_id, channel_state_lock);
1882         }
1883
1884         /// Gets the node_id held by this ChannelManager
1885         pub fn get_our_node_id(&self) -> PublicKey {
1886                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1887         }
1888
1889         /// Used to restore channels to normal operation after a
1890         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1891         /// operation.
1892         pub fn test_restore_channel_monitor(&self) {
1893                 let mut close_results = Vec::new();
1894                 let mut htlc_forwards = Vec::new();
1895                 let mut htlc_failures = Vec::new();
1896                 let mut pending_events = Vec::new();
1897                 let _ = self.total_consistency_lock.read().unwrap();
1898
1899                 {
1900                         let mut channel_lock = self.channel_state.lock().unwrap();
1901                         let channel_state = &mut *channel_lock;
1902                         let short_to_id = &mut channel_state.short_to_id;
1903                         let pending_msg_events = &mut channel_state.pending_msg_events;
1904                         channel_state.by_id.retain(|_, channel| {
1905                                 if channel.is_awaiting_monitor_update() {
1906                                         let chan_monitor = channel.channel_monitor().clone();
1907                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1908                                                 match e {
1909                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1910                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1911                                                                 // backwards when a monitor update failed. We should make sure
1912                                                                 // knowledge of those gets moved into the appropriate in-memory
1913                                                                 // ChannelMonitor and they get failed backwards once we get
1914                                                                 // on-chain confirmations.
1915                                                                 // Note I think #198 addresses this, so once it's merged a test
1916                                                                 // should be written.
1917                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1918                                                                         short_to_id.remove(&short_id);
1919                                                                 }
1920                                                                 close_results.push(channel.force_shutdown());
1921                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1922                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1923                                                                                 msg: update
1924                                                                         });
1925                                                                 }
1926                                                                 false
1927                                                         },
1928                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1929                                                 }
1930                                         } else {
1931                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures, needs_broadcast_safe, funding_locked) = channel.monitor_updating_restored();
1932                                                 if !pending_forwards.is_empty() {
1933                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1934                                                 }
1935                                                 htlc_failures.append(&mut pending_failures);
1936
1937                                                 macro_rules! handle_cs { () => {
1938                                                         if let Some(update) = commitment_update {
1939                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1940                                                                         node_id: channel.get_their_node_id(),
1941                                                                         updates: update,
1942                                                                 });
1943                                                         }
1944                                                 } }
1945                                                 macro_rules! handle_raa { () => {
1946                                                         if let Some(revoke_and_ack) = raa {
1947                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1948                                                                         node_id: channel.get_their_node_id(),
1949                                                                         msg: revoke_and_ack,
1950                                                                 });
1951                                                         }
1952                                                 } }
1953                                                 match order {
1954                                                         RAACommitmentOrder::CommitmentFirst => {
1955                                                                 handle_cs!();
1956                                                                 handle_raa!();
1957                                                         },
1958                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1959                                                                 handle_raa!();
1960                                                                 handle_cs!();
1961                                                         },
1962                                                 }
1963                                                 if needs_broadcast_safe {
1964                                                         pending_events.push(events::Event::FundingBroadcastSafe {
1965                                                                 funding_txo: channel.get_funding_txo().unwrap(),
1966                                                                 user_channel_id: channel.get_user_id(),
1967                                                         });
1968                                                 }
1969                                                 if let Some(msg) = funding_locked {
1970                                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
1971                                                                 node_id: channel.get_their_node_id(),
1972                                                                 msg,
1973                                                         });
1974                                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
1975                                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1976                                                                         node_id: channel.get_their_node_id(),
1977                                                                         msg: announcement_sigs,
1978                                                                 });
1979                                                         }
1980                                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
1981                                                 }
1982                                                 true
1983                                         }
1984                                 } else { true }
1985                         });
1986                 }
1987
1988                 self.pending_events.lock().unwrap().append(&mut pending_events);
1989
1990                 for failure in htlc_failures.drain(..) {
1991                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1992                 }
1993                 self.forward_htlcs(&mut htlc_forwards[..]);
1994
1995                 for res in close_results.drain(..) {
1996                         self.finish_force_close_channel(res);
1997                 }
1998         }
1999
2000         fn internal_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
2001                 if msg.chain_hash != self.genesis_hash {
2002                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
2003                 }
2004
2005                 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)
2006                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
2007                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2008                 let channel_state = &mut *channel_state_lock;
2009                 match channel_state.by_id.entry(channel.channel_id()) {
2010                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
2011                         hash_map::Entry::Vacant(entry) => {
2012                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
2013                                         node_id: their_node_id.clone(),
2014                                         msg: channel.get_accept_channel(),
2015                                 });
2016                                 entry.insert(channel);
2017                         }
2018                 }
2019                 Ok(())
2020         }
2021
2022         fn internal_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
2023                 let (value, output_script, user_id) = {
2024                         let mut channel_lock = self.channel_state.lock().unwrap();
2025                         let channel_state = &mut *channel_lock;
2026                         match channel_state.by_id.entry(msg.temporary_channel_id) {
2027                                 hash_map::Entry::Occupied(mut chan) => {
2028                                         if chan.get().get_their_node_id() != *their_node_id {
2029                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
2030                                         }
2031                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration, their_features), channel_state, chan);
2032                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
2033                                 },
2034                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
2035                         }
2036                 };
2037                 let mut pending_events = self.pending_events.lock().unwrap();
2038                 pending_events.push(events::Event::FundingGenerationReady {
2039                         temporary_channel_id: msg.temporary_channel_id,
2040                         channel_value_satoshis: value,
2041                         output_script: output_script,
2042                         user_channel_id: user_id,
2043                 });
2044                 Ok(())
2045         }
2046
2047         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
2048                 let ((funding_msg, monitor_update), mut chan) = {
2049                         let mut channel_lock = self.channel_state.lock().unwrap();
2050                         let channel_state = &mut *channel_lock;
2051                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
2052                                 hash_map::Entry::Occupied(mut chan) => {
2053                                         if chan.get().get_their_node_id() != *their_node_id {
2054                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
2055                                         }
2056                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
2057                                 },
2058                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
2059                         }
2060                 };
2061                 // Because we have exclusive ownership of the channel here we can release the channel_state
2062                 // lock before add_update_monitor
2063                 if let Err(e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
2064                         match e {
2065                                 ChannelMonitorUpdateErr::PermanentFailure => {
2066                                         // Note that we reply with the new channel_id in error messages if we gave up on the
2067                                         // channel, not the temporary_channel_id. This is compatible with ourselves, but the
2068                                         // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
2069                                         // any messages referencing a previously-closed channel anyway.
2070                                         return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", funding_msg.channel_id, chan.force_shutdown(), None));
2071                                 },
2072                                 ChannelMonitorUpdateErr::TemporaryFailure => {
2073                                         // There's no problem signing a counterparty's funding transaction if our monitor
2074                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
2075                                         // accepted payment from yet. We do, however, need to wait to send our funding_locked
2076                                         // until we have persisted our monitor.
2077                                         chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
2078                                 },
2079                         }
2080                 }
2081                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2082                 let channel_state = &mut *channel_state_lock;
2083                 match channel_state.by_id.entry(funding_msg.channel_id) {
2084                         hash_map::Entry::Occupied(_) => {
2085                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
2086                         },
2087                         hash_map::Entry::Vacant(e) => {
2088                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
2089                                         node_id: their_node_id.clone(),
2090                                         msg: funding_msg,
2091                                 });
2092                                 e.insert(chan);
2093                         }
2094                 }
2095                 Ok(())
2096         }
2097
2098         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
2099                 let (funding_txo, user_id) = {
2100                         let mut channel_lock = self.channel_state.lock().unwrap();
2101                         let channel_state = &mut *channel_lock;
2102                         match channel_state.by_id.entry(msg.channel_id) {
2103                                 hash_map::Entry::Occupied(mut chan) => {
2104                                         if chan.get().get_their_node_id() != *their_node_id {
2105                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2106                                         }
2107                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
2108                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2109                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
2110                                         }
2111                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
2112                                 },
2113                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2114                         }
2115                 };
2116                 let mut pending_events = self.pending_events.lock().unwrap();
2117                 pending_events.push(events::Event::FundingBroadcastSafe {
2118                         funding_txo: funding_txo,
2119                         user_channel_id: user_id,
2120                 });
2121                 Ok(())
2122         }
2123
2124         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
2125                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2126                 let channel_state = &mut *channel_state_lock;
2127                 match channel_state.by_id.entry(msg.channel_id) {
2128                         hash_map::Entry::Occupied(mut chan) => {
2129                                 if chan.get().get_their_node_id() != *their_node_id {
2130                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2131                                 }
2132                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
2133                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
2134                                         // If we see locking block before receiving remote funding_locked, we broadcast our
2135                                         // announcement_sigs at remote funding_locked reception. If we receive remote
2136                                         // funding_locked before seeing locking block, we broadcast our announcement_sigs at locking
2137                                         // block connection. We should guanrantee to broadcast announcement_sigs to our peer whatever
2138                                         // the order of the events but our peer may not receive it due to disconnection. The specs
2139                                         // lacking an acknowledgement for announcement_sigs we may have to re-send them at peer
2140                                         // connection in the future if simultaneous misses by both peers due to network/hardware
2141                                         // failures is an issue. Note, to achieve its goal, only one of the announcement_sigs needs
2142                                         // to be received, from then sigs are going to be flood to the whole network.
2143                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2144                                                 node_id: their_node_id.clone(),
2145                                                 msg: announcement_sigs,
2146                                         });
2147                                 }
2148                                 Ok(())
2149                         },
2150                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2151                 }
2152         }
2153
2154         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
2155                 let (mut dropped_htlcs, chan_option) = {
2156                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2157                         let channel_state = &mut *channel_state_lock;
2158
2159                         match channel_state.by_id.entry(msg.channel_id.clone()) {
2160                                 hash_map::Entry::Occupied(mut chan_entry) => {
2161                                         if chan_entry.get().get_their_node_id() != *their_node_id {
2162                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2163                                         }
2164                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
2165                                         if let Some(msg) = shutdown {
2166                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2167                                                         node_id: their_node_id.clone(),
2168                                                         msg,
2169                                                 });
2170                                         }
2171                                         if let Some(msg) = closing_signed {
2172                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2173                                                         node_id: their_node_id.clone(),
2174                                                         msg,
2175                                                 });
2176                                         }
2177                                         if chan_entry.get().is_shutdown() {
2178                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2179                                                         channel_state.short_to_id.remove(&short_id);
2180                                                 }
2181                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
2182                                         } else { (dropped_htlcs, None) }
2183                                 },
2184                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2185                         }
2186                 };
2187                 for htlc_source in dropped_htlcs.drain(..) {
2188                         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() });
2189                 }
2190                 if let Some(chan) = chan_option {
2191                         if let Ok(update) = self.get_channel_update(&chan) {
2192                                 let mut channel_state = self.channel_state.lock().unwrap();
2193                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2194                                         msg: update
2195                                 });
2196                         }
2197                 }
2198                 Ok(())
2199         }
2200
2201         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
2202                 let (tx, chan_option) = {
2203                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2204                         let channel_state = &mut *channel_state_lock;
2205                         match channel_state.by_id.entry(msg.channel_id.clone()) {
2206                                 hash_map::Entry::Occupied(mut chan_entry) => {
2207                                         if chan_entry.get().get_their_node_id() != *their_node_id {
2208                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2209                                         }
2210                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
2211                                         if let Some(msg) = closing_signed {
2212                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2213                                                         node_id: their_node_id.clone(),
2214                                                         msg,
2215                                                 });
2216                                         }
2217                                         if tx.is_some() {
2218                                                 // We're done with this channel, we've got a signed closing transaction and
2219                                                 // will send the closing_signed back to the remote peer upon return. This
2220                                                 // also implies there are no pending HTLCs left on the channel, so we can
2221                                                 // fully delete it from tracking (the channel monitor is still around to
2222                                                 // watch for old state broadcasts)!
2223                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2224                                                         channel_state.short_to_id.remove(&short_id);
2225                                                 }
2226                                                 (tx, Some(chan_entry.remove_entry().1))
2227                                         } else { (tx, None) }
2228                                 },
2229                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2230                         }
2231                 };
2232                 if let Some(broadcast_tx) = tx {
2233                         log_trace!(self, "Broadcast onchain {}", log_tx!(broadcast_tx));
2234                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2235                 }
2236                 if let Some(chan) = chan_option {
2237                         if let Ok(update) = self.get_channel_update(&chan) {
2238                                 let mut channel_state = self.channel_state.lock().unwrap();
2239                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2240                                         msg: update
2241                                 });
2242                         }
2243                 }
2244                 Ok(())
2245         }
2246
2247         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2248                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2249                 //determine the state of the payment based on our response/if we forward anything/the time
2250                 //we take to respond. We should take care to avoid allowing such an attack.
2251                 //
2252                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2253                 //us repeatedly garbled in different ways, and compare our error messages, which are
2254                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
2255                 //but we should prevent it anyway.
2256
2257                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2258                 let channel_state = &mut *channel_state_lock;
2259
2260                 match channel_state.by_id.entry(msg.channel_id) {
2261                         hash_map::Entry::Occupied(mut chan) => {
2262                                 if chan.get().get_their_node_id() != *their_node_id {
2263                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2264                                 }
2265                                 if !chan.get().is_usable() {
2266                                         // If the update_add is completely bogus, the call will Err and we will close,
2267                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2268                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2269                                         if let PendingHTLCStatus::Forward(PendingHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2270                                                 let chan_update = self.get_channel_update(chan.get());
2271                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2272                                                         channel_id: msg.channel_id,
2273                                                         htlc_id: msg.htlc_id,
2274                                                         reason: if let Ok(update) = chan_update {
2275                                                                 // TODO: Note that |20 is defined as "channel FROM the processing
2276                                                                 // node has been disabled" (emphasis mine), which seems to imply
2277                                                                 // that we can't return |20 for an inbound channel being disabled.
2278                                                                 // This probably needs a spec update but should definitely be
2279                                                                 // allowed.
2280                                                                 onion_utils::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &{
2281                                                                         let mut res = Vec::with_capacity(8 + 128);
2282                                                                         res.extend_from_slice(&byte_utils::be16_to_array(update.contents.flags));
2283                                                                         res.extend_from_slice(&update.encode_with_len()[..]);
2284                                                                         res
2285                                                                 }[..])
2286                                                         } else {
2287                                                                 // This can only happen if the channel isn't in the fully-funded
2288                                                                 // state yet, implying our counterparty is trying to route payments
2289                                                                 // over the channel back to themselves (cause no one else should
2290                                                                 // know the short_id is a lightning channel yet). We should have no
2291                                                                 // problem just calling this unknown_next_peer
2292                                                                 onion_utils::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2293                                                         },
2294                                                 }));
2295                                         }
2296                                 }
2297                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2298                         },
2299                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2300                 }
2301                 Ok(())
2302         }
2303
2304         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2305                 let mut channel_lock = self.channel_state.lock().unwrap();
2306                 let htlc_source = {
2307                         let channel_state = &mut *channel_lock;
2308                         match channel_state.by_id.entry(msg.channel_id) {
2309                                 hash_map::Entry::Occupied(mut chan) => {
2310                                         if chan.get().get_their_node_id() != *their_node_id {
2311                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2312                                         }
2313                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2314                                 },
2315                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2316                         }
2317                 };
2318                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2319                 Ok(())
2320         }
2321
2322         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2323                 let mut channel_lock = self.channel_state.lock().unwrap();
2324                 let channel_state = &mut *channel_lock;
2325                 match channel_state.by_id.entry(msg.channel_id) {
2326                         hash_map::Entry::Occupied(mut chan) => {
2327                                 if chan.get().get_their_node_id() != *their_node_id {
2328                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2329                                 }
2330                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::LightningError { err: msg.reason.clone() }), channel_state, chan);
2331                         },
2332                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2333                 }
2334                 Ok(())
2335         }
2336
2337         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2338                 let mut channel_lock = self.channel_state.lock().unwrap();
2339                 let channel_state = &mut *channel_lock;
2340                 match channel_state.by_id.entry(msg.channel_id) {
2341                         hash_map::Entry::Occupied(mut chan) => {
2342                                 if chan.get().get_their_node_id() != *their_node_id {
2343                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2344                                 }
2345                                 if (msg.failure_code & 0x8000) == 0 {
2346                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2347                                 }
2348                                 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);
2349                                 Ok(())
2350                         },
2351                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2352                 }
2353         }
2354
2355         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2356                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2357                 let channel_state = &mut *channel_state_lock;
2358                 match channel_state.by_id.entry(msg.channel_id) {
2359                         hash_map::Entry::Occupied(mut chan) => {
2360                                 if chan.get().get_their_node_id() != *their_node_id {
2361                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2362                                 }
2363                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2364                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2365                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2366                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some());
2367                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2368                                 }
2369                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2370                                         node_id: their_node_id.clone(),
2371                                         msg: revoke_and_ack,
2372                                 });
2373                                 if let Some(msg) = commitment_signed {
2374                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2375                                                 node_id: their_node_id.clone(),
2376                                                 updates: msgs::CommitmentUpdate {
2377                                                         update_add_htlcs: Vec::new(),
2378                                                         update_fulfill_htlcs: Vec::new(),
2379                                                         update_fail_htlcs: Vec::new(),
2380                                                         update_fail_malformed_htlcs: Vec::new(),
2381                                                         update_fee: None,
2382                                                         commitment_signed: msg,
2383                                                 },
2384                                         });
2385                                 }
2386                                 if let Some(msg) = closing_signed {
2387                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2388                                                 node_id: their_node_id.clone(),
2389                                                 msg,
2390                                         });
2391                                 }
2392                                 Ok(())
2393                         },
2394                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2395                 }
2396         }
2397
2398         #[inline]
2399         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingHTLCInfo, u64)>)]) {
2400                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2401                         let mut forward_event = None;
2402                         if !pending_forwards.is_empty() {
2403                                 let mut channel_state = self.channel_state.lock().unwrap();
2404                                 if channel_state.forward_htlcs.is_empty() {
2405                                         forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS))
2406                                 }
2407                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2408                                         match channel_state.forward_htlcs.entry(match forward_info.type_data {
2409                                                         PendingForwardReceiveHTLCInfo::Forward { short_channel_id, .. } => short_channel_id,
2410                                                         PendingForwardReceiveHTLCInfo::Receive { .. } => 0,
2411                                         }) {
2412                                                 hash_map::Entry::Occupied(mut entry) => {
2413                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info });
2414                                                 },
2415                                                 hash_map::Entry::Vacant(entry) => {
2416                                                         entry.insert(vec!(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info }));
2417                                                 }
2418                                         }
2419                                 }
2420                         }
2421                         match forward_event {
2422                                 Some(time) => {
2423                                         let mut pending_events = self.pending_events.lock().unwrap();
2424                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2425                                                 time_forwardable: time
2426                                         });
2427                                 }
2428                                 None => {},
2429                         }
2430                 }
2431         }
2432
2433         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2434                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2435                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2436                         let channel_state = &mut *channel_state_lock;
2437                         match channel_state.by_id.entry(msg.channel_id) {
2438                                 hash_map::Entry::Occupied(mut chan) => {
2439                                         if chan.get().get_their_node_id() != *their_node_id {
2440                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2441                                         }
2442                                         let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2443                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2444                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2445                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2446                                                 if was_frozen_for_monitor {
2447                                                         assert!(commitment_update.is_none() && closing_signed.is_none() && pending_forwards.is_empty() && pending_failures.is_empty());
2448                                                         return Err(MsgHandleErrInternal::ignore_no_close("Previous monitor update failure prevented responses to RAA"));
2449                                                 } else {
2450                                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, commitment_update.is_some(), pending_forwards, pending_failures);
2451                                                 }
2452                                         }
2453                                         if let Some(updates) = commitment_update {
2454                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2455                                                         node_id: their_node_id.clone(),
2456                                                         updates,
2457                                                 });
2458                                         }
2459                                         if let Some(msg) = closing_signed {
2460                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2461                                                         node_id: their_node_id.clone(),
2462                                                         msg,
2463                                                 });
2464                                         }
2465                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2466                                 },
2467                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2468                         }
2469                 };
2470                 for failure in pending_failures.drain(..) {
2471                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2472                 }
2473                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2474
2475                 Ok(())
2476         }
2477
2478         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2479                 let mut channel_lock = self.channel_state.lock().unwrap();
2480                 let channel_state = &mut *channel_lock;
2481                 match channel_state.by_id.entry(msg.channel_id) {
2482                         hash_map::Entry::Occupied(mut chan) => {
2483                                 if chan.get().get_their_node_id() != *their_node_id {
2484                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2485                                 }
2486                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2487                         },
2488                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2489                 }
2490                 Ok(())
2491         }
2492
2493         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2494                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2495                 let channel_state = &mut *channel_state_lock;
2496
2497                 match channel_state.by_id.entry(msg.channel_id) {
2498                         hash_map::Entry::Occupied(mut chan) => {
2499                                 if chan.get().get_their_node_id() != *their_node_id {
2500                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2501                                 }
2502                                 if !chan.get().is_usable() {
2503                                         return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it", action: msgs::ErrorAction::IgnoreError}));
2504                                 }
2505
2506                                 let our_node_id = self.get_our_node_id();
2507                                 let (announcement, our_bitcoin_sig) =
2508                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2509
2510                                 let were_node_one = announcement.node_id_1 == our_node_id;
2511                                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
2512                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2513                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2514                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2515                                 }
2516
2517                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2518
2519                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2520                                         msg: msgs::ChannelAnnouncement {
2521                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2522                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2523                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2524                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2525                                                 contents: announcement,
2526                                         },
2527                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2528                                 });
2529                         },
2530                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2531                 }
2532                 Ok(())
2533         }
2534
2535         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2536                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2537                 let channel_state = &mut *channel_state_lock;
2538
2539                 match channel_state.by_id.entry(msg.channel_id) {
2540                         hash_map::Entry::Occupied(mut chan) => {
2541                                 if chan.get().get_their_node_id() != *their_node_id {
2542                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2543                                 }
2544                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2545                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2546                                 if let Some(monitor) = channel_monitor {
2547                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2548                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2549                                                 // for the messages it returns, but if we're setting what messages to
2550                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2551                                                 if revoke_and_ack.is_none() {
2552                                                         order = RAACommitmentOrder::CommitmentFirst;
2553                                                 }
2554                                                 if commitment_update.is_none() {
2555                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2556                                                 }
2557                                                 return_monitor_err!(self, e, channel_state, chan, order, revoke_and_ack.is_some(), commitment_update.is_some());
2558                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2559                                         }
2560                                 }
2561                                 if let Some(msg) = funding_locked {
2562                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2563                                                 node_id: their_node_id.clone(),
2564                                                 msg
2565                                         });
2566                                 }
2567                                 macro_rules! send_raa { () => {
2568                                         if let Some(msg) = revoke_and_ack {
2569                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2570                                                         node_id: their_node_id.clone(),
2571                                                         msg
2572                                                 });
2573                                         }
2574                                 } }
2575                                 macro_rules! send_cu { () => {
2576                                         if let Some(updates) = commitment_update {
2577                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2578                                                         node_id: their_node_id.clone(),
2579                                                         updates
2580                                                 });
2581                                         }
2582                                 } }
2583                                 match order {
2584                                         RAACommitmentOrder::RevokeAndACKFirst => {
2585                                                 send_raa!();
2586                                                 send_cu!();
2587                                         },
2588                                         RAACommitmentOrder::CommitmentFirst => {
2589                                                 send_cu!();
2590                                                 send_raa!();
2591                                         },
2592                                 }
2593                                 if let Some(msg) = shutdown {
2594                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2595                                                 node_id: their_node_id.clone(),
2596                                                 msg,
2597                                         });
2598                                 }
2599                                 Ok(())
2600                         },
2601                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2602                 }
2603         }
2604
2605         /// Begin Update fee process. Allowed only on an outbound channel.
2606         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2607         /// PeerManager::process_events afterwards.
2608         /// Note: This API is likely to change!
2609         #[doc(hidden)]
2610         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2611                 let _ = self.total_consistency_lock.read().unwrap();
2612                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2613                 let their_node_id;
2614                 let err: Result<(), _> = loop {
2615                         let channel_state = &mut *channel_state_lock;
2616
2617                         match channel_state.by_id.entry(channel_id) {
2618                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2619                                 hash_map::Entry::Occupied(mut chan) => {
2620                                         if !chan.get().is_outbound() {
2621                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2622                                         }
2623                                         if chan.get().is_awaiting_monitor_update() {
2624                                                 return Err(APIError::MonitorUpdateFailed);
2625                                         }
2626                                         if !chan.get().is_live() {
2627                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2628                                         }
2629                                         their_node_id = chan.get().get_their_node_id();
2630                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2631                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2632                                         {
2633                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2634                                                         unimplemented!();
2635                                                 }
2636                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2637                                                         node_id: chan.get().get_their_node_id(),
2638                                                         updates: msgs::CommitmentUpdate {
2639                                                                 update_add_htlcs: Vec::new(),
2640                                                                 update_fulfill_htlcs: Vec::new(),
2641                                                                 update_fail_htlcs: Vec::new(),
2642                                                                 update_fail_malformed_htlcs: Vec::new(),
2643                                                                 update_fee: Some(update_fee),
2644                                                                 commitment_signed,
2645                                                         },
2646                                                 });
2647                                         }
2648                                 },
2649                         }
2650                         return Ok(())
2651                 };
2652
2653                 match handle_error!(self, err, their_node_id, channel_state_lock) {
2654                         Ok(_) => unreachable!(),
2655                         Err(e) => { Err(APIError::APIMisuseError { err: e.err })}
2656                 }
2657         }
2658 }
2659
2660 impl<ChanSigner: ChannelKeys, M: Deref> events::MessageSendEventsProvider for ChannelManager<ChanSigner, M> where M::Target: ManyChannelMonitor {
2661         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2662                 // TODO: Event release to users and serialization is currently race-y: it's very easy for a
2663                 // user to serialize a ChannelManager with pending events in it and lose those events on
2664                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2665                 {
2666                         //TODO: This behavior should be documented.
2667                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2668                                 if let Some(preimage) = htlc_update.payment_preimage {
2669                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2670                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2671                                 } else {
2672                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2673                                         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() });
2674                                 }
2675                         }
2676                 }
2677
2678                 let mut ret = Vec::new();
2679                 let mut channel_state = self.channel_state.lock().unwrap();
2680                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2681                 ret
2682         }
2683 }
2684
2685 impl<ChanSigner: ChannelKeys, M: Deref> events::EventsProvider for ChannelManager<ChanSigner, M> where M::Target: ManyChannelMonitor {
2686         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2687                 // TODO: Event release to users and serialization is currently race-y: it's very easy for a
2688                 // user to serialize a ChannelManager with pending events in it and lose those events on
2689                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2690                 {
2691                         //TODO: This behavior should be documented.
2692                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2693                                 if let Some(preimage) = htlc_update.payment_preimage {
2694                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2695                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2696                                 } else {
2697                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2698                                         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() });
2699                                 }
2700                         }
2701                 }
2702
2703                 let mut ret = Vec::new();
2704                 let mut pending_events = self.pending_events.lock().unwrap();
2705                 mem::swap(&mut ret, &mut *pending_events);
2706                 ret
2707         }
2708 }
2709
2710 impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send> ChainListener for ChannelManager<ChanSigner, M> where M::Target: ManyChannelMonitor {
2711         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2712                 let header_hash = header.bitcoin_hash();
2713                 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2714                 let _ = self.total_consistency_lock.read().unwrap();
2715                 let mut failed_channels = Vec::new();
2716                 {
2717                         let mut channel_lock = self.channel_state.lock().unwrap();
2718                         let channel_state = &mut *channel_lock;
2719                         let short_to_id = &mut channel_state.short_to_id;
2720                         let pending_msg_events = &mut channel_state.pending_msg_events;
2721                         channel_state.by_id.retain(|_, channel| {
2722                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2723                                 if let Ok(Some(funding_locked)) = chan_res {
2724                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2725                                                 node_id: channel.get_their_node_id(),
2726                                                 msg: funding_locked,
2727                                         });
2728                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2729                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2730                                                         node_id: channel.get_their_node_id(),
2731                                                         msg: announcement_sigs,
2732                                                 });
2733                                         }
2734                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2735                                 } else if let Err(e) = chan_res {
2736                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
2737                                                 node_id: channel.get_their_node_id(),
2738                                                 action: msgs::ErrorAction::SendErrorMessage { msg: e },
2739                                         });
2740                                         return false;
2741                                 }
2742                                 if let Some(funding_txo) = channel.get_funding_txo() {
2743                                         for tx in txn_matched {
2744                                                 for inp in tx.input.iter() {
2745                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2746                                                                 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()));
2747                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2748                                                                         short_to_id.remove(&short_id);
2749                                                                 }
2750                                                                 // It looks like our counterparty went on-chain. We go ahead and
2751                                                                 // broadcast our latest local state as well here, just in case its
2752                                                                 // some kind of SPV attack, though we expect these to be dropped.
2753                                                                 failed_channels.push(channel.force_shutdown());
2754                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2755                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2756                                                                                 msg: update
2757                                                                         });
2758                                                                 }
2759                                                                 return false;
2760                                                         }
2761                                                 }
2762                                         }
2763                                 }
2764                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2765                                         if let Some(short_id) = channel.get_short_channel_id() {
2766                                                 short_to_id.remove(&short_id);
2767                                         }
2768                                         failed_channels.push(channel.force_shutdown());
2769                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2770                                         // the latest local tx for us, so we should skip that here (it doesn't really
2771                                         // hurt anything, but does make tests a bit simpler).
2772                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2773                                         if let Ok(update) = self.get_channel_update(&channel) {
2774                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2775                                                         msg: update
2776                                                 });
2777                                         }
2778                                         return false;
2779                                 }
2780                                 true
2781                         });
2782                 }
2783                 for failure in failed_channels.drain(..) {
2784                         self.finish_force_close_channel(failure);
2785                 }
2786                 self.latest_block_height.store(height as usize, Ordering::Release);
2787                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2788         }
2789
2790         /// We force-close the channel without letting our counterparty participate in the shutdown
2791         fn block_disconnected(&self, header: &BlockHeader, _: u32) {
2792                 let _ = self.total_consistency_lock.read().unwrap();
2793                 let mut failed_channels = Vec::new();
2794                 {
2795                         let mut channel_lock = self.channel_state.lock().unwrap();
2796                         let channel_state = &mut *channel_lock;
2797                         let short_to_id = &mut channel_state.short_to_id;
2798                         let pending_msg_events = &mut channel_state.pending_msg_events;
2799                         channel_state.by_id.retain(|_,  v| {
2800                                 if v.block_disconnected(header) {
2801                                         if let Some(short_id) = v.get_short_channel_id() {
2802                                                 short_to_id.remove(&short_id);
2803                                         }
2804                                         failed_channels.push(v.force_shutdown());
2805                                         if let Ok(update) = self.get_channel_update(&v) {
2806                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2807                                                         msg: update
2808                                                 });
2809                                         }
2810                                         false
2811                                 } else {
2812                                         true
2813                                 }
2814                         });
2815                 }
2816                 for failure in failed_channels.drain(..) {
2817                         self.finish_force_close_channel(failure);
2818                 }
2819                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2820                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2821         }
2822 }
2823
2824 impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send> ChannelMessageHandler for ChannelManager<ChanSigner, M> where M::Target: ManyChannelMonitor {
2825         fn handle_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) {
2826                 let _ = self.total_consistency_lock.read().unwrap();
2827                 let res = self.internal_open_channel(their_node_id, their_features, msg);
2828                 if res.is_err() {
2829                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2830                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2831                 }
2832         }
2833
2834         fn handle_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) {
2835                 let _ = self.total_consistency_lock.read().unwrap();
2836                 let res = self.internal_accept_channel(their_node_id, their_features, msg);
2837                 if res.is_err() {
2838                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2839                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2840                 }
2841         }
2842
2843         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
2844                 let _ = self.total_consistency_lock.read().unwrap();
2845                 let res = self.internal_funding_created(their_node_id, msg);
2846                 if res.is_err() {
2847                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2848                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2849                 }
2850         }
2851
2852         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
2853                 let _ = self.total_consistency_lock.read().unwrap();
2854                 let res = self.internal_funding_signed(their_node_id, msg);
2855                 if res.is_err() {
2856                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2857                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2858                 }
2859         }
2860
2861         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) {
2862                 let _ = self.total_consistency_lock.read().unwrap();
2863                 let res = self.internal_funding_locked(their_node_id, msg);
2864                 if res.is_err() {
2865                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2866                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2867                 }
2868         }
2869
2870         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) {
2871                 let _ = self.total_consistency_lock.read().unwrap();
2872                 let res = self.internal_shutdown(their_node_id, msg);
2873                 if res.is_err() {
2874                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2875                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2876                 }
2877         }
2878
2879         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
2880                 let _ = self.total_consistency_lock.read().unwrap();
2881                 let res = self.internal_closing_signed(their_node_id, msg);
2882                 if res.is_err() {
2883                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2884                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2885                 }
2886         }
2887
2888         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
2889                 let _ = self.total_consistency_lock.read().unwrap();
2890                 let res = self.internal_update_add_htlc(their_node_id, msg);
2891                 if res.is_err() {
2892                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2893                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2894                 }
2895         }
2896
2897         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
2898                 let _ = self.total_consistency_lock.read().unwrap();
2899                 let res = self.internal_update_fulfill_htlc(their_node_id, msg);
2900                 if res.is_err() {
2901                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2902                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2903                 }
2904         }
2905
2906         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
2907                 let _ = self.total_consistency_lock.read().unwrap();
2908                 let res = self.internal_update_fail_htlc(their_node_id, msg);
2909                 if res.is_err() {
2910                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2911                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2912                 }
2913         }
2914
2915         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
2916                 let _ = self.total_consistency_lock.read().unwrap();
2917                 let res = self.internal_update_fail_malformed_htlc(their_node_id, msg);
2918                 if res.is_err() {
2919                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2920                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2921                 }
2922         }
2923
2924         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
2925                 let _ = self.total_consistency_lock.read().unwrap();
2926                 let res = self.internal_commitment_signed(their_node_id, msg);
2927                 if res.is_err() {
2928                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2929                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2930                 }
2931         }
2932
2933         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
2934                 let _ = self.total_consistency_lock.read().unwrap();
2935                 let res = self.internal_revoke_and_ack(their_node_id, msg);
2936                 if res.is_err() {
2937                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2938                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2939                 }
2940         }
2941
2942         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
2943                 let _ = self.total_consistency_lock.read().unwrap();
2944                 let res = self.internal_update_fee(their_node_id, msg);
2945                 if res.is_err() {
2946                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2947                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2948                 }
2949         }
2950
2951         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
2952                 let _ = self.total_consistency_lock.read().unwrap();
2953                 let res = self.internal_announcement_signatures(their_node_id, msg);
2954                 if res.is_err() {
2955                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2956                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2957                 }
2958         }
2959
2960         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
2961                 let _ = self.total_consistency_lock.read().unwrap();
2962                 let res = self.internal_channel_reestablish(their_node_id, msg);
2963                 if res.is_err() {
2964                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2965                         let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2966                 }
2967         }
2968
2969         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2970                 let _ = self.total_consistency_lock.read().unwrap();
2971                 let mut failed_channels = Vec::new();
2972                 let mut failed_payments = Vec::new();
2973                 let mut no_channels_remain = true;
2974                 {
2975                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2976                         let channel_state = &mut *channel_state_lock;
2977                         let short_to_id = &mut channel_state.short_to_id;
2978                         let pending_msg_events = &mut channel_state.pending_msg_events;
2979                         if no_connection_possible {
2980                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2981                                 channel_state.by_id.retain(|_, chan| {
2982                                         if chan.get_their_node_id() == *their_node_id {
2983                                                 if let Some(short_id) = chan.get_short_channel_id() {
2984                                                         short_to_id.remove(&short_id);
2985                                                 }
2986                                                 failed_channels.push(chan.force_shutdown());
2987                                                 if let Ok(update) = self.get_channel_update(&chan) {
2988                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2989                                                                 msg: update
2990                                                         });
2991                                                 }
2992                                                 false
2993                                         } else {
2994                                                 true
2995                                         }
2996                                 });
2997                         } else {
2998                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2999                                 channel_state.by_id.retain(|_, chan| {
3000                                         if chan.get_their_node_id() == *their_node_id {
3001                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
3002                                                 chan.to_disabled_marked();
3003                                                 if !failed_adds.is_empty() {
3004                                                         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
3005                                                         failed_payments.push((chan_update, failed_adds));
3006                                                 }
3007                                                 if chan.is_shutdown() {
3008                                                         if let Some(short_id) = chan.get_short_channel_id() {
3009                                                                 short_to_id.remove(&short_id);
3010                                                         }
3011                                                         return false;
3012                                                 } else {
3013                                                         no_channels_remain = false;
3014                                                 }
3015                                         }
3016                                         true
3017                                 })
3018                         }
3019                         pending_msg_events.retain(|msg| {
3020                                 match msg {
3021                                         &events::MessageSendEvent::SendAcceptChannel { ref node_id, .. } => node_id != their_node_id,
3022                                         &events::MessageSendEvent::SendOpenChannel { ref node_id, .. } => node_id != their_node_id,
3023                                         &events::MessageSendEvent::SendFundingCreated { ref node_id, .. } => node_id != their_node_id,
3024                                         &events::MessageSendEvent::SendFundingSigned { ref node_id, .. } => node_id != their_node_id,
3025                                         &events::MessageSendEvent::SendFundingLocked { ref node_id, .. } => node_id != their_node_id,
3026                                         &events::MessageSendEvent::SendAnnouncementSignatures { ref node_id, .. } => node_id != their_node_id,
3027                                         &events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => node_id != their_node_id,
3028                                         &events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => node_id != their_node_id,
3029                                         &events::MessageSendEvent::SendClosingSigned { ref node_id, .. } => node_id != their_node_id,
3030                                         &events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != their_node_id,
3031                                         &events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != their_node_id,
3032                                         &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
3033                                         &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
3034                                         &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
3035                                         &events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != their_node_id,
3036                                         &events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
3037                                 }
3038                         });
3039                 }
3040                 if no_channels_remain {
3041                         self.per_peer_state.write().unwrap().remove(their_node_id);
3042                 }
3043
3044                 for failure in failed_channels.drain(..) {
3045                         self.finish_force_close_channel(failure);
3046                 }
3047                 for (chan_update, mut htlc_sources) in failed_payments {
3048                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
3049                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
3050                         }
3051                 }
3052         }
3053
3054         fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init) {
3055                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
3056
3057                 let _ = self.total_consistency_lock.read().unwrap();
3058
3059                 {
3060                         let mut peer_state_lock = self.per_peer_state.write().unwrap();
3061                         match peer_state_lock.entry(their_node_id.clone()) {
3062                                 hash_map::Entry::Vacant(e) => {
3063                                         e.insert(Mutex::new(PeerState {
3064                                                 latest_features: init_msg.features.clone(),
3065                                         }));
3066                                 },
3067                                 hash_map::Entry::Occupied(e) => {
3068                                         e.get().lock().unwrap().latest_features = init_msg.features.clone();
3069                                 },
3070                         }
3071                 }
3072
3073                 let mut channel_state_lock = self.channel_state.lock().unwrap();
3074                 let channel_state = &mut *channel_state_lock;
3075                 let pending_msg_events = &mut channel_state.pending_msg_events;
3076                 channel_state.by_id.retain(|_, chan| {
3077                         if chan.get_their_node_id() == *their_node_id {
3078                                 if !chan.have_received_message() {
3079                                         // If we created this (outbound) channel while we were disconnected from the
3080                                         // peer we probably failed to send the open_channel message, which is now
3081                                         // lost. We can't have had anything pending related to this channel, so we just
3082                                         // drop it.
3083                                         false
3084                                 } else {
3085                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
3086                                                 node_id: chan.get_their_node_id(),
3087                                                 msg: chan.get_channel_reestablish(),
3088                                         });
3089                                         true
3090                                 }
3091                         } else { true }
3092                 });
3093                 //TODO: Also re-broadcast announcement_signatures
3094         }
3095
3096         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
3097                 let _ = self.total_consistency_lock.read().unwrap();
3098
3099                 if msg.channel_id == [0; 32] {
3100                         for chan in self.list_channels() {
3101                                 if chan.remote_network_id == *their_node_id {
3102                                         self.force_close_channel(&chan.channel_id);
3103                                 }
3104                         }
3105                 } else {
3106                         self.force_close_channel(&msg.channel_id);
3107                 }
3108         }
3109 }
3110
3111 const SERIALIZATION_VERSION: u8 = 1;
3112 const MIN_SERIALIZATION_VERSION: u8 = 1;
3113
3114 impl Writeable for PendingHTLCInfo {
3115         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3116                 match &self.type_data {
3117                         &PendingForwardReceiveHTLCInfo::Forward { ref onion_packet, ref short_channel_id } => {
3118                                 0u8.write(writer)?;
3119                                 onion_packet.write(writer)?;
3120                                 short_channel_id.write(writer)?;
3121                         },
3122                         &PendingForwardReceiveHTLCInfo::Receive { ref payment_data } => {
3123                                 1u8.write(writer)?;
3124                                 payment_data.write(writer)?;
3125                         },
3126                 }
3127                 self.incoming_shared_secret.write(writer)?;
3128                 self.payment_hash.write(writer)?;
3129                 self.amt_to_forward.write(writer)?;
3130                 self.outgoing_cltv_value.write(writer)?;
3131                 Ok(())
3132         }
3133 }
3134
3135 impl<R: ::std::io::Read> Readable<R> for PendingHTLCInfo {
3136         fn read(reader: &mut R) -> Result<PendingHTLCInfo, DecodeError> {
3137                 Ok(PendingHTLCInfo {
3138                         type_data: match Readable::read(reader)? {
3139                                 0u8 => PendingForwardReceiveHTLCInfo::Forward {
3140                                         onion_packet: Readable::read(reader)?,
3141                                         short_channel_id: Readable::read(reader)?,
3142                                 },
3143                                 1u8 => PendingForwardReceiveHTLCInfo::Receive {
3144                                         payment_data: Readable::read(reader)?,
3145                                 },
3146                                 _ => return Err(DecodeError::InvalidValue),
3147                         },
3148                         incoming_shared_secret: Readable::read(reader)?,
3149                         payment_hash: Readable::read(reader)?,
3150                         amt_to_forward: Readable::read(reader)?,
3151                         outgoing_cltv_value: Readable::read(reader)?,
3152                 })
3153         }
3154 }
3155
3156 impl Writeable for HTLCFailureMsg {
3157         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3158                 match self {
3159                         &HTLCFailureMsg::Relay(ref fail_msg) => {
3160                                 0u8.write(writer)?;
3161                                 fail_msg.write(writer)?;
3162                         },
3163                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
3164                                 1u8.write(writer)?;
3165                                 fail_msg.write(writer)?;
3166                         }
3167                 }
3168                 Ok(())
3169         }
3170 }
3171
3172 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3173         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3174                 match <u8 as Readable<R>>::read(reader)? {
3175                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3176                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3177                         _ => Err(DecodeError::InvalidValue),
3178                 }
3179         }
3180 }
3181
3182 impl Writeable for PendingHTLCStatus {
3183         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3184                 match self {
3185                         &PendingHTLCStatus::Forward(ref forward_info) => {
3186                                 0u8.write(writer)?;
3187                                 forward_info.write(writer)?;
3188                         },
3189                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3190                                 1u8.write(writer)?;
3191                                 fail_msg.write(writer)?;
3192                         }
3193                 }
3194                 Ok(())
3195         }
3196 }
3197
3198 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3199         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3200                 match <u8 as Readable<R>>::read(reader)? {
3201                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3202                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3203                         _ => Err(DecodeError::InvalidValue),
3204                 }
3205         }
3206 }
3207
3208 impl_writeable!(HTLCPreviousHopData, 0, {
3209         short_channel_id,
3210         htlc_id,
3211         incoming_packet_shared_secret
3212 });
3213
3214 impl Writeable for HTLCSource {
3215         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3216                 match self {
3217                         &HTLCSource::PreviousHopData(ref hop_data) => {
3218                                 0u8.write(writer)?;
3219                                 hop_data.write(writer)?;
3220                         },
3221                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3222                                 1u8.write(writer)?;
3223                                 route.write(writer)?;
3224                                 session_priv.write(writer)?;
3225                                 first_hop_htlc_msat.write(writer)?;
3226                         }
3227                 }
3228                 Ok(())
3229         }
3230 }
3231
3232 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3233         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3234                 match <u8 as Readable<R>>::read(reader)? {
3235                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3236                         1 => Ok(HTLCSource::OutboundRoute {
3237                                 route: Readable::read(reader)?,
3238                                 session_priv: Readable::read(reader)?,
3239                                 first_hop_htlc_msat: Readable::read(reader)?,
3240                         }),
3241                         _ => Err(DecodeError::InvalidValue),
3242                 }
3243         }
3244 }
3245
3246 impl Writeable for HTLCFailReason {
3247         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3248                 match self {
3249                         &HTLCFailReason::LightningError { ref err } => {
3250                                 0u8.write(writer)?;
3251                                 err.write(writer)?;
3252                         },
3253                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3254                                 1u8.write(writer)?;
3255                                 failure_code.write(writer)?;
3256                                 data.write(writer)?;
3257                         }
3258                 }
3259                 Ok(())
3260         }
3261 }
3262
3263 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3264         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3265                 match <u8 as Readable<R>>::read(reader)? {
3266                         0 => Ok(HTLCFailReason::LightningError { err: Readable::read(reader)? }),
3267                         1 => Ok(HTLCFailReason::Reason {
3268                                 failure_code: Readable::read(reader)?,
3269                                 data: Readable::read(reader)?,
3270                         }),
3271                         _ => Err(DecodeError::InvalidValue),
3272                 }
3273         }
3274 }
3275
3276 impl Writeable for HTLCForwardInfo {
3277         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3278                 match self {
3279                         &HTLCForwardInfo::AddHTLC { ref prev_short_channel_id, ref prev_htlc_id, ref forward_info } => {
3280                                 0u8.write(writer)?;
3281                                 prev_short_channel_id.write(writer)?;
3282                                 prev_htlc_id.write(writer)?;
3283                                 forward_info.write(writer)?;
3284                         },
3285                         &HTLCForwardInfo::FailHTLC { ref htlc_id, ref err_packet } => {
3286                                 1u8.write(writer)?;
3287                                 htlc_id.write(writer)?;
3288                                 err_packet.write(writer)?;
3289                         },
3290                 }
3291                 Ok(())
3292         }
3293 }
3294
3295 impl<R: ::std::io::Read> Readable<R> for HTLCForwardInfo {
3296         fn read(reader: &mut R) -> Result<HTLCForwardInfo, DecodeError> {
3297                 match <u8 as Readable<R>>::read(reader)? {
3298                         0 => Ok(HTLCForwardInfo::AddHTLC {
3299                                 prev_short_channel_id: Readable::read(reader)?,
3300                                 prev_htlc_id: Readable::read(reader)?,
3301                                 forward_info: Readable::read(reader)?,
3302                         }),
3303                         1 => Ok(HTLCForwardInfo::FailHTLC {
3304                                 htlc_id: Readable::read(reader)?,
3305                                 err_packet: Readable::read(reader)?,
3306                         }),
3307                         _ => Err(DecodeError::InvalidValue),
3308                 }
3309         }
3310 }
3311
3312 impl<ChanSigner: ChannelKeys + Writeable, M: Deref> Writeable for ChannelManager<ChanSigner, M> where M::Target: ManyChannelMonitor {
3313         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3314                 let _ = self.total_consistency_lock.write().unwrap();
3315
3316                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3317                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3318
3319                 self.genesis_hash.write(writer)?;
3320                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3321                 self.last_block_hash.lock().unwrap().write(writer)?;
3322
3323                 let channel_state = self.channel_state.lock().unwrap();
3324                 let mut unfunded_channels = 0;
3325                 for (_, channel) in channel_state.by_id.iter() {
3326                         if !channel.is_funding_initiated() {
3327                                 unfunded_channels += 1;
3328                         }
3329                 }
3330                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3331                 for (_, channel) in channel_state.by_id.iter() {
3332                         if channel.is_funding_initiated() {
3333                                 channel.write(writer)?;
3334                         }
3335                 }
3336
3337                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3338                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3339                         short_channel_id.write(writer)?;
3340                         (pending_forwards.len() as u64).write(writer)?;
3341                         for forward in pending_forwards {
3342                                 forward.write(writer)?;
3343                         }
3344                 }
3345
3346                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3347                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3348                         payment_hash.write(writer)?;
3349                         (previous_hops.len() as u64).write(writer)?;
3350                         for htlc in previous_hops.iter() {
3351                                 htlc.src.write(writer)?;
3352                                 htlc.value.write(writer)?;
3353                                 htlc.payment_data.write(writer)?;
3354                         }
3355                 }
3356
3357                 let per_peer_state = self.per_peer_state.write().unwrap();
3358                 (per_peer_state.len() as u64).write(writer)?;
3359                 for (peer_pubkey, peer_state_mutex) in per_peer_state.iter() {
3360                         peer_pubkey.write(writer)?;
3361                         let peer_state = peer_state_mutex.lock().unwrap();
3362                         peer_state.latest_features.write(writer)?;
3363                 }
3364
3365                 (self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
3366
3367                 Ok(())
3368         }
3369 }
3370
3371 /// Arguments for the creation of a ChannelManager that are not deserialized.
3372 ///
3373 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3374 /// is:
3375 /// 1) Deserialize all stored ChannelMonitors.
3376 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3377 ///    ChannelManager)>::read(reader, args).
3378 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3379 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3380 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3381 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3382 /// 4) Reconnect blocks on your ChannelMonitors.
3383 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3384 /// 6) Disconnect/connect blocks on the ChannelManager.
3385 /// 7) Register the new ChannelManager with your ChainWatchInterface.
3386 pub struct ChannelManagerReadArgs<'a, ChanSigner: ChannelKeys, M: Deref> where M::Target: ManyChannelMonitor {
3387         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3388         /// deserialization.
3389         pub keys_manager: Arc<KeysInterface<ChanKeySigner = ChanSigner>>,
3390
3391         /// The fee_estimator for use in the ChannelManager in the future.
3392         ///
3393         /// No calls to the FeeEstimator will be made during deserialization.
3394         pub fee_estimator: Arc<FeeEstimator>,
3395         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3396         ///
3397         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3398         /// you have deserialized ChannelMonitors separately and will add them to your
3399         /// ManyChannelMonitor after deserializing this ChannelManager.
3400         pub monitor: M,
3401
3402         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3403         /// used to broadcast the latest local commitment transactions of channels which must be
3404         /// force-closed during deserialization.
3405         pub tx_broadcaster: Arc<BroadcasterInterface>,
3406         /// The Logger for use in the ChannelManager and which may be used to log information during
3407         /// deserialization.
3408         pub logger: Arc<Logger>,
3409         /// Default settings used for new channels. Any existing channels will continue to use the
3410         /// runtime settings which were stored when the ChannelManager was serialized.
3411         pub default_config: UserConfig,
3412
3413         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3414         /// value.get_funding_txo() should be the key).
3415         ///
3416         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3417         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
3418         /// is true for missing channels as well. If there is a monitor missing for which we find
3419         /// channel data Err(DecodeError::InvalidValue) will be returned.
3420         ///
3421         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3422         /// this struct.
3423         pub channel_monitors: &'a mut HashMap<OutPoint, &'a mut ChannelMonitor>,
3424 }
3425
3426 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 {
3427         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a, ChanSigner, M>) -> Result<Self, DecodeError> {
3428                 let _ver: u8 = Readable::read(reader)?;
3429                 let min_ver: u8 = Readable::read(reader)?;
3430                 if min_ver > SERIALIZATION_VERSION {
3431                         return Err(DecodeError::UnknownVersion);
3432                 }
3433
3434                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3435                 let latest_block_height: u32 = Readable::read(reader)?;
3436                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3437
3438                 let mut closed_channels = Vec::new();
3439
3440                 let channel_count: u64 = Readable::read(reader)?;
3441                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3442                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3443                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3444                 for _ in 0..channel_count {
3445                         let mut channel: Channel<ChanSigner> = ReadableArgs::read(reader, args.logger.clone())?;
3446                         if channel.last_block_connected != last_block_hash {
3447                                 return Err(DecodeError::InvalidValue);
3448                         }
3449
3450                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3451                         funding_txo_set.insert(funding_txo.clone());
3452                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
3453                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3454                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3455                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3456                                         let mut force_close_res = channel.force_shutdown();
3457                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3458                                         closed_channels.push(force_close_res);
3459                                 } else {
3460                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3461                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3462                                         }
3463                                         by_id.insert(channel.channel_id(), channel);
3464                                 }
3465                         } else {
3466                                 return Err(DecodeError::InvalidValue);
3467                         }
3468                 }
3469
3470                 for (ref funding_txo, ref mut monitor) in args.channel_monitors.iter_mut() {
3471                         if !funding_txo_set.contains(funding_txo) {
3472                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3473                         }
3474                 }
3475
3476                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3477                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3478                 for _ in 0..forward_htlcs_count {
3479                         let short_channel_id = Readable::read(reader)?;
3480                         let pending_forwards_count: u64 = Readable::read(reader)?;
3481                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3482                         for _ in 0..pending_forwards_count {
3483                                 pending_forwards.push(Readable::read(reader)?);
3484                         }
3485                         forward_htlcs.insert(short_channel_id, pending_forwards);
3486                 }
3487
3488                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3489                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3490                 for _ in 0..claimable_htlcs_count {
3491                         let payment_hash = Readable::read(reader)?;
3492                         let previous_hops_len: u64 = Readable::read(reader)?;
3493                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3494                         for _ in 0..previous_hops_len {
3495                                 previous_hops.push(ClaimableHTLC {
3496                                         src: Readable::read(reader)?,
3497                                         value: Readable::read(reader)?,
3498                                         payment_data: Readable::read(reader)?,
3499                                 });
3500                         }
3501                         claimable_htlcs.insert(payment_hash, previous_hops);
3502                 }
3503
3504                 let peer_count: u64 = Readable::read(reader)?;
3505                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, 128));
3506                 for _ in 0..peer_count {
3507                         let peer_pubkey = Readable::read(reader)?;
3508                         let peer_state = PeerState {
3509                                 latest_features: Readable::read(reader)?,
3510                         };
3511                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
3512                 }
3513
3514                 let last_node_announcement_serial: u32 = Readable::read(reader)?;
3515
3516                 let channel_manager = ChannelManager {
3517                         genesis_hash,
3518                         fee_estimator: args.fee_estimator,
3519                         monitor: args.monitor,
3520                         tx_broadcaster: args.tx_broadcaster,
3521
3522                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3523                         last_block_hash: Mutex::new(last_block_hash),
3524                         secp_ctx: Secp256k1::new(),
3525
3526                         channel_state: Mutex::new(ChannelHolder {
3527                                 by_id,
3528                                 short_to_id,
3529                                 forward_htlcs,
3530                                 claimable_htlcs,
3531                                 pending_msg_events: Vec::new(),
3532                         }),
3533                         our_network_key: args.keys_manager.get_node_secret(),
3534
3535                         last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
3536
3537                         per_peer_state: RwLock::new(per_peer_state),
3538
3539                         pending_events: Mutex::new(Vec::new()),
3540                         total_consistency_lock: RwLock::new(()),
3541                         keys_manager: args.keys_manager,
3542                         logger: args.logger,
3543                         default_configuration: args.default_config,
3544                 };
3545
3546                 for close_res in closed_channels.drain(..) {
3547                         channel_manager.finish_force_close_channel(close_res);
3548                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3549                         //connection or two.
3550                 }
3551
3552                 Ok((last_block_hash.clone(), channel_manager))
3553         }
3554 }