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