1 //! The top-level channel management and payment tracking stuff lives here.
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).
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).
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;
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;
23 use secp256k1::key::{SecretKey,PublicKey};
24 use secp256k1::Secp256k1;
25 use secp256k1::ecdh::SharedSecret;
28 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
29 use chain::transaction::OutPoint;
30 use ln::channel::{Channel, ChannelError};
31 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
32 use ln::router::Route;
34 use ln::msgs::LocalFeatures;
36 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
37 use chain::keysinterface::KeysInterface;
38 use util::config::UserConfig;
39 use util::{byte_utils, events};
40 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
41 use util::chacha20::ChaCha20;
42 use util::logger::Logger;
43 use util::errors::APIError;
46 use std::collections::{HashMap, hash_map, HashSet};
48 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
49 use std::sync::atomic::{AtomicUsize, Ordering};
50 use std::time::Duration;
52 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
54 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
55 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
56 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
58 // When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
59 // which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
60 // filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
61 // the HTLC backwards along the relevant path).
62 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
63 // our payment, which we can use to decode errors or inform the user that the payment was sent.
64 /// Stores the info we will need to send when we want to forward an HTLC onwards
65 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
66 pub(super) struct PendingForwardHTLCInfo {
67 onion_packet: Option<msgs::OnionPacket>,
68 incoming_shared_secret: [u8; 32],
69 payment_hash: PaymentHash,
70 short_channel_id: u64,
71 pub(super) amt_to_forward: u64,
72 pub(super) outgoing_cltv_value: u32,
75 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
76 pub(super) enum HTLCFailureMsg {
77 Relay(msgs::UpdateFailHTLC),
78 Malformed(msgs::UpdateFailMalformedHTLC),
81 /// Stores whether we can't forward an HTLC or relevant forwarding info
82 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
83 pub(super) enum PendingHTLCStatus {
84 Forward(PendingForwardHTLCInfo),
88 /// Tracks the inbound corresponding to an outbound HTLC
89 #[derive(Clone, PartialEq)]
90 pub(super) struct HTLCPreviousHopData {
91 short_channel_id: u64,
93 incoming_packet_shared_secret: [u8; 32],
96 /// Tracks the inbound corresponding to an outbound HTLC
97 #[derive(Clone, PartialEq)]
98 pub(super) enum HTLCSource {
99 PreviousHopData(HTLCPreviousHopData),
102 session_priv: SecretKey,
103 /// Technically we can recalculate this from the route, but we cache it here to avoid
104 /// doing a double-pass on route when we get a failure back
105 first_hop_htlc_msat: u64,
110 pub fn dummy() -> Self {
111 HTLCSource::OutboundRoute {
112 route: Route { hops: Vec::new() },
113 session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
114 first_hop_htlc_msat: 0,
119 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
120 pub(super) enum HTLCFailReason {
122 err: msgs::OnionErrorPacket,
130 /// payment_hash type, use to cross-lock hop
131 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
132 pub struct PaymentHash(pub [u8;32]);
133 /// payment_preimage type, use to route payment between hop
134 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
135 pub struct PaymentPreimage(pub [u8;32]);
137 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
139 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
140 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
141 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
142 /// channel_state lock. We then return the set of things that need to be done outside the lock in
143 /// this struct and call handle_error!() on it.
145 struct MsgHandleErrInternal {
146 err: msgs::HandleError,
147 shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
149 impl MsgHandleErrInternal {
151 fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
155 action: Some(msgs::ErrorAction::SendErrorMessage {
156 msg: msgs::ErrorMessage {
158 data: err.to_string()
162 shutdown_finish: None,
166 fn ignore_no_close(err: &'static str) -> Self {
170 action: Some(msgs::ErrorAction::IgnoreError),
172 shutdown_finish: None,
176 fn from_no_close(err: msgs::HandleError) -> Self {
177 Self { err, shutdown_finish: None }
180 fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
184 action: Some(msgs::ErrorAction::SendErrorMessage {
185 msg: msgs::ErrorMessage {
187 data: err.to_string()
191 shutdown_finish: Some((shutdown_res, channel_update)),
195 fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
198 ChannelError::Ignore(msg) => HandleError {
200 action: Some(msgs::ErrorAction::IgnoreError),
202 ChannelError::Close(msg) => HandleError {
204 action: Some(msgs::ErrorAction::SendErrorMessage {
205 msg: msgs::ErrorMessage {
207 data: msg.to_string()
211 ChannelError::CloseDelayBroadcast { msg, .. } => HandleError {
213 action: Some(msgs::ErrorAction::SendErrorMessage {
214 msg: msgs::ErrorMessage {
216 data: msg.to_string()
221 shutdown_finish: None,
226 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
227 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
228 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
229 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
230 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
232 pub(super) enum HTLCForwardInfo {
234 prev_short_channel_id: u64,
236 forward_info: PendingForwardHTLCInfo,
240 err_packet: msgs::OnionErrorPacket,
244 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
245 /// be sent in the order they appear in the return value, however sometimes the order needs to be
246 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
247 /// they were originally sent). In those cases, this enum is also returned.
248 #[derive(Clone, PartialEq)]
249 pub(super) enum RAACommitmentOrder {
250 /// Send the CommitmentUpdate messages first
252 /// Send the RevokeAndACK message first
256 // Note this is only exposed in cfg(test):
257 pub(super) struct ChannelHolder {
258 pub(super) by_id: HashMap<[u8; 32], Channel>,
259 pub(super) short_to_id: HashMap<u64, [u8; 32]>,
260 /// short channel id -> forward infos. Key of 0 means payments received
261 /// Note that while this is held in the same mutex as the channels themselves, no consistency
262 /// guarantees are made about the existence of a channel with the short id here, nor the short
263 /// ids in the PendingForwardHTLCInfo!
264 pub(super) forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
265 /// payment_hash -> Vec<(amount_received, htlc_source)> for tracking things that were to us and
266 /// can be failed/claimed by the user
267 /// Note that while this is held in the same mutex as the channels themselves, no consistency
268 /// guarantees are made about the channels given here actually existing anymore by the time you
270 pub(super) claimable_htlcs: HashMap<PaymentHash, Vec<(u64, HTLCPreviousHopData)>>,
271 /// Messages to send to peers - pushed to in the same lock that they are generated in (except
272 /// for broadcast messages, where ordering isn't as strict).
273 pub(super) pending_msg_events: Vec<events::MessageSendEvent>,
275 pub(super) struct MutChannelHolder<'a> {
276 pub(super) by_id: &'a mut HashMap<[u8; 32], Channel>,
277 pub(super) short_to_id: &'a mut HashMap<u64, [u8; 32]>,
278 pub(super) forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
279 pub(super) claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<(u64, HTLCPreviousHopData)>>,
280 pub(super) pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
283 pub(super) fn borrow_parts(&mut self) -> MutChannelHolder {
285 by_id: &mut self.by_id,
286 short_to_id: &mut self.short_to_id,
287 forward_htlcs: &mut self.forward_htlcs,
288 claimable_htlcs: &mut self.claimable_htlcs,
289 pending_msg_events: &mut self.pending_msg_events,
294 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
295 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
297 /// Manager which keeps track of a number of channels and sends messages to the appropriate
298 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
300 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
301 /// to individual Channels.
303 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
304 /// all peers during write/read (though does not modify this instance, only the instance being
305 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
306 /// called funding_transaction_generated for outbound channels).
308 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
309 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
310 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
311 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
312 /// the serialization process). If the deserialized version is out-of-date compared to the
313 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
314 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
316 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
317 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
318 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
319 /// block_connected() to step towards your best block) upon deserialization before using the
321 pub struct ChannelManager {
322 default_configuration: UserConfig,
323 genesis_hash: Sha256dHash,
324 fee_estimator: Arc<FeeEstimator>,
325 monitor: Arc<ManyChannelMonitor>,
326 chain_monitor: Arc<ChainWatchInterface>,
327 tx_broadcaster: Arc<BroadcasterInterface>,
330 pub(super) latest_block_height: AtomicUsize,
332 latest_block_height: AtomicUsize,
333 last_block_hash: Mutex<Sha256dHash>,
334 secp_ctx: Secp256k1<secp256k1::All>,
337 pub(super) channel_state: Mutex<ChannelHolder>,
339 channel_state: Mutex<ChannelHolder>,
340 our_network_key: SecretKey,
342 pending_events: Mutex<Vec<events::Event>>,
343 /// Used when we have to take a BIG lock to make sure everything is self-consistent.
344 /// Essentially just when we're serializing ourselves out.
345 /// Taken first everywhere where we are making changes before any other locks.
346 total_consistency_lock: RwLock<()>,
348 keys_manager: Arc<KeysInterface>,
353 /// The amount of time we require our counterparty wait to claim their money (ie time between when
354 /// we, or our watchtower, must check for them having broadcast a theft transaction).
355 pub(crate) const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
356 /// The amount of time we're willing to wait to claim money back to us
357 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 6 * 24 * 7;
359 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
360 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
361 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
362 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
363 /// CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
364 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
365 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
367 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
368 // ie that if the next-hop peer fails the HTLC within
369 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
370 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
371 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
372 // LATENCY_GRACE_PERIOD_BLOCKS.
375 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;
377 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
378 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
381 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
383 macro_rules! secp_call {
384 ( $res: expr, $err: expr ) => {
387 Err(_) => return Err($err),
392 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
393 pub struct ChannelDetails {
394 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
395 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
396 /// Note that this means this value is *not* persistent - it can change once during the
397 /// lifetime of the channel.
398 pub channel_id: [u8; 32],
399 /// The position of the funding transaction in the chain. None if the funding transaction has
400 /// not yet been confirmed and the channel fully opened.
401 pub short_channel_id: Option<u64>,
402 /// The node_id of our counterparty
403 pub remote_network_id: PublicKey,
404 /// The value, in satoshis, of this channel as appears in the funding output
405 pub channel_value_satoshis: u64,
406 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
408 /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
409 /// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
410 /// available for inclusion in new outbound HTLCs). This further does not include any pending
411 /// outgoing HTLCs which are awaiting some other resolution to be sent.
412 pub outbound_capacity_msat: u64,
413 /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
414 /// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
415 /// available for inclusion in new inbound HTLCs).
416 /// Note that there are some corner cases not fully handled here, so the actual available
417 /// inbound capacity may be slightly higher than this.
418 pub inbound_capacity_msat: u64,
419 /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
420 /// the peer is connected, and (c) no monitor update failure is pending resolution.
424 macro_rules! handle_error {
425 ($self: ident, $internal: expr) => {
428 Err(MsgHandleErrInternal { err, shutdown_finish }) => {
429 if let Some((shutdown_res, update_option)) = shutdown_finish {
430 $self.finish_force_close_channel(shutdown_res);
431 if let Some(update) = update_option {
432 let mut channel_state = $self.channel_state.lock().unwrap();
433 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
444 macro_rules! break_chan_entry {
445 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
448 Err(ChannelError::Ignore(msg)) => {
449 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
451 Err(ChannelError::Close(msg)) => {
452 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
453 let (channel_id, mut chan) = $entry.remove_entry();
454 if let Some(short_id) = chan.get_short_channel_id() {
455 $channel_state.short_to_id.remove(&short_id);
457 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
459 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"); }
464 macro_rules! try_chan_entry {
465 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
468 Err(ChannelError::Ignore(msg)) => {
469 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
471 Err(ChannelError::Close(msg)) => {
472 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
473 let (channel_id, mut chan) = $entry.remove_entry();
474 if let Some(short_id) = chan.get_short_channel_id() {
475 $channel_state.short_to_id.remove(&short_id);
477 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
479 Err(ChannelError::CloseDelayBroadcast { msg, update }) => {
480 log_error!($self, "Channel {} need to be shutdown but closing transactions not broadcast due to {}", log_bytes!($entry.key()[..]), msg);
481 let (channel_id, mut chan) = $entry.remove_entry();
482 if let Some(short_id) = chan.get_short_channel_id() {
483 $channel_state.short_to_id.remove(&short_id);
485 if let Some(update) = update {
486 if let Err(e) = $self.monitor.add_update_monitor(update.get_funding_txo().unwrap(), update) {
488 // Upstream channel is dead, but we want at least to fail backward HTLCs to save
489 // downstream channels. In case of PermanentFailure, we are not going to be able
490 // to claim back to_remote output on remote commitment transaction. Doesn't
491 // make a difference here, we are concern about HTLCs circuit, not onchain funds.
492 ChannelMonitorUpdateErr::PermanentFailure => {},
493 ChannelMonitorUpdateErr::TemporaryFailure => {},
497 let mut shutdown_res = chan.force_shutdown();
498 if shutdown_res.0.len() >= 1 {
499 log_error!($self, "You have a toxic local commitment transaction {} avaible in channel monitor, read comment in ChannelMonitor::get_latest_local_commitment_txn to be informed of manual action to take", shutdown_res.0[0].txid());
501 shutdown_res.0.clear();
502 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, shutdown_res, $self.get_channel_update(&chan).ok()))
508 macro_rules! handle_monitor_err {
509 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
510 handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, Vec::new(), Vec::new())
512 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
514 ChannelMonitorUpdateErr::PermanentFailure => {
515 log_error!($self, "Closing channel {} due to monitor update PermanentFailure", log_bytes!($entry.key()[..]));
516 let (channel_id, mut chan) = $entry.remove_entry();
517 if let Some(short_id) = chan.get_short_channel_id() {
518 $channel_state.short_to_id.remove(&short_id);
520 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
521 // chain in a confused state! We need to move them into the ChannelMonitor which
522 // will be responsible for failing backwards once things confirm on-chain.
523 // It's ok that we drop $failed_forwards here - at this point we'd rather they
524 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
525 // us bother trying to claim it just to forward on to another peer. If we're
526 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
527 // given up the preimage yet, so might as well just wait until the payment is
528 // retried, avoiding the on-chain fees.
529 let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()));
532 ChannelMonitorUpdateErr::TemporaryFailure => {
533 log_info!($self, "Disabling channel {} due to monitor update TemporaryFailure. On restore will send {} and process {} forwards and {} fails",
534 log_bytes!($entry.key()[..]),
535 if $resend_commitment && $resend_raa {
537 RAACommitmentOrder::CommitmentFirst => { "commitment then RAA" },
538 RAACommitmentOrder::RevokeAndACKFirst => { "RAA then commitment" },
540 } else if $resend_commitment { "commitment" }
541 else if $resend_raa { "RAA" }
543 (&$failed_forwards as &Vec<(PendingForwardHTLCInfo, u64)>).len(),
544 (&$failed_fails as &Vec<(HTLCSource, PaymentHash, HTLCFailReason)>).len());
545 if !$resend_commitment {
546 debug_assert!($action_type == RAACommitmentOrder::RevokeAndACKFirst || !$resend_raa);
549 debug_assert!($action_type == RAACommitmentOrder::CommitmentFirst || !$resend_commitment);
551 $entry.get_mut().monitor_update_failed($resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
552 Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()))
558 macro_rules! return_monitor_err {
559 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
560 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment);
562 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
563 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
567 // Does not break in case of TemporaryFailure!
568 macro_rules! maybe_break_monitor_err {
569 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
570 match (handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment), $err) {
571 (e, ChannelMonitorUpdateErr::PermanentFailure) => {
574 (_, ChannelMonitorUpdateErr::TemporaryFailure) => { },
579 impl ChannelManager {
580 /// Constructs a new ChannelManager to hold several channels and route between them.
582 /// This is the main "logic hub" for all channel-related actions, and implements
583 /// ChannelMessageHandler.
585 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
587 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
588 pub fn new(network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>,keys_manager: Arc<KeysInterface>, config: UserConfig) -> Result<Arc<ChannelManager>, secp256k1::Error> {
589 let secp_ctx = Secp256k1::new();
591 let res = Arc::new(ChannelManager {
592 default_configuration: config.clone(),
593 genesis_hash: genesis_block(network).header.bitcoin_hash(),
594 fee_estimator: feeest.clone(),
595 monitor: monitor.clone(),
599 latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
600 last_block_hash: Mutex::new(Default::default()),
603 channel_state: Mutex::new(ChannelHolder{
604 by_id: HashMap::new(),
605 short_to_id: HashMap::new(),
606 forward_htlcs: HashMap::new(),
607 claimable_htlcs: HashMap::new(),
608 pending_msg_events: Vec::new(),
610 our_network_key: keys_manager.get_node_secret(),
612 pending_events: Mutex::new(Vec::new()),
613 total_consistency_lock: RwLock::new(()),
619 let weak_res = Arc::downgrade(&res);
620 res.chain_monitor.register_listener(weak_res);
624 /// Creates a new outbound channel to the given remote node and with the given value.
626 /// user_id will be provided back as user_channel_id in FundingGenerationReady and
627 /// FundingBroadcastSafe events to allow tracking of which events correspond with which
628 /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
629 /// may wish to avoid using 0 for user_id here.
631 /// If successful, will generate a SendOpenChannel message event, so you should probably poll
632 /// PeerManager::process_events afterwards.
634 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
635 /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
636 pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
637 if channel_value_satoshis < 1000 {
638 return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
641 let channel = Channel::new_outbound(&*self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, Arc::clone(&self.logger), &self.default_configuration)?;
642 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
644 let _ = self.total_consistency_lock.read().unwrap();
645 let mut channel_state = self.channel_state.lock().unwrap();
646 match channel_state.by_id.entry(channel.channel_id()) {
647 hash_map::Entry::Occupied(_) => {
648 if cfg!(feature = "fuzztarget") {
649 return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
651 panic!("RNG is bad???");
654 hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
656 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
657 node_id: their_network_key,
663 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
664 /// more information.
665 pub fn list_channels(&self) -> Vec<ChannelDetails> {
666 let channel_state = self.channel_state.lock().unwrap();
667 let mut res = Vec::with_capacity(channel_state.by_id.len());
668 for (channel_id, channel) in channel_state.by_id.iter() {
669 let (inbound_capacity_msat, outbound_capacity_msat) = channel.get_inbound_outbound_available_balance_msat();
670 res.push(ChannelDetails {
671 channel_id: (*channel_id).clone(),
672 short_channel_id: channel.get_short_channel_id(),
673 remote_network_id: channel.get_their_node_id(),
674 channel_value_satoshis: channel.get_value_satoshis(),
675 inbound_capacity_msat,
676 outbound_capacity_msat,
677 user_id: channel.get_user_id(),
678 is_live: channel.is_live(),
684 /// Gets the list of usable channels, in random order. Useful as an argument to
685 /// Router::get_route to ensure non-announced channels are used.
687 /// These are guaranteed to have their is_live value set to true, see the documentation for
688 /// ChannelDetails::is_live for more info on exactly what the criteria are.
689 pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
690 let channel_state = self.channel_state.lock().unwrap();
691 let mut res = Vec::with_capacity(channel_state.by_id.len());
692 for (channel_id, channel) in channel_state.by_id.iter() {
693 // Note we use is_live here instead of usable which leads to somewhat confused
694 // internal/external nomenclature, but that's ok cause that's probably what the user
695 // really wanted anyway.
696 if channel.is_live() {
697 let (inbound_capacity_msat, outbound_capacity_msat) = channel.get_inbound_outbound_available_balance_msat();
698 res.push(ChannelDetails {
699 channel_id: (*channel_id).clone(),
700 short_channel_id: channel.get_short_channel_id(),
701 remote_network_id: channel.get_their_node_id(),
702 channel_value_satoshis: channel.get_value_satoshis(),
703 inbound_capacity_msat,
704 outbound_capacity_msat,
705 user_id: channel.get_user_id(),
713 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
714 /// will be accepted on the given channel, and after additional timeout/the closing of all
715 /// pending HTLCs, the channel will be closed on chain.
717 /// May generate a SendShutdown message event on success, which should be relayed.
718 pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
719 let _ = self.total_consistency_lock.read().unwrap();
721 let (mut failed_htlcs, chan_option) = {
722 let mut channel_state_lock = self.channel_state.lock().unwrap();
723 let channel_state = channel_state_lock.borrow_parts();
724 match channel_state.by_id.entry(channel_id.clone()) {
725 hash_map::Entry::Occupied(mut chan_entry) => {
726 let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
727 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
728 node_id: chan_entry.get().get_their_node_id(),
731 if chan_entry.get().is_shutdown() {
732 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
733 channel_state.short_to_id.remove(&short_id);
735 (failed_htlcs, Some(chan_entry.remove_entry().1))
736 } else { (failed_htlcs, None) }
738 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
741 for htlc_source in failed_htlcs.drain(..) {
742 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() });
744 let chan_update = if let Some(chan) = chan_option {
745 if let Ok(update) = self.get_channel_update(&chan) {
750 if let Some(update) = chan_update {
751 let mut channel_state = self.channel_state.lock().unwrap();
752 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
761 fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
762 let (local_txn, mut failed_htlcs) = shutdown_res;
763 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
764 for htlc_source in failed_htlcs.drain(..) {
765 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() });
767 for tx in local_txn {
768 self.tx_broadcaster.broadcast_transaction(&tx);
772 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
773 /// the chain and rejecting new HTLCs on the given channel.
774 pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
775 let _ = self.total_consistency_lock.read().unwrap();
778 let mut channel_state_lock = self.channel_state.lock().unwrap();
779 let channel_state = channel_state_lock.borrow_parts();
780 if let Some(chan) = channel_state.by_id.remove(channel_id) {
781 if let Some(short_id) = chan.get_short_channel_id() {
782 channel_state.short_to_id.remove(&short_id);
789 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
790 self.finish_force_close_channel(chan.force_shutdown());
791 if let Ok(update) = self.get_channel_update(&chan) {
792 let mut channel_state = self.channel_state.lock().unwrap();
793 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
799 /// Force close all channels, immediately broadcasting the latest local commitment transaction
800 /// for each to the chain and rejecting new HTLCs on each.
801 pub fn force_close_all_channels(&self) {
802 for chan in self.list_channels() {
803 self.force_close_channel(&chan.channel_id);
807 const ZERO:[u8; 65] = [0; 65];
808 fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
809 macro_rules! return_malformed_err {
810 ($msg: expr, $err_code: expr) => {
812 log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
813 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
814 channel_id: msg.channel_id,
815 htlc_id: msg.htlc_id,
816 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
817 failure_code: $err_code,
818 })), self.channel_state.lock().unwrap());
823 if let Err(_) = msg.onion_routing_packet.public_key {
824 return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
827 let shared_secret = {
828 let mut arr = [0; 32];
829 arr.copy_from_slice(&SharedSecret::new(&msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
832 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(&shared_secret);
834 if msg.onion_routing_packet.version != 0 {
835 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
836 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
837 //the hash doesn't really serve any purpose - in the case of hashing all data, the
838 //receiving node would have to brute force to figure out which version was put in the
839 //packet by the node that send us the message, in the case of hashing the hop_data, the
840 //node knows the HMAC matched, so they already know what is there...
841 return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
844 let mut hmac = HmacEngine::<Sha256>::new(&mu);
845 hmac.input(&msg.onion_routing_packet.hop_data);
846 hmac.input(&msg.payment_hash.0[..]);
847 if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
848 return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
851 let mut channel_state = None;
852 macro_rules! return_err {
853 ($msg: expr, $err_code: expr, $data: expr) => {
855 log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
856 if channel_state.is_none() {
857 channel_state = Some(self.channel_state.lock().unwrap());
859 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
860 channel_id: msg.channel_id,
861 htlc_id: msg.htlc_id,
862 reason: onion_utils::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
863 })), channel_state.unwrap());
868 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
869 let next_hop_data = {
870 let mut decoded = [0; 65];
871 chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
872 match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
874 let error_code = match err {
875 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
876 _ => 0x2000 | 2, // Should never happen
878 return_err!("Unable to decode our hop data", error_code, &[0;0]);
884 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
886 // final_expiry_too_soon
887 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
888 return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
890 // final_incorrect_htlc_amount
891 if next_hop_data.data.amt_to_forward > msg.amount_msat {
892 return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
894 // final_incorrect_cltv_expiry
895 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
896 return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
899 // Note that we could obviously respond immediately with an update_fulfill_htlc
900 // message, however that would leak that we are the recipient of this payment, so
901 // instead we stay symmetric with the forwarding case, only responding (after a
902 // delay) once they've send us a commitment_signed!
904 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
906 payment_hash: msg.payment_hash.clone(),
908 incoming_shared_secret: shared_secret,
909 amt_to_forward: next_hop_data.data.amt_to_forward,
910 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
913 let mut new_packet_data = [0; 20*65];
914 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
915 chacha.process(&ChannelManager::ZERO[..], &mut new_packet_data[19*65..]);
917 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
919 let blinding_factor = {
920 let mut sha = Sha256::engine();
921 sha.input(&new_pubkey.serialize()[..]);
922 sha.input(&shared_secret);
923 Sha256::from_engine(sha).into_inner()
926 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor[..]) {
928 } else { Ok(new_pubkey) };
930 let outgoing_packet = msgs::OnionPacket {
933 hop_data: new_packet_data,
934 hmac: next_hop_data.hmac.clone(),
937 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
938 onion_packet: Some(outgoing_packet),
939 payment_hash: msg.payment_hash.clone(),
940 short_channel_id: next_hop_data.data.short_channel_id,
941 incoming_shared_secret: shared_secret,
942 amt_to_forward: next_hop_data.data.amt_to_forward,
943 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
947 channel_state = Some(self.channel_state.lock().unwrap());
948 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
949 if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
950 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
951 let forwarding_id = match id_option {
952 None => { // unknown_next_peer
953 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
955 Some(id) => id.clone(),
957 if let Some((err, code, chan_update)) = loop {
958 let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
960 // Note that we could technically not return an error yet here and just hope
961 // that the connection is reestablished or monitor updated by the time we get
962 // around to doing the actual forward, but better to fail early if we can and
963 // hopefully an attacker trying to path-trace payments cannot make this occur
964 // on a small/per-node/per-channel scale.
965 if !chan.is_live() { // channel_disabled
966 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
968 if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
969 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
971 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) });
972 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
973 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())));
975 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
976 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())));
978 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
979 // We want to have at least LATENCY_GRACE_PERIOD_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
980 if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS as u32 { // expiry_too_soon
981 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
983 if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
984 break Some(("CLTV expiry is too far in the future", 21, None));
989 let mut res = Vec::with_capacity(8 + 128);
990 if let Some(chan_update) = chan_update {
991 if code == 0x1000 | 11 || code == 0x1000 | 12 {
992 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
994 else if code == 0x1000 | 13 {
995 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
997 else if code == 0x1000 | 20 {
998 res.extend_from_slice(&byte_utils::be16_to_array(chan_update.contents.flags));
1000 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1002 return_err!(err, code, &res[..]);
1007 (pending_forward_info, channel_state.unwrap())
1010 /// only fails if the channel does not yet have an assigned short_id
1011 /// May be called with channel_state already locked!
1012 fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1013 let short_channel_id = match chan.get_short_channel_id() {
1014 None => return Err(HandleError{err: "Channel not yet established", action: None}),
1018 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1020 let unsigned = msgs::UnsignedChannelUpdate {
1021 chain_hash: self.genesis_hash,
1022 short_channel_id: short_channel_id,
1023 timestamp: chan.get_channel_update_count(),
1024 flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1025 cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1026 htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1027 fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1028 fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1029 excess_data: Vec::new(),
1032 let msg_hash = Sha256dHash::hash(&unsigned.encode()[..]);
1033 let sig = self.secp_ctx.sign(&hash_to_message!(&msg_hash[..]), &self.our_network_key);
1035 Ok(msgs::ChannelUpdate {
1041 /// Sends a payment along a given route.
1043 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1044 /// fields for more info.
1046 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1047 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1048 /// next hop knows the preimage to payment_hash they can claim an additional amount as
1049 /// specified in the last hop in the route! Thus, you should probably do your own
1050 /// payment_preimage tracking (which you should already be doing as they represent "proof of
1051 /// payment") and prevent double-sends yourself.
1053 /// May generate a SendHTLCs message event on success, which should be relayed.
1055 /// Raises APIError::RoutError when invalid route or forward parameter
1056 /// (cltv_delta, fee, node public key) is specified.
1057 /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1058 /// (including due to previous monitor update failure or new permanent monitor update failure).
1059 /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1060 /// relevant updates.
1062 /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1063 /// and you may wish to retry via a different route immediately.
1064 /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1065 /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1066 /// the payment via a different route unless you intend to pay twice!
1067 pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1068 if route.hops.len() < 1 || route.hops.len() > 20 {
1069 return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1071 let our_node_id = self.get_our_node_id();
1072 for (idx, hop) in route.hops.iter().enumerate() {
1073 if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1074 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1078 let session_priv = self.keys_manager.get_session_key();
1080 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1082 let onion_keys = secp_call!(onion_utils::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1083 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1084 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height)?;
1085 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1087 let _ = self.total_consistency_lock.read().unwrap();
1089 let err: Result<(), _> = loop {
1090 let mut channel_lock = self.channel_state.lock().unwrap();
1092 let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1093 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1094 Some(id) => id.clone(),
1097 let channel_state = channel_lock.borrow_parts();
1098 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1100 if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1101 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1103 if !chan.get().is_live() {
1104 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1106 break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1107 route: route.clone(),
1108 session_priv: session_priv.clone(),
1109 first_hop_htlc_msat: htlc_msat,
1110 }, onion_packet), channel_state, chan)
1112 Some((update_add, commitment_signed, chan_monitor)) => {
1113 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1114 maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true);
1115 // Note that MonitorUpdateFailed here indicates (per function docs)
1116 // that we will resent the commitment update once we unfree monitor
1117 // updating, so we have to take special care that we don't return
1118 // something else in case we will resend later!
1119 return Err(APIError::MonitorUpdateFailed);
1122 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1123 node_id: route.hops.first().unwrap().pubkey,
1124 updates: msgs::CommitmentUpdate {
1125 update_add_htlcs: vec![update_add],
1126 update_fulfill_htlcs: Vec::new(),
1127 update_fail_htlcs: Vec::new(),
1128 update_fail_malformed_htlcs: Vec::new(),
1136 } else { unreachable!(); }
1140 match handle_error!(self, err) {
1141 Ok(_) => unreachable!(),
1143 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1145 log_error!(self, "Got bad keys: {}!", e.err);
1146 let mut channel_state = self.channel_state.lock().unwrap();
1147 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1148 node_id: route.hops.first().unwrap().pubkey,
1152 Err(APIError::ChannelUnavailable { err: e.err })
1157 /// Call this upon creation of a funding transaction for the given channel.
1159 /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1160 /// or your counterparty can steal your funds!
1162 /// Panics if a funding transaction has already been provided for this channel.
1164 /// May panic if the funding_txo is duplicative with some other channel (note that this should
1165 /// be trivially prevented by using unique funding transaction keys per-channel).
1166 pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1167 let _ = self.total_consistency_lock.read().unwrap();
1169 let (mut chan, msg, chan_monitor) = {
1171 let mut channel_state = self.channel_state.lock().unwrap();
1172 match channel_state.by_id.remove(temporary_channel_id) {
1174 (chan.get_outbound_funding_created(funding_txo)
1175 .map_err(|e| if let ChannelError::Close(msg) = e {
1176 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1177 } else { unreachable!(); })
1183 match handle_error!(self, res) {
1184 Ok(funding_msg) => {
1185 (chan, funding_msg.0, funding_msg.1)
1188 log_error!(self, "Got bad signatures: {}!", e.err);
1189 let mut channel_state = self.channel_state.lock().unwrap();
1190 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1191 node_id: chan.get_their_node_id(),
1198 // Because we have exclusive ownership of the channel here we can release the channel_state
1199 // lock before add_update_monitor
1200 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1202 ChannelMonitorUpdateErr::PermanentFailure => {
1203 match handle_error!(self, Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", *temporary_channel_id, chan.force_shutdown(), None))) {
1205 log_error!(self, "Failed to store ChannelMonitor update for funding tx generation");
1206 let mut channel_state = self.channel_state.lock().unwrap();
1207 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1208 node_id: chan.get_their_node_id(),
1213 Ok(()) => unreachable!(),
1216 ChannelMonitorUpdateErr::TemporaryFailure => {
1217 // Its completely fine to continue with a FundingCreated until the monitor
1218 // update is persisted, as long as we don't generate the FundingBroadcastSafe
1219 // until the monitor has been safely persisted (as funding broadcast is not,
1221 chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
1226 let mut channel_state = self.channel_state.lock().unwrap();
1227 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1228 node_id: chan.get_their_node_id(),
1231 match channel_state.by_id.entry(chan.channel_id()) {
1232 hash_map::Entry::Occupied(_) => {
1233 panic!("Generated duplicate funding txid?");
1235 hash_map::Entry::Vacant(e) => {
1241 fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1242 if !chan.should_announce() { return None }
1244 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1246 Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1248 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1249 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1251 Some(msgs::AnnouncementSignatures {
1252 channel_id: chan.channel_id(),
1253 short_channel_id: chan.get_short_channel_id().unwrap(),
1254 node_signature: our_node_sig,
1255 bitcoin_signature: our_bitcoin_sig,
1259 /// Processes HTLCs which are pending waiting on random forward delay.
1261 /// Should only really ever be called in response to a PendingHTLCsForwardable event.
1262 /// Will likely generate further events.
1263 pub fn process_pending_htlc_forwards(&self) {
1264 let _ = self.total_consistency_lock.read().unwrap();
1266 let mut new_events = Vec::new();
1267 let mut failed_forwards = Vec::new();
1268 let mut handle_errors = Vec::new();
1270 let mut channel_state_lock = self.channel_state.lock().unwrap();
1271 let channel_state = channel_state_lock.borrow_parts();
1273 for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1274 if short_chan_id != 0 {
1275 let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1276 Some(chan_id) => chan_id.clone(),
1278 failed_forwards.reserve(pending_forwards.len());
1279 for forward_info in pending_forwards.drain(..) {
1280 match forward_info {
1281 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info } => {
1282 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1283 short_channel_id: prev_short_channel_id,
1284 htlc_id: prev_htlc_id,
1285 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1287 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1289 HTLCForwardInfo::FailHTLC { .. } => {
1290 // Channel went away before we could fail it. This implies
1291 // the channel is now on chain and our counterparty is
1292 // trying to broadcast the HTLC-Timeout, but that's their
1293 // problem, not ours.
1300 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(forward_chan_id) {
1301 let mut add_htlc_msgs = Vec::new();
1302 let mut fail_htlc_msgs = Vec::new();
1303 for forward_info in pending_forwards.drain(..) {
1304 match forward_info {
1305 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info } => {
1306 log_trace!(self, "Adding HTLC from short id {} with payment_hash {} to channel with short id {} after delay", log_bytes!(forward_info.payment_hash.0), prev_short_channel_id, short_chan_id);
1307 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1308 short_channel_id: prev_short_channel_id,
1309 htlc_id: prev_htlc_id,
1310 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1312 match chan.get_mut().send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, htlc_source.clone(), forward_info.onion_packet.unwrap()) {
1314 if let ChannelError::Ignore(msg) = e {
1315 log_trace!(self, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(forward_info.payment_hash.0), msg);
1317 panic!("Stated return value requirements in send_htlc() were not met");
1319 let chan_update = self.get_channel_update(chan.get()).unwrap();
1320 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1325 Some(msg) => { add_htlc_msgs.push(msg); },
1327 // Nothing to do here...we're waiting on a remote
1328 // revoke_and_ack before we can add anymore HTLCs. The Channel
1329 // will automatically handle building the update_add_htlc and
1330 // commitment_signed messages when we can.
1331 // TODO: Do some kind of timer to set the channel as !is_live()
1332 // as we don't really want others relying on us relaying through
1333 // this channel currently :/.
1339 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
1340 log_trace!(self, "Failing HTLC back to channel with short id {} after delay", short_chan_id);
1341 match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet) {
1343 if let ChannelError::Ignore(msg) = e {
1344 log_trace!(self, "Failed to fail backwards to short_id {}: {}", short_chan_id, msg);
1346 panic!("Stated return value requirements in get_update_fail_htlc() were not met");
1348 // fail-backs are best-effort, we probably already have one
1349 // pending, and if not that's OK, if not, the channel is on
1350 // the chain and sending the HTLC-Timeout is their problem.
1353 Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
1355 // Nothing to do here...we're waiting on a remote
1356 // revoke_and_ack before we can update the commitment
1357 // transaction. The Channel will automatically handle
1358 // building the update_fail_htlc and commitment_signed
1359 // messages when we can.
1360 // We don't need any kind of timer here as they should fail
1361 // the channel onto the chain if they can't get our
1362 // update_fail_htlc in time, it's not our problem.
1369 if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
1370 let (commitment_msg, monitor) = match chan.get_mut().send_commitment() {
1373 // We surely failed send_commitment due to bad keys, in that case
1374 // close channel and then send error message to peer.
1375 let their_node_id = chan.get().get_their_node_id();
1376 let err: Result<(), _> = match e {
1377 ChannelError::Ignore(_) => {
1378 panic!("Stated return value requirements in send_commitment() were not met");
1380 ChannelError::Close(msg) => {
1381 log_trace!(self, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
1382 let (channel_id, mut channel) = chan.remove_entry();
1383 if let Some(short_id) = channel.get_short_channel_id() {
1384 channel_state.short_to_id.remove(&short_id);
1386 Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, channel.force_shutdown(), self.get_channel_update(&channel).ok()))
1388 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"); }
1390 match handle_error!(self, err) {
1391 Ok(_) => unreachable!(),
1393 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1395 log_error!(self, "Got bad keys: {}!", e.err);
1396 let mut channel_state = self.channel_state.lock().unwrap();
1397 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1398 node_id: their_node_id,
1407 if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1408 handle_errors.push((chan.get().get_their_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
1411 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1412 node_id: chan.get().get_their_node_id(),
1413 updates: msgs::CommitmentUpdate {
1414 update_add_htlcs: add_htlc_msgs,
1415 update_fulfill_htlcs: Vec::new(),
1416 update_fail_htlcs: fail_htlc_msgs,
1417 update_fail_malformed_htlcs: Vec::new(),
1419 commitment_signed: commitment_msg,
1427 for forward_info in pending_forwards.drain(..) {
1428 match forward_info {
1429 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info } => {
1430 let prev_hop_data = HTLCPreviousHopData {
1431 short_channel_id: prev_short_channel_id,
1432 htlc_id: prev_htlc_id,
1433 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1435 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1436 hash_map::Entry::Occupied(mut entry) => entry.get_mut().push((forward_info.amt_to_forward, prev_hop_data)),
1437 hash_map::Entry::Vacant(entry) => { entry.insert(vec![(forward_info.amt_to_forward, prev_hop_data)]); },
1439 new_events.push(events::Event::PaymentReceived {
1440 payment_hash: forward_info.payment_hash,
1441 amt: forward_info.amt_to_forward,
1444 HTLCForwardInfo::FailHTLC { .. } => {
1445 panic!("Got pending fail of our own HTLC");
1453 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1455 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1456 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() }),
1460 for (their_node_id, err) in handle_errors.drain(..) {
1461 match handle_error!(self, err) {
1464 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1466 let mut channel_state = self.channel_state.lock().unwrap();
1467 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1468 node_id: their_node_id,
1476 if new_events.is_empty() { return }
1477 let mut events = self.pending_events.lock().unwrap();
1478 events.append(&mut new_events);
1481 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1482 /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
1483 /// along the path (including in our own channel on which we received it).
1484 /// Returns false if no payment was found to fail backwards, true if the process of failing the
1485 /// HTLC backwards has been started.
1486 pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) -> bool {
1487 let _ = self.total_consistency_lock.read().unwrap();
1489 let mut channel_state = Some(self.channel_state.lock().unwrap());
1490 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1491 if let Some(mut sources) = removed_source {
1492 for (recvd_value, htlc_with_hash) in sources.drain(..) {
1493 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1494 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1495 HTLCSource::PreviousHopData(htlc_with_hash), payment_hash,
1496 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(recvd_value).to_vec() });
1502 /// Fails an HTLC backwards to the sender of it to us.
1503 /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1504 /// There are several callsites that do stupid things like loop over a list of payment_hashes
1505 /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1506 /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1507 /// still-available channels.
1508 fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1509 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
1510 //identify whether we sent it or not based on the (I presume) very different runtime
1511 //between the branches here. We should make this async and move it into the forward HTLCs
1514 HTLCSource::OutboundRoute { ref route, .. } => {
1515 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1516 mem::drop(channel_state_lock);
1517 match &onion_error {
1518 &HTLCFailReason::ErrorPacket { ref err } => {
1520 let (channel_update, payment_retryable, onion_error_code) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
1522 let (channel_update, payment_retryable, _) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
1523 // TODO: If we decided to blame ourselves (or one of our channels) in
1524 // process_onion_failure we should close that channel as it implies our
1525 // next-hop is needlessly blaming us!
1526 if let Some(update) = channel_update {
1527 self.channel_state.lock().unwrap().pending_msg_events.push(
1528 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1533 self.pending_events.lock().unwrap().push(
1534 events::Event::PaymentFailed {
1535 payment_hash: payment_hash.clone(),
1536 rejected_by_dest: !payment_retryable,
1538 error_code: onion_error_code
1542 &HTLCFailReason::Reason {
1546 // we get a fail_malformed_htlc from the first hop
1547 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1548 // failures here, but that would be insufficient as Router::get_route
1549 // generally ignores its view of our own channels as we provide them via
1551 // TODO: For non-temporary failures, we really should be closing the
1552 // channel here as we apparently can't relay through them anyway.
1553 self.pending_events.lock().unwrap().push(
1554 events::Event::PaymentFailed {
1555 payment_hash: payment_hash.clone(),
1556 rejected_by_dest: route.hops.len() == 1,
1558 error_code: Some(*failure_code),
1564 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1565 let err_packet = match onion_error {
1566 HTLCFailReason::Reason { failure_code, data } => {
1567 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1568 let packet = onion_utils::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1569 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1571 HTLCFailReason::ErrorPacket { err } => {
1572 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1573 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1577 let mut forward_event = None;
1578 if channel_state_lock.forward_htlcs.is_empty() {
1579 forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
1581 match channel_state_lock.forward_htlcs.entry(short_channel_id) {
1582 hash_map::Entry::Occupied(mut entry) => {
1583 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id, err_packet });
1585 hash_map::Entry::Vacant(entry) => {
1586 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id, err_packet }));
1589 mem::drop(channel_state_lock);
1590 if let Some(time) = forward_event {
1591 let mut pending_events = self.pending_events.lock().unwrap();
1592 pending_events.push(events::Event::PendingHTLCsForwardable {
1593 time_forwardable: time
1600 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1601 /// generating message events for the net layer to claim the payment, if possible. Thus, you
1602 /// should probably kick the net layer to go send messages if this returns true!
1604 /// May panic if called except in response to a PaymentReceived event.
1605 pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1606 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1608 let _ = self.total_consistency_lock.read().unwrap();
1610 let mut channel_state = Some(self.channel_state.lock().unwrap());
1611 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1612 if let Some(mut sources) = removed_source {
1613 // TODO: We should require the user specify the expected amount so that we can claim
1614 // only payments for the correct amount, and reject payments for incorrect amounts
1615 // (which are probably middle nodes probing to break our privacy).
1616 for (_, htlc_with_hash) in sources.drain(..) {
1617 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1618 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1623 fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1624 let (their_node_id, err) = loop {
1626 HTLCSource::OutboundRoute { .. } => {
1627 mem::drop(channel_state_lock);
1628 let mut pending_events = self.pending_events.lock().unwrap();
1629 pending_events.push(events::Event::PaymentSent {
1633 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1634 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1635 let channel_state = channel_state_lock.borrow_parts();
1637 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1638 Some(chan_id) => chan_id.clone(),
1640 // TODO: There is probably a channel manager somewhere that needs to
1641 // learn the preimage as the channel already hit the chain and that's
1642 // why it's missing.
1647 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(chan_id) {
1648 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
1649 match chan.get_mut().get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1650 Ok((msgs, monitor_option)) => {
1651 if let Some(chan_monitor) = monitor_option {
1652 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1653 if was_frozen_for_monitor {
1654 assert!(msgs.is_none());
1656 break (chan.get().get_their_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, msgs.is_some()));
1660 if let Some((msg, commitment_signed)) = msgs {
1661 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1662 node_id: chan.get().get_their_node_id(),
1663 updates: msgs::CommitmentUpdate {
1664 update_add_htlcs: Vec::new(),
1665 update_fulfill_htlcs: vec![msg],
1666 update_fail_htlcs: Vec::new(),
1667 update_fail_malformed_htlcs: Vec::new(),
1675 // TODO: There is probably a channel manager somewhere that needs to
1676 // learn the preimage as the channel may be about to hit the chain.
1677 //TODO: Do something with e?
1681 } else { unreachable!(); }
1687 match handle_error!(self, err) {
1690 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1692 let mut channel_state = self.channel_state.lock().unwrap();
1693 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1694 node_id: their_node_id,
1702 /// Gets the node_id held by this ChannelManager
1703 pub fn get_our_node_id(&self) -> PublicKey {
1704 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1707 /// Used to restore channels to normal operation after a
1708 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1710 pub fn test_restore_channel_monitor(&self) {
1711 let mut close_results = Vec::new();
1712 let mut htlc_forwards = Vec::new();
1713 let mut htlc_failures = Vec::new();
1714 let mut pending_events = Vec::new();
1715 let _ = self.total_consistency_lock.read().unwrap();
1718 let mut channel_lock = self.channel_state.lock().unwrap();
1719 let channel_state = channel_lock.borrow_parts();
1720 let short_to_id = channel_state.short_to_id;
1721 let pending_msg_events = channel_state.pending_msg_events;
1722 channel_state.by_id.retain(|_, channel| {
1723 if channel.is_awaiting_monitor_update() {
1724 let chan_monitor = channel.channel_monitor();
1725 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1727 ChannelMonitorUpdateErr::PermanentFailure => {
1728 // TODO: There may be some pending HTLCs that we intended to fail
1729 // backwards when a monitor update failed. We should make sure
1730 // knowledge of those gets moved into the appropriate in-memory
1731 // ChannelMonitor and they get failed backwards once we get
1732 // on-chain confirmations.
1733 // Note I think #198 addresses this, so once it's merged a test
1734 // should be written.
1735 if let Some(short_id) = channel.get_short_channel_id() {
1736 short_to_id.remove(&short_id);
1738 close_results.push(channel.force_shutdown());
1739 if let Ok(update) = self.get_channel_update(&channel) {
1740 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1746 ChannelMonitorUpdateErr::TemporaryFailure => true,
1749 let (raa, commitment_update, order, pending_forwards, mut pending_failures, needs_broadcast_safe, funding_locked) = channel.monitor_updating_restored();
1750 if !pending_forwards.is_empty() {
1751 htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1753 htlc_failures.append(&mut pending_failures);
1755 macro_rules! handle_cs { () => {
1756 if let Some(update) = commitment_update {
1757 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1758 node_id: channel.get_their_node_id(),
1763 macro_rules! handle_raa { () => {
1764 if let Some(revoke_and_ack) = raa {
1765 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1766 node_id: channel.get_their_node_id(),
1767 msg: revoke_and_ack,
1772 RAACommitmentOrder::CommitmentFirst => {
1776 RAACommitmentOrder::RevokeAndACKFirst => {
1781 if needs_broadcast_safe {
1782 pending_events.push(events::Event::FundingBroadcastSafe {
1783 funding_txo: channel.get_funding_txo().unwrap(),
1784 user_channel_id: channel.get_user_id(),
1787 if let Some(msg) = funding_locked {
1788 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
1789 node_id: channel.get_their_node_id(),
1792 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
1793 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1794 node_id: channel.get_their_node_id(),
1795 msg: announcement_sigs,
1798 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
1806 self.pending_events.lock().unwrap().append(&mut pending_events);
1808 for failure in htlc_failures.drain(..) {
1809 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1811 self.forward_htlcs(&mut htlc_forwards[..]);
1813 for res in close_results.drain(..) {
1814 self.finish_force_close_channel(res);
1818 fn internal_open_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1819 if msg.chain_hash != self.genesis_hash {
1820 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1823 let channel = Channel::new_from_req(&*self.fee_estimator, &self.keys_manager, their_node_id.clone(), their_local_features, msg, 0, Arc::clone(&self.logger), &self.default_configuration)
1824 .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1825 let mut channel_state_lock = self.channel_state.lock().unwrap();
1826 let channel_state = channel_state_lock.borrow_parts();
1827 match channel_state.by_id.entry(channel.channel_id()) {
1828 hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1829 hash_map::Entry::Vacant(entry) => {
1830 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1831 node_id: their_node_id.clone(),
1832 msg: channel.get_accept_channel(),
1834 entry.insert(channel);
1840 fn internal_accept_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1841 let (value, output_script, user_id) = {
1842 let mut channel_lock = self.channel_state.lock().unwrap();
1843 let channel_state = channel_lock.borrow_parts();
1844 match channel_state.by_id.entry(msg.temporary_channel_id) {
1845 hash_map::Entry::Occupied(mut chan) => {
1846 if chan.get().get_their_node_id() != *their_node_id {
1847 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1848 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1850 try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration, their_local_features), channel_state, chan);
1851 (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1853 //TODO: same as above
1854 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1857 let mut pending_events = self.pending_events.lock().unwrap();
1858 pending_events.push(events::Event::FundingGenerationReady {
1859 temporary_channel_id: msg.temporary_channel_id,
1860 channel_value_satoshis: value,
1861 output_script: output_script,
1862 user_channel_id: user_id,
1867 fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1868 let ((funding_msg, monitor_update), mut chan) = {
1869 let mut channel_lock = self.channel_state.lock().unwrap();
1870 let channel_state = channel_lock.borrow_parts();
1871 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1872 hash_map::Entry::Occupied(mut chan) => {
1873 if chan.get().get_their_node_id() != *their_node_id {
1874 //TODO: here and below MsgHandleErrInternal, #153 case
1875 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1877 (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1879 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1882 // Because we have exclusive ownership of the channel here we can release the channel_state
1883 // lock before add_update_monitor
1884 if let Err(e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1886 ChannelMonitorUpdateErr::PermanentFailure => {
1887 // Note that we reply with the new channel_id in error messages if we gave up on the
1888 // channel, not the temporary_channel_id. This is compatible with ourselves, but the
1889 // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
1890 // any messages referencing a previously-closed channel anyway.
1891 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", funding_msg.channel_id, chan.force_shutdown(), None));
1893 ChannelMonitorUpdateErr::TemporaryFailure => {
1894 // There's no problem signing a counterparty's funding transaction if our monitor
1895 // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
1896 // accepted payment from yet. We do, however, need to wait to send our funding_locked
1897 // until we have persisted our monitor.
1898 chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
1902 let mut channel_state_lock = self.channel_state.lock().unwrap();
1903 let channel_state = channel_state_lock.borrow_parts();
1904 match channel_state.by_id.entry(funding_msg.channel_id) {
1905 hash_map::Entry::Occupied(_) => {
1906 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1908 hash_map::Entry::Vacant(e) => {
1909 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1910 node_id: their_node_id.clone(),
1919 fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1920 let (funding_txo, user_id) = {
1921 let mut channel_lock = self.channel_state.lock().unwrap();
1922 let channel_state = channel_lock.borrow_parts();
1923 match channel_state.by_id.entry(msg.channel_id) {
1924 hash_map::Entry::Occupied(mut chan) => {
1925 if chan.get().get_their_node_id() != *their_node_id {
1926 //TODO: here and below MsgHandleErrInternal, #153 case
1927 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1929 let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1930 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1931 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
1933 (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1935 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1938 let mut pending_events = self.pending_events.lock().unwrap();
1939 pending_events.push(events::Event::FundingBroadcastSafe {
1940 funding_txo: funding_txo,
1941 user_channel_id: user_id,
1946 fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1947 let mut channel_state_lock = self.channel_state.lock().unwrap();
1948 let channel_state = channel_state_lock.borrow_parts();
1949 match channel_state.by_id.entry(msg.channel_id) {
1950 hash_map::Entry::Occupied(mut chan) => {
1951 if chan.get().get_their_node_id() != *their_node_id {
1952 //TODO: here and below MsgHandleErrInternal, #153 case
1953 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1955 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1956 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1957 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1958 node_id: their_node_id.clone(),
1959 msg: announcement_sigs,
1964 hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1968 fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1969 let (mut dropped_htlcs, chan_option) = {
1970 let mut channel_state_lock = self.channel_state.lock().unwrap();
1971 let channel_state = channel_state_lock.borrow_parts();
1973 match channel_state.by_id.entry(msg.channel_id.clone()) {
1974 hash_map::Entry::Occupied(mut chan_entry) => {
1975 if chan_entry.get().get_their_node_id() != *their_node_id {
1976 //TODO: here and below MsgHandleErrInternal, #153 case
1977 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1979 let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1980 if let Some(msg) = shutdown {
1981 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1982 node_id: their_node_id.clone(),
1986 if let Some(msg) = closing_signed {
1987 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1988 node_id: their_node_id.clone(),
1992 if chan_entry.get().is_shutdown() {
1993 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1994 channel_state.short_to_id.remove(&short_id);
1996 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1997 } else { (dropped_htlcs, None) }
1999 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2002 for htlc_source in dropped_htlcs.drain(..) {
2003 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() });
2005 if let Some(chan) = chan_option {
2006 if let Ok(update) = self.get_channel_update(&chan) {
2007 let mut channel_state = self.channel_state.lock().unwrap();
2008 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2016 fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
2017 let (tx, chan_option) = {
2018 let mut channel_state_lock = self.channel_state.lock().unwrap();
2019 let channel_state = channel_state_lock.borrow_parts();
2020 match channel_state.by_id.entry(msg.channel_id.clone()) {
2021 hash_map::Entry::Occupied(mut chan_entry) => {
2022 if chan_entry.get().get_their_node_id() != *their_node_id {
2023 //TODO: here and below MsgHandleErrInternal, #153 case
2024 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2026 let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
2027 if let Some(msg) = closing_signed {
2028 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2029 node_id: their_node_id.clone(),
2034 // We're done with this channel, we've got a signed closing transaction and
2035 // will send the closing_signed back to the remote peer upon return. This
2036 // also implies there are no pending HTLCs left on the channel, so we can
2037 // fully delete it from tracking (the channel monitor is still around to
2038 // watch for old state broadcasts)!
2039 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2040 channel_state.short_to_id.remove(&short_id);
2042 (tx, Some(chan_entry.remove_entry().1))
2043 } else { (tx, None) }
2045 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2048 if let Some(broadcast_tx) = tx {
2049 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2051 if let Some(chan) = chan_option {
2052 if let Ok(update) = self.get_channel_update(&chan) {
2053 let mut channel_state = self.channel_state.lock().unwrap();
2054 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2062 fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2063 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2064 //determine the state of the payment based on our response/if we forward anything/the time
2065 //we take to respond. We should take care to avoid allowing such an attack.
2067 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2068 //us repeatedly garbled in different ways, and compare our error messages, which are
2069 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
2070 //but we should prevent it anyway.
2072 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2073 let channel_state = channel_state_lock.borrow_parts();
2075 match channel_state.by_id.entry(msg.channel_id) {
2076 hash_map::Entry::Occupied(mut chan) => {
2077 if chan.get().get_their_node_id() != *their_node_id {
2078 //TODO: here MsgHandleErrInternal, #153 case
2079 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2081 if !chan.get().is_usable() {
2082 // If the update_add is completely bogus, the call will Err and we will close,
2083 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2084 // want to reject the new HTLC and fail it backwards instead of forwarding.
2085 if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2086 let chan_update = self.get_channel_update(chan.get());
2087 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2088 channel_id: msg.channel_id,
2089 htlc_id: msg.htlc_id,
2090 reason: if let Ok(update) = chan_update {
2091 // TODO: Note that |20 is defined as "channel FROM the processing
2092 // node has been disabled" (emphasis mine), which seems to imply
2093 // that we can't return |20 for an inbound channel being disabled.
2094 // This probably needs a spec update but should definitely be
2096 onion_utils::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &{
2097 let mut res = Vec::with_capacity(8 + 128);
2098 res.extend_from_slice(&byte_utils::be16_to_array(update.contents.flags));
2099 res.extend_from_slice(&update.encode_with_len()[..]);
2103 // This can only happen if the channel isn't in the fully-funded
2104 // state yet, implying our counterparty is trying to route payments
2105 // over the channel back to themselves (cause no one else should
2106 // know the short_id is a lightning channel yet). We should have no
2107 // problem just calling this unknown_next_peer
2108 onion_utils::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2113 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2115 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2120 fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2121 let mut channel_lock = self.channel_state.lock().unwrap();
2123 let channel_state = channel_lock.borrow_parts();
2124 match channel_state.by_id.entry(msg.channel_id) {
2125 hash_map::Entry::Occupied(mut chan) => {
2126 if chan.get().get_their_node_id() != *their_node_id {
2127 //TODO: here and below MsgHandleErrInternal, #153 case
2128 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2130 try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2132 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2135 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2139 fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2140 let mut channel_lock = self.channel_state.lock().unwrap();
2141 let channel_state = channel_lock.borrow_parts();
2142 match channel_state.by_id.entry(msg.channel_id) {
2143 hash_map::Entry::Occupied(mut chan) => {
2144 if chan.get().get_their_node_id() != *their_node_id {
2145 //TODO: here and below MsgHandleErrInternal, #153 case
2146 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2148 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2150 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2155 fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2156 let mut channel_lock = self.channel_state.lock().unwrap();
2157 let channel_state = channel_lock.borrow_parts();
2158 match channel_state.by_id.entry(msg.channel_id) {
2159 hash_map::Entry::Occupied(mut chan) => {
2160 if chan.get().get_their_node_id() != *their_node_id {
2161 //TODO: here and below MsgHandleErrInternal, #153 case
2162 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2164 if (msg.failure_code & 0x8000) == 0 {
2165 try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2167 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);
2170 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2174 fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2175 let mut channel_state_lock = self.channel_state.lock().unwrap();
2176 let channel_state = channel_state_lock.borrow_parts();
2177 match channel_state.by_id.entry(msg.channel_id) {
2178 hash_map::Entry::Occupied(mut chan) => {
2179 if chan.get().get_their_node_id() != *their_node_id {
2180 //TODO: here and below MsgHandleErrInternal, #153 case
2181 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2183 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2184 try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2185 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2186 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some());
2187 //TODO: Rebroadcast closing_signed if present on monitor update restoration
2189 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2190 node_id: their_node_id.clone(),
2191 msg: revoke_and_ack,
2193 if let Some(msg) = commitment_signed {
2194 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2195 node_id: their_node_id.clone(),
2196 updates: msgs::CommitmentUpdate {
2197 update_add_htlcs: Vec::new(),
2198 update_fulfill_htlcs: Vec::new(),
2199 update_fail_htlcs: Vec::new(),
2200 update_fail_malformed_htlcs: Vec::new(),
2202 commitment_signed: msg,
2206 if let Some(msg) = closing_signed {
2207 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2208 node_id: their_node_id.clone(),
2214 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2219 fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2220 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2221 let mut forward_event = None;
2222 if !pending_forwards.is_empty() {
2223 let mut channel_state = self.channel_state.lock().unwrap();
2224 if channel_state.forward_htlcs.is_empty() {
2225 forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS))
2227 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2228 match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2229 hash_map::Entry::Occupied(mut entry) => {
2230 entry.get_mut().push(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info });
2232 hash_map::Entry::Vacant(entry) => {
2233 entry.insert(vec!(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info }));
2238 match forward_event {
2240 let mut pending_events = self.pending_events.lock().unwrap();
2241 pending_events.push(events::Event::PendingHTLCsForwardable {
2242 time_forwardable: time
2250 fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2251 let (pending_forwards, mut pending_failures, short_channel_id) = {
2252 let mut channel_state_lock = self.channel_state.lock().unwrap();
2253 let channel_state = channel_state_lock.borrow_parts();
2254 match channel_state.by_id.entry(msg.channel_id) {
2255 hash_map::Entry::Occupied(mut chan) => {
2256 if chan.get().get_their_node_id() != *their_node_id {
2257 //TODO: here and below MsgHandleErrInternal, #153 case
2258 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2260 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2261 let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2262 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2263 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2264 if was_frozen_for_monitor {
2265 assert!(commitment_update.is_none() && closing_signed.is_none() && pending_forwards.is_empty() && pending_failures.is_empty());
2266 return Err(MsgHandleErrInternal::ignore_no_close("Previous monitor update failure prevented responses to RAA"));
2268 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, commitment_update.is_some(), pending_forwards, pending_failures);
2271 if let Some(updates) = commitment_update {
2272 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2273 node_id: their_node_id.clone(),
2277 if let Some(msg) = closing_signed {
2278 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2279 node_id: their_node_id.clone(),
2283 (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2285 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2288 for failure in pending_failures.drain(..) {
2289 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2291 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2296 fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2297 let mut channel_lock = self.channel_state.lock().unwrap();
2298 let channel_state = channel_lock.borrow_parts();
2299 match channel_state.by_id.entry(msg.channel_id) {
2300 hash_map::Entry::Occupied(mut chan) => {
2301 if chan.get().get_their_node_id() != *their_node_id {
2302 //TODO: here and below MsgHandleErrInternal, #153 case
2303 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2305 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2307 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2312 fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2313 let mut channel_state_lock = self.channel_state.lock().unwrap();
2314 let channel_state = channel_state_lock.borrow_parts();
2316 match channel_state.by_id.entry(msg.channel_id) {
2317 hash_map::Entry::Occupied(mut chan) => {
2318 if chan.get().get_their_node_id() != *their_node_id {
2319 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2321 if !chan.get().is_usable() {
2322 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2325 let our_node_id = self.get_our_node_id();
2326 let (announcement, our_bitcoin_sig) =
2327 try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2329 let were_node_one = announcement.node_id_1 == our_node_id;
2330 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
2331 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2332 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2333 try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2336 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2338 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2339 msg: msgs::ChannelAnnouncement {
2340 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2341 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2342 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2343 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2344 contents: announcement,
2346 update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2349 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2354 fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2355 let mut channel_state_lock = self.channel_state.lock().unwrap();
2356 let channel_state = channel_state_lock.borrow_parts();
2358 match channel_state.by_id.entry(msg.channel_id) {
2359 hash_map::Entry::Occupied(mut chan) => {
2360 if chan.get().get_their_node_id() != *their_node_id {
2361 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2363 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2364 try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2365 if let Some(monitor) = channel_monitor {
2366 if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2367 // channel_reestablish doesn't guarantee the order it returns is sensical
2368 // for the messages it returns, but if we're setting what messages to
2369 // re-transmit on monitor update success, we need to make sure it is sane.
2370 if revoke_and_ack.is_none() {
2371 order = RAACommitmentOrder::CommitmentFirst;
2373 if commitment_update.is_none() {
2374 order = RAACommitmentOrder::RevokeAndACKFirst;
2376 return_monitor_err!(self, e, channel_state, chan, order, revoke_and_ack.is_some(), commitment_update.is_some());
2377 //TODO: Resend the funding_locked if needed once we get the monitor running again
2380 if let Some(msg) = funding_locked {
2381 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2382 node_id: their_node_id.clone(),
2386 macro_rules! send_raa { () => {
2387 if let Some(msg) = revoke_and_ack {
2388 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2389 node_id: their_node_id.clone(),
2394 macro_rules! send_cu { () => {
2395 if let Some(updates) = commitment_update {
2396 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2397 node_id: their_node_id.clone(),
2403 RAACommitmentOrder::RevokeAndACKFirst => {
2407 RAACommitmentOrder::CommitmentFirst => {
2412 if let Some(msg) = shutdown {
2413 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2414 node_id: their_node_id.clone(),
2420 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2424 /// Begin Update fee process. Allowed only on an outbound channel.
2425 /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2426 /// PeerManager::process_events afterwards.
2427 /// Note: This API is likely to change!
2429 pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2430 let _ = self.total_consistency_lock.read().unwrap();
2432 let err: Result<(), _> = loop {
2433 let mut channel_state_lock = self.channel_state.lock().unwrap();
2434 let channel_state = channel_state_lock.borrow_parts();
2436 match channel_state.by_id.entry(channel_id) {
2437 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2438 hash_map::Entry::Occupied(mut chan) => {
2439 if !chan.get().is_outbound() {
2440 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2442 if chan.get().is_awaiting_monitor_update() {
2443 return Err(APIError::MonitorUpdateFailed);
2445 if !chan.get().is_live() {
2446 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2448 their_node_id = chan.get().get_their_node_id();
2449 if let Some((update_fee, commitment_signed, chan_monitor)) =
2450 break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2452 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2455 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2456 node_id: chan.get().get_their_node_id(),
2457 updates: msgs::CommitmentUpdate {
2458 update_add_htlcs: Vec::new(),
2459 update_fulfill_htlcs: Vec::new(),
2460 update_fail_htlcs: Vec::new(),
2461 update_fail_malformed_htlcs: Vec::new(),
2462 update_fee: Some(update_fee),
2472 match handle_error!(self, err) {
2473 Ok(_) => unreachable!(),
2475 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2477 log_error!(self, "Got bad keys: {}!", e.err);
2478 let mut channel_state = self.channel_state.lock().unwrap();
2479 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2480 node_id: their_node_id,
2484 Err(APIError::APIMisuseError { err: e.err })
2490 impl events::MessageSendEventsProvider for ChannelManager {
2491 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2492 // TODO: Event release to users and serialization is currently race-y: it's very easy for a
2493 // user to serialize a ChannelManager with pending events in it and lose those events on
2494 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2496 //TODO: This behavior should be documented.
2497 for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2498 if let Some(preimage) = htlc_update.payment_preimage {
2499 log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2500 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2502 log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2503 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() });
2508 let mut ret = Vec::new();
2509 let mut channel_state = self.channel_state.lock().unwrap();
2510 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2515 impl events::EventsProvider for ChannelManager {
2516 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2517 // TODO: Event release to users and serialization is currently race-y: it's very easy for a
2518 // user to serialize a ChannelManager with pending events in it and lose those events on
2519 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2521 //TODO: This behavior should be documented.
2522 for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2523 if let Some(preimage) = htlc_update.payment_preimage {
2524 log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2525 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2527 log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2528 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() });
2533 let mut ret = Vec::new();
2534 let mut pending_events = self.pending_events.lock().unwrap();
2535 mem::swap(&mut ret, &mut *pending_events);
2540 impl ChainListener for ChannelManager {
2541 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2542 let header_hash = header.bitcoin_hash();
2543 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2544 let _ = self.total_consistency_lock.read().unwrap();
2545 let mut failed_channels = Vec::new();
2547 let mut channel_lock = self.channel_state.lock().unwrap();
2548 let channel_state = channel_lock.borrow_parts();
2549 let short_to_id = channel_state.short_to_id;
2550 let pending_msg_events = channel_state.pending_msg_events;
2551 channel_state.by_id.retain(|_, channel| {
2552 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2553 if let Ok(Some(funding_locked)) = chan_res {
2554 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2555 node_id: channel.get_their_node_id(),
2556 msg: funding_locked,
2558 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2559 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2560 node_id: channel.get_their_node_id(),
2561 msg: announcement_sigs,
2564 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2565 } else if let Err(e) = chan_res {
2566 pending_msg_events.push(events::MessageSendEvent::HandleError {
2567 node_id: channel.get_their_node_id(),
2568 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2572 if let Some(funding_txo) = channel.get_funding_txo() {
2573 for tx in txn_matched {
2574 for inp in tx.input.iter() {
2575 if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2576 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()));
2577 if let Some(short_id) = channel.get_short_channel_id() {
2578 short_to_id.remove(&short_id);
2580 // It looks like our counterparty went on-chain. We go ahead and
2581 // broadcast our latest local state as well here, just in case its
2582 // some kind of SPV attack, though we expect these to be dropped.
2583 failed_channels.push(channel.force_shutdown());
2584 if let Ok(update) = self.get_channel_update(&channel) {
2585 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2594 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2595 if let Some(short_id) = channel.get_short_channel_id() {
2596 short_to_id.remove(&short_id);
2598 failed_channels.push(channel.force_shutdown());
2599 // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2600 // the latest local tx for us, so we should skip that here (it doesn't really
2601 // hurt anything, but does make tests a bit simpler).
2602 failed_channels.last_mut().unwrap().0 = Vec::new();
2603 if let Ok(update) = self.get_channel_update(&channel) {
2604 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2613 for failure in failed_channels.drain(..) {
2614 self.finish_force_close_channel(failure);
2616 self.latest_block_height.store(height as usize, Ordering::Release);
2617 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2620 /// We force-close the channel without letting our counterparty participate in the shutdown
2621 fn block_disconnected(&self, header: &BlockHeader, _: u32) {
2622 let _ = self.total_consistency_lock.read().unwrap();
2623 let mut failed_channels = Vec::new();
2625 let mut channel_lock = self.channel_state.lock().unwrap();
2626 let channel_state = channel_lock.borrow_parts();
2627 let short_to_id = channel_state.short_to_id;
2628 let pending_msg_events = channel_state.pending_msg_events;
2629 channel_state.by_id.retain(|_, v| {
2630 if v.block_disconnected(header) {
2631 if let Some(short_id) = v.get_short_channel_id() {
2632 short_to_id.remove(&short_id);
2634 failed_channels.push(v.force_shutdown());
2635 if let Ok(update) = self.get_channel_update(&v) {
2636 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2646 for failure in failed_channels.drain(..) {
2647 self.finish_force_close_channel(failure);
2649 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2650 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2654 impl ChannelMessageHandler for ChannelManager {
2655 //TODO: Handle errors and close channel (or so)
2656 fn handle_open_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2657 let _ = self.total_consistency_lock.read().unwrap();
2658 handle_error!(self, self.internal_open_channel(their_node_id, their_local_features, msg))
2661 fn handle_accept_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2662 let _ = self.total_consistency_lock.read().unwrap();
2663 handle_error!(self, self.internal_accept_channel(their_node_id, their_local_features, msg))
2666 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2667 let _ = self.total_consistency_lock.read().unwrap();
2668 handle_error!(self, self.internal_funding_created(their_node_id, msg))
2671 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2672 let _ = self.total_consistency_lock.read().unwrap();
2673 handle_error!(self, self.internal_funding_signed(their_node_id, msg))
2676 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2677 let _ = self.total_consistency_lock.read().unwrap();
2678 handle_error!(self, self.internal_funding_locked(their_node_id, msg))
2681 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2682 let _ = self.total_consistency_lock.read().unwrap();
2683 handle_error!(self, self.internal_shutdown(their_node_id, msg))
2686 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2687 let _ = self.total_consistency_lock.read().unwrap();
2688 handle_error!(self, self.internal_closing_signed(their_node_id, msg))
2691 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2692 let _ = self.total_consistency_lock.read().unwrap();
2693 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg))
2696 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2697 let _ = self.total_consistency_lock.read().unwrap();
2698 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg))
2701 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2702 let _ = self.total_consistency_lock.read().unwrap();
2703 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg))
2706 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2707 let _ = self.total_consistency_lock.read().unwrap();
2708 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg))
2711 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2712 let _ = self.total_consistency_lock.read().unwrap();
2713 handle_error!(self, self.internal_commitment_signed(their_node_id, msg))
2716 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2717 let _ = self.total_consistency_lock.read().unwrap();
2718 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg))
2721 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2722 let _ = self.total_consistency_lock.read().unwrap();
2723 handle_error!(self, self.internal_update_fee(their_node_id, msg))
2726 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2727 let _ = self.total_consistency_lock.read().unwrap();
2728 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg))
2731 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2732 let _ = self.total_consistency_lock.read().unwrap();
2733 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg))
2736 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2737 let _ = self.total_consistency_lock.read().unwrap();
2738 let mut failed_channels = Vec::new();
2739 let mut failed_payments = Vec::new();
2741 let mut channel_state_lock = self.channel_state.lock().unwrap();
2742 let channel_state = channel_state_lock.borrow_parts();
2743 let short_to_id = channel_state.short_to_id;
2744 let pending_msg_events = channel_state.pending_msg_events;
2745 if no_connection_possible {
2746 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2747 channel_state.by_id.retain(|_, chan| {
2748 if chan.get_their_node_id() == *their_node_id {
2749 if let Some(short_id) = chan.get_short_channel_id() {
2750 short_to_id.remove(&short_id);
2752 failed_channels.push(chan.force_shutdown());
2753 if let Ok(update) = self.get_channel_update(&chan) {
2754 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2764 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2765 channel_state.by_id.retain(|_, chan| {
2766 if chan.get_their_node_id() == *their_node_id {
2767 //TODO: mark channel disabled (and maybe announce such after a timeout).
2768 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2769 if !failed_adds.is_empty() {
2770 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
2771 failed_payments.push((chan_update, failed_adds));
2773 if chan.is_shutdown() {
2774 if let Some(short_id) = chan.get_short_channel_id() {
2775 short_to_id.remove(&short_id);
2783 pending_msg_events.retain(|msg| {
2785 &events::MessageSendEvent::SendAcceptChannel { ref node_id, .. } => node_id != their_node_id,
2786 &events::MessageSendEvent::SendOpenChannel { ref node_id, .. } => node_id != their_node_id,
2787 &events::MessageSendEvent::SendFundingCreated { ref node_id, .. } => node_id != their_node_id,
2788 &events::MessageSendEvent::SendFundingSigned { ref node_id, .. } => node_id != their_node_id,
2789 &events::MessageSendEvent::SendFundingLocked { ref node_id, .. } => node_id != their_node_id,
2790 &events::MessageSendEvent::SendAnnouncementSignatures { ref node_id, .. } => node_id != their_node_id,
2791 &events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => node_id != their_node_id,
2792 &events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => node_id != their_node_id,
2793 &events::MessageSendEvent::SendClosingSigned { ref node_id, .. } => node_id != their_node_id,
2794 &events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != their_node_id,
2795 &events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != their_node_id,
2796 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
2797 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
2798 &events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != their_node_id,
2799 &events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
2803 for failure in failed_channels.drain(..) {
2804 self.finish_force_close_channel(failure);
2806 for (chan_update, mut htlc_sources) in failed_payments {
2807 for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2808 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2813 fn peer_connected(&self, their_node_id: &PublicKey) {
2814 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2816 let _ = self.total_consistency_lock.read().unwrap();
2817 let mut channel_state_lock = self.channel_state.lock().unwrap();
2818 let channel_state = channel_state_lock.borrow_parts();
2819 let pending_msg_events = channel_state.pending_msg_events;
2820 channel_state.by_id.retain(|_, chan| {
2821 if chan.get_their_node_id() == *their_node_id {
2822 if !chan.have_received_message() {
2823 // If we created this (outbound) channel while we were disconnected from the
2824 // peer we probably failed to send the open_channel message, which is now
2825 // lost. We can't have had anything pending related to this channel, so we just
2829 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2830 node_id: chan.get_their_node_id(),
2831 msg: chan.get_channel_reestablish(),
2837 //TODO: Also re-broadcast announcement_signatures
2840 fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2841 let _ = self.total_consistency_lock.read().unwrap();
2843 if msg.channel_id == [0; 32] {
2844 for chan in self.list_channels() {
2845 if chan.remote_network_id == *their_node_id {
2846 self.force_close_channel(&chan.channel_id);
2850 self.force_close_channel(&msg.channel_id);
2855 const SERIALIZATION_VERSION: u8 = 1;
2856 const MIN_SERIALIZATION_VERSION: u8 = 1;
2858 impl Writeable for PendingForwardHTLCInfo {
2859 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2860 self.onion_packet.write(writer)?;
2861 self.incoming_shared_secret.write(writer)?;
2862 self.payment_hash.write(writer)?;
2863 self.short_channel_id.write(writer)?;
2864 self.amt_to_forward.write(writer)?;
2865 self.outgoing_cltv_value.write(writer)?;
2870 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2871 fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2872 Ok(PendingForwardHTLCInfo {
2873 onion_packet: Readable::read(reader)?,
2874 incoming_shared_secret: Readable::read(reader)?,
2875 payment_hash: Readable::read(reader)?,
2876 short_channel_id: Readable::read(reader)?,
2877 amt_to_forward: Readable::read(reader)?,
2878 outgoing_cltv_value: Readable::read(reader)?,
2883 impl Writeable for HTLCFailureMsg {
2884 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2886 &HTLCFailureMsg::Relay(ref fail_msg) => {
2888 fail_msg.write(writer)?;
2890 &HTLCFailureMsg::Malformed(ref fail_msg) => {
2892 fail_msg.write(writer)?;
2899 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
2900 fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
2901 match <u8 as Readable<R>>::read(reader)? {
2902 0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
2903 1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
2904 _ => Err(DecodeError::InvalidValue),
2909 impl Writeable for PendingHTLCStatus {
2910 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2912 &PendingHTLCStatus::Forward(ref forward_info) => {
2914 forward_info.write(writer)?;
2916 &PendingHTLCStatus::Fail(ref fail_msg) => {
2918 fail_msg.write(writer)?;
2925 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
2926 fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
2927 match <u8 as Readable<R>>::read(reader)? {
2928 0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
2929 1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
2930 _ => Err(DecodeError::InvalidValue),
2935 impl_writeable!(HTLCPreviousHopData, 0, {
2938 incoming_packet_shared_secret
2941 impl Writeable for HTLCSource {
2942 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2944 &HTLCSource::PreviousHopData(ref hop_data) => {
2946 hop_data.write(writer)?;
2948 &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
2950 route.write(writer)?;
2951 session_priv.write(writer)?;
2952 first_hop_htlc_msat.write(writer)?;
2959 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
2960 fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
2961 match <u8 as Readable<R>>::read(reader)? {
2962 0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
2963 1 => Ok(HTLCSource::OutboundRoute {
2964 route: Readable::read(reader)?,
2965 session_priv: Readable::read(reader)?,
2966 first_hop_htlc_msat: Readable::read(reader)?,
2968 _ => Err(DecodeError::InvalidValue),
2973 impl Writeable for HTLCFailReason {
2974 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2976 &HTLCFailReason::ErrorPacket { ref err } => {
2980 &HTLCFailReason::Reason { ref failure_code, ref data } => {
2982 failure_code.write(writer)?;
2983 data.write(writer)?;
2990 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
2991 fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
2992 match <u8 as Readable<R>>::read(reader)? {
2993 0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
2994 1 => Ok(HTLCFailReason::Reason {
2995 failure_code: Readable::read(reader)?,
2996 data: Readable::read(reader)?,
2998 _ => Err(DecodeError::InvalidValue),
3003 impl Writeable for HTLCForwardInfo {
3004 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3006 &HTLCForwardInfo::AddHTLC { ref prev_short_channel_id, ref prev_htlc_id, ref forward_info } => {
3008 prev_short_channel_id.write(writer)?;
3009 prev_htlc_id.write(writer)?;
3010 forward_info.write(writer)?;
3012 &HTLCForwardInfo::FailHTLC { ref htlc_id, ref err_packet } => {
3014 htlc_id.write(writer)?;
3015 err_packet.write(writer)?;
3022 impl<R: ::std::io::Read> Readable<R> for HTLCForwardInfo {
3023 fn read(reader: &mut R) -> Result<HTLCForwardInfo, DecodeError> {
3024 match <u8 as Readable<R>>::read(reader)? {
3025 0 => Ok(HTLCForwardInfo::AddHTLC {
3026 prev_short_channel_id: Readable::read(reader)?,
3027 prev_htlc_id: Readable::read(reader)?,
3028 forward_info: Readable::read(reader)?,
3030 1 => Ok(HTLCForwardInfo::FailHTLC {
3031 htlc_id: Readable::read(reader)?,
3032 err_packet: Readable::read(reader)?,
3034 _ => Err(DecodeError::InvalidValue),
3039 impl Writeable for ChannelManager {
3040 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3041 let _ = self.total_consistency_lock.write().unwrap();
3043 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3044 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3046 self.genesis_hash.write(writer)?;
3047 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3048 self.last_block_hash.lock().unwrap().write(writer)?;
3050 let channel_state = self.channel_state.lock().unwrap();
3051 let mut unfunded_channels = 0;
3052 for (_, channel) in channel_state.by_id.iter() {
3053 if !channel.is_funding_initiated() {
3054 unfunded_channels += 1;
3057 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3058 for (_, channel) in channel_state.by_id.iter() {
3059 if channel.is_funding_initiated() {
3060 channel.write(writer)?;
3064 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3065 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3066 short_channel_id.write(writer)?;
3067 (pending_forwards.len() as u64).write(writer)?;
3068 for forward in pending_forwards {
3069 forward.write(writer)?;
3073 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3074 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3075 payment_hash.write(writer)?;
3076 (previous_hops.len() as u64).write(writer)?;
3077 for &(recvd_amt, ref previous_hop) in previous_hops.iter() {
3078 recvd_amt.write(writer)?;
3079 previous_hop.write(writer)?;
3087 /// Arguments for the creation of a ChannelManager that are not deserialized.
3089 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3091 /// 1) Deserialize all stored ChannelMonitors.
3092 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3093 /// ChannelManager)>::read(reader, args).
3094 /// This may result in closing some Channels if the ChannelMonitor is newer than the stored
3095 /// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3096 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3097 /// ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3098 /// 4) Reconnect blocks on your ChannelMonitors.
3099 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3100 /// 6) Disconnect/connect blocks on the ChannelManager.
3101 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3102 /// automatically as it does in ChannelManager::new()).
3103 pub struct ChannelManagerReadArgs<'a> {
3104 /// The keys provider which will give us relevant keys. Some keys will be loaded during
3105 /// deserialization.
3106 pub keys_manager: Arc<KeysInterface>,
3108 /// The fee_estimator for use in the ChannelManager in the future.
3110 /// No calls to the FeeEstimator will be made during deserialization.
3111 pub fee_estimator: Arc<FeeEstimator>,
3112 /// The ManyChannelMonitor for use in the ChannelManager in the future.
3114 /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3115 /// you have deserialized ChannelMonitors separately and will add them to your
3116 /// ManyChannelMonitor after deserializing this ChannelManager.
3117 pub monitor: Arc<ManyChannelMonitor>,
3118 /// The ChainWatchInterface for use in the ChannelManager in the future.
3120 /// No calls to the ChainWatchInterface will be made during deserialization.
3121 pub chain_monitor: Arc<ChainWatchInterface>,
3122 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3123 /// used to broadcast the latest local commitment transactions of channels which must be
3124 /// force-closed during deserialization.
3125 pub tx_broadcaster: Arc<BroadcasterInterface>,
3126 /// The Logger for use in the ChannelManager and which may be used to log information during
3127 /// deserialization.
3128 pub logger: Arc<Logger>,
3129 /// Default settings used for new channels. Any existing channels will continue to use the
3130 /// runtime settings which were stored when the ChannelManager was serialized.
3131 pub default_config: UserConfig,
3133 /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3134 /// value.get_funding_txo() should be the key).
3136 /// If a monitor is inconsistent with the channel state during deserialization the channel will
3137 /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
3138 /// is true for missing channels as well. If there is a monitor missing for which we find
3139 /// channel data Err(DecodeError::InvalidValue) will be returned.
3141 /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3143 pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3146 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3147 fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3148 let _ver: u8 = Readable::read(reader)?;
3149 let min_ver: u8 = Readable::read(reader)?;
3150 if min_ver > SERIALIZATION_VERSION {
3151 return Err(DecodeError::UnknownVersion);
3154 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3155 let latest_block_height: u32 = Readable::read(reader)?;
3156 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3158 let mut closed_channels = Vec::new();
3160 let channel_count: u64 = Readable::read(reader)?;
3161 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3162 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3163 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3164 for _ in 0..channel_count {
3165 let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3166 if channel.last_block_connected != last_block_hash {
3167 return Err(DecodeError::InvalidValue);
3170 let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3171 funding_txo_set.insert(funding_txo.clone());
3172 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3173 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3174 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3175 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3176 let mut force_close_res = channel.force_shutdown();
3177 force_close_res.0 = monitor.get_latest_local_commitment_txn();
3178 closed_channels.push(force_close_res);
3180 if let Some(short_channel_id) = channel.get_short_channel_id() {
3181 short_to_id.insert(short_channel_id, channel.channel_id());
3183 by_id.insert(channel.channel_id(), channel);
3186 return Err(DecodeError::InvalidValue);
3190 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3191 if !funding_txo_set.contains(funding_txo) {
3192 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3196 let forward_htlcs_count: u64 = Readable::read(reader)?;
3197 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3198 for _ in 0..forward_htlcs_count {
3199 let short_channel_id = Readable::read(reader)?;
3200 let pending_forwards_count: u64 = Readable::read(reader)?;
3201 let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3202 for _ in 0..pending_forwards_count {
3203 pending_forwards.push(Readable::read(reader)?);
3205 forward_htlcs.insert(short_channel_id, pending_forwards);
3208 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3209 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3210 for _ in 0..claimable_htlcs_count {
3211 let payment_hash = Readable::read(reader)?;
3212 let previous_hops_len: u64 = Readable::read(reader)?;
3213 let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3214 for _ in 0..previous_hops_len {
3215 previous_hops.push((Readable::read(reader)?, Readable::read(reader)?));
3217 claimable_htlcs.insert(payment_hash, previous_hops);
3220 let channel_manager = ChannelManager {
3222 fee_estimator: args.fee_estimator,
3223 monitor: args.monitor,
3224 chain_monitor: args.chain_monitor,
3225 tx_broadcaster: args.tx_broadcaster,
3227 latest_block_height: AtomicUsize::new(latest_block_height as usize),
3228 last_block_hash: Mutex::new(last_block_hash),
3229 secp_ctx: Secp256k1::new(),
3231 channel_state: Mutex::new(ChannelHolder {
3236 pending_msg_events: Vec::new(),
3238 our_network_key: args.keys_manager.get_node_secret(),
3240 pending_events: Mutex::new(Vec::new()),
3241 total_consistency_lock: RwLock::new(()),
3242 keys_manager: args.keys_manager,
3243 logger: args.logger,
3244 default_configuration: args.default_config,
3247 for close_res in closed_channels.drain(..) {
3248 channel_manager.finish_force_close_channel(close_res);
3249 //TODO: Broadcast channel update for closed channels, but only after we've made a
3250 //connection or two.
3253 Ok((last_block_hash.clone(), channel_manager))