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,FeeEstimator};
29 use chain::transaction::OutPoint;
30 use ln::channel::{Channel, ChannelError};
31 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
32 use ln::router::Route;
33 use ln::features::{InitFeatures, NodeFeatures};
36 use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
37 use chain::keysinterface::{ChannelKeys, KeysInterface, InMemoryChannelKeys};
38 use util::config::UserConfig;
39 use util::{byte_utils, events};
40 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
41 use util::chacha20::{ChaCha20, ChaChaReader};
42 use util::logger::Logger;
43 use util::errors::APIError;
46 use std::collections::{HashMap, hash_map, HashSet};
47 use std::io::{Cursor, Read};
48 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
49 use std::sync::atomic::{AtomicUsize, Ordering};
50 use std::time::Duration;
51 use std::marker::{Sync, Send};
54 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
56 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
57 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
58 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
60 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
61 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
62 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
63 // before we forward it.
65 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
66 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
67 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
68 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
69 // our payment, which we can use to decode errors or inform the user that the payment was sent.
71 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
72 enum PendingForwardReceiveHTLCInfo {
74 onion_packet: msgs::OnionPacket,
75 short_channel_id: u64, // This should be NonZero<u64> eventually
78 payment_data: Option<msgs::FinalOnionHopData>,
82 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
83 pub(super) struct PendingHTLCInfo {
84 type_data: PendingForwardReceiveHTLCInfo,
85 incoming_shared_secret: [u8; 32],
86 payment_hash: PaymentHash,
87 pub(super) amt_to_forward: u64,
88 pub(super) outgoing_cltv_value: u32,
91 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
92 pub(super) enum HTLCFailureMsg {
93 Relay(msgs::UpdateFailHTLC),
94 Malformed(msgs::UpdateFailMalformedHTLC),
97 /// Stores whether we can't forward an HTLC or relevant forwarding info
98 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
99 pub(super) enum PendingHTLCStatus {
100 Forward(PendingHTLCInfo),
101 Fail(HTLCFailureMsg),
104 pub(super) enum HTLCForwardInfo {
106 prev_short_channel_id: u64,
108 forward_info: PendingHTLCInfo,
112 err_packet: msgs::OnionErrorPacket,
116 /// Tracks the inbound corresponding to an outbound HTLC
117 #[derive(Clone, PartialEq)]
118 pub(super) struct HTLCPreviousHopData {
119 short_channel_id: u64,
121 incoming_packet_shared_secret: [u8; 32],
124 struct ClaimableHTLC {
125 src: HTLCPreviousHopData,
127 payment_data: Option<msgs::FinalOnionHopData>,
130 /// Tracks the inbound corresponding to an outbound HTLC
131 #[derive(Clone, PartialEq)]
132 pub(super) enum HTLCSource {
133 PreviousHopData(HTLCPreviousHopData),
136 session_priv: SecretKey,
137 /// Technically we can recalculate this from the route, but we cache it here to avoid
138 /// doing a double-pass on route when we get a failure back
139 first_hop_htlc_msat: u64,
144 pub fn dummy() -> Self {
145 HTLCSource::OutboundRoute {
146 route: Route { hops: Vec::new() },
147 session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
148 first_hop_htlc_msat: 0,
153 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
154 pub(super) enum HTLCFailReason {
156 err: msgs::OnionErrorPacket,
164 /// payment_hash type, use to cross-lock hop
165 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
166 pub struct PaymentHash(pub [u8;32]);
167 /// payment_preimage type, use to route payment between hop
168 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
169 pub struct PaymentPreimage(pub [u8;32]);
171 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
173 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
174 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
175 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
176 /// channel_state lock. We then return the set of things that need to be done outside the lock in
177 /// this struct and call handle_error!() on it.
179 struct MsgHandleErrInternal {
180 err: msgs::LightningError,
181 shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
183 impl MsgHandleErrInternal {
185 fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
187 err: LightningError {
189 action: msgs::ErrorAction::SendErrorMessage {
190 msg: msgs::ErrorMessage {
192 data: err.to_string()
196 shutdown_finish: None,
200 fn ignore_no_close(err: &'static str) -> Self {
202 err: LightningError {
204 action: msgs::ErrorAction::IgnoreError,
206 shutdown_finish: None,
210 fn from_no_close(err: msgs::LightningError) -> Self {
211 Self { err, shutdown_finish: None }
214 fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
216 err: LightningError {
218 action: msgs::ErrorAction::SendErrorMessage {
219 msg: msgs::ErrorMessage {
221 data: err.to_string()
225 shutdown_finish: Some((shutdown_res, channel_update)),
229 fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
232 ChannelError::Ignore(msg) => LightningError {
234 action: msgs::ErrorAction::IgnoreError,
236 ChannelError::Close(msg) => LightningError {
238 action: msgs::ErrorAction::SendErrorMessage {
239 msg: msgs::ErrorMessage {
241 data: msg.to_string()
245 ChannelError::CloseDelayBroadcast { msg, .. } => LightningError {
247 action: msgs::ErrorAction::SendErrorMessage {
248 msg: msgs::ErrorMessage {
250 data: msg.to_string()
255 shutdown_finish: None,
260 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
261 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
262 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
263 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
264 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
266 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
267 /// be sent in the order they appear in the return value, however sometimes the order needs to be
268 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
269 /// they were originally sent). In those cases, this enum is also returned.
270 #[derive(Clone, PartialEq)]
271 pub(super) enum RAACommitmentOrder {
272 /// Send the CommitmentUpdate messages first
274 /// Send the RevokeAndACK message first
278 // Note this is only exposed in cfg(test):
279 pub(super) struct ChannelHolder<ChanSigner: ChannelKeys> {
280 pub(super) by_id: HashMap<[u8; 32], Channel<ChanSigner>>,
281 pub(super) short_to_id: HashMap<u64, [u8; 32]>,
282 /// short channel id -> forward infos. Key of 0 means payments received
283 /// Note that while this is held in the same mutex as the channels themselves, no consistency
284 /// guarantees are made about the existence of a channel with the short id here, nor the short
285 /// ids in the PendingHTLCInfo!
286 pub(super) forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
287 /// (payment_hash, payment_secret) -> Vec<HTLCs> for tracking things that
288 /// were to us and can be failed/claimed by the user
289 /// Note that while this is held in the same mutex as the channels themselves, no consistency
290 /// guarantees are made about the channels given here actually existing anymore by the time you
292 /// TODO: We need to time out HTLCs sitting here which are waiting on other AMP HTLCs to
294 claimable_htlcs: HashMap<(PaymentHash, Option<[u8; 32]>), Vec<ClaimableHTLC>>,
295 /// Messages to send to peers - pushed to in the same lock that they are generated in (except
296 /// for broadcast messages, where ordering isn't as strict).
297 pub(super) pending_msg_events: Vec<events::MessageSendEvent>,
300 /// State we hold per-peer. In the future we should put channels in here, but for now we only hold
301 /// the latest Init features we heard from the peer.
303 latest_features: InitFeatures,
306 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
307 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
309 /// SimpleArcChannelManager is useful when you need a ChannelManager with a static lifetime, e.g.
310 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
311 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
312 /// SimpleRefChannelManager is the more appropriate type. Defining these type aliases prevents
313 /// issues such as overly long function definitions.
314 pub type SimpleArcChannelManager<M> = Arc<ChannelManager<InMemoryChannelKeys, Arc<M>>>;
316 /// SimpleRefChannelManager is a type alias for a ChannelManager reference, and is the reference
317 /// counterpart to the SimpleArcChannelManager type alias. Use this type by default when you don't
318 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
319 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
320 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
321 /// helps with issues such as long function definitions.
322 pub type SimpleRefChannelManager<'a, M> = ChannelManager<InMemoryChannelKeys, &'a M>;
324 /// Manager which keeps track of a number of channels and sends messages to the appropriate
325 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
327 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
328 /// to individual Channels.
330 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
331 /// all peers during write/read (though does not modify this instance, only the instance being
332 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
333 /// called funding_transaction_generated for outbound channels).
335 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
336 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
337 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
338 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
339 /// the serialization process). If the deserialized version is out-of-date compared to the
340 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
341 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
343 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
344 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
345 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
346 /// block_connected() to step towards your best block) upon deserialization before using the
349 /// Note that ChannelManager is responsible for tracking liveness of its channels and generating
350 /// ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid
351 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
352 /// offline for a full minute. In order to track this, you must call
353 /// timer_chan_freshness_every_min roughly once per minute, though it doesn't have to be perfect.
355 /// Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager
356 /// a SimpleRefChannelManager, for conciseness. See their documentation for more details, but
357 /// essentially you should default to using a SimpleRefChannelManager, and use a
358 /// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
359 /// you're using lightning-net-tokio.
360 pub struct ChannelManager<ChanSigner: ChannelKeys, M: Deref> where M::Target: ManyChannelMonitor {
361 default_configuration: UserConfig,
362 genesis_hash: Sha256dHash,
363 fee_estimator: Arc<FeeEstimator>,
365 tx_broadcaster: Arc<BroadcasterInterface>,
368 pub(super) latest_block_height: AtomicUsize,
370 latest_block_height: AtomicUsize,
371 last_block_hash: Mutex<Sha256dHash>,
372 secp_ctx: Secp256k1<secp256k1::All>,
375 pub(super) channel_state: Mutex<ChannelHolder<ChanSigner>>,
377 channel_state: Mutex<ChannelHolder<ChanSigner>>,
378 our_network_key: SecretKey,
380 last_node_announcement_serial: AtomicUsize,
382 /// The bulk of our storage will eventually be here (channels and message queues and the like).
383 /// If we are connected to a peer we always at least have an entry here, even if no channels
384 /// are currently open with that peer.
385 /// Because adding or removing an entry is rare, we usually take an outer read lock and then
386 /// operate on the inner value freely. Sadly, this prevents parallel operation when opening a
388 per_peer_state: RwLock<HashMap<PublicKey, Mutex<PeerState>>>,
390 pending_events: Mutex<Vec<events::Event>>,
391 /// Used when we have to take a BIG lock to make sure everything is self-consistent.
392 /// Essentially just when we're serializing ourselves out.
393 /// Taken first everywhere where we are making changes before any other locks.
394 total_consistency_lock: RwLock<()>,
396 keys_manager: Arc<KeysInterface<ChanKeySigner = ChanSigner>>,
401 /// The amount of time we require our counterparty wait to claim their money (ie time between when
402 /// we, or our watchtower, must check for them having broadcast a theft transaction).
403 pub(crate) const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
404 /// The amount of time we're willing to wait to claim money back to us
405 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 6 * 24 * 7;
407 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
408 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
409 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
410 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
411 /// CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
412 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
413 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
415 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
416 // ie that if the next-hop peer fails the HTLC within
417 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
418 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
419 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
420 // LATENCY_GRACE_PERIOD_BLOCKS.
423 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - CLTV_CLAIM_BUFFER - ANTI_REORG_DELAY - LATENCY_GRACE_PERIOD_BLOCKS;
425 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
426 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
429 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
431 macro_rules! secp_call {
432 ( $res: expr, $err: expr ) => {
435 Err(_) => return Err($err),
440 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
441 pub struct ChannelDetails {
442 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
443 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
444 /// Note that this means this value is *not* persistent - it can change once during the
445 /// lifetime of the channel.
446 pub channel_id: [u8; 32],
447 /// The position of the funding transaction in the chain. None if the funding transaction has
448 /// not yet been confirmed and the channel fully opened.
449 pub short_channel_id: Option<u64>,
450 /// The node_id of our counterparty
451 pub remote_network_id: PublicKey,
452 /// The Features the channel counterparty provided upon last connection.
453 /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
454 /// many routing-relevant features are present in the init context.
455 pub counterparty_features: InitFeatures,
456 /// The value, in satoshis, of this channel as appears in the funding output
457 pub channel_value_satoshis: u64,
458 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
460 /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
461 /// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
462 /// available for inclusion in new outbound HTLCs). This further does not include any pending
463 /// outgoing HTLCs which are awaiting some other resolution to be sent.
464 pub outbound_capacity_msat: u64,
465 /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
466 /// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
467 /// available for inclusion in new inbound HTLCs).
468 /// Note that there are some corner cases not fully handled here, so the actual available
469 /// inbound capacity may be slightly higher than this.
470 pub inbound_capacity_msat: u64,
471 /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
472 /// the peer is connected, and (c) no monitor update failure is pending resolution.
476 macro_rules! handle_error {
477 ($self: ident, $internal: expr, $their_node_id: expr, $locked_channel_state: expr) => {
480 Err(MsgHandleErrInternal { err, shutdown_finish }) => {
481 if let Some((shutdown_res, update_option)) = shutdown_finish {
482 $self.finish_force_close_channel(shutdown_res);
483 if let Some(update) = update_option {
484 $locked_channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
489 log_error!($self, "{}", err.err);
490 if let msgs::ErrorAction::IgnoreError = err.action {
491 } else { $locked_channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError { node_id: $their_node_id, action: err.action.clone() }); }
492 // Return error in case higher-API need one
499 macro_rules! break_chan_entry {
500 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
503 Err(ChannelError::Ignore(msg)) => {
504 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
506 Err(ChannelError::Close(msg)) => {
507 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
508 let (channel_id, mut chan) = $entry.remove_entry();
509 if let Some(short_id) = chan.get_short_channel_id() {
510 $channel_state.short_to_id.remove(&short_id);
512 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
514 Err(ChannelError::CloseDelayBroadcast { .. }) => { panic!("Wait is only generated on receipt of channel_reestablish, which is handled by try_chan_entry, we don't bother to support it here"); }
519 macro_rules! try_chan_entry {
520 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
523 Err(ChannelError::Ignore(msg)) => {
524 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
526 Err(ChannelError::Close(msg)) => {
527 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
528 let (channel_id, mut chan) = $entry.remove_entry();
529 if let Some(short_id) = chan.get_short_channel_id() {
530 $channel_state.short_to_id.remove(&short_id);
532 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
534 Err(ChannelError::CloseDelayBroadcast { msg, update }) => {
535 log_error!($self, "Channel {} need to be shutdown but closing transactions not broadcast due to {}", log_bytes!($entry.key()[..]), msg);
536 let (channel_id, mut chan) = $entry.remove_entry();
537 if let Some(short_id) = chan.get_short_channel_id() {
538 $channel_state.short_to_id.remove(&short_id);
540 if let Some(update) = update {
541 if let Err(e) = $self.monitor.add_update_monitor(update.get_funding_txo().unwrap(), update) {
543 // Upstream channel is dead, but we want at least to fail backward HTLCs to save
544 // downstream channels. In case of PermanentFailure, we are not going to be able
545 // to claim back to_remote output on remote commitment transaction. Doesn't
546 // make a difference here, we are concern about HTLCs circuit, not onchain funds.
547 ChannelMonitorUpdateErr::PermanentFailure => {},
548 ChannelMonitorUpdateErr::TemporaryFailure => {},
552 let mut shutdown_res = chan.force_shutdown();
553 if shutdown_res.0.len() >= 1 {
554 log_error!($self, "You have a toxic local commitment transaction {} avaible in channel monitor, read comment in ChannelMonitor::get_latest_local_commitment_txn to be informed of manual action to take", shutdown_res.0[0].txid());
556 shutdown_res.0.clear();
557 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, shutdown_res, $self.get_channel_update(&chan).ok()))
563 macro_rules! handle_monitor_err {
564 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
565 handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, Vec::new(), Vec::new())
567 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
569 ChannelMonitorUpdateErr::PermanentFailure => {
570 log_error!($self, "Closing channel {} due to monitor update PermanentFailure", log_bytes!($entry.key()[..]));
571 let (channel_id, mut chan) = $entry.remove_entry();
572 if let Some(short_id) = chan.get_short_channel_id() {
573 $channel_state.short_to_id.remove(&short_id);
575 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
576 // chain in a confused state! We need to move them into the ChannelMonitor which
577 // will be responsible for failing backwards once things confirm on-chain.
578 // It's ok that we drop $failed_forwards here - at this point we'd rather they
579 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
580 // us bother trying to claim it just to forward on to another peer. If we're
581 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
582 // given up the preimage yet, so might as well just wait until the payment is
583 // retried, avoiding the on-chain fees.
584 let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()));
587 ChannelMonitorUpdateErr::TemporaryFailure => {
588 log_info!($self, "Disabling channel {} due to monitor update TemporaryFailure. On restore will send {} and process {} forwards and {} fails",
589 log_bytes!($entry.key()[..]),
590 if $resend_commitment && $resend_raa {
592 RAACommitmentOrder::CommitmentFirst => { "commitment then RAA" },
593 RAACommitmentOrder::RevokeAndACKFirst => { "RAA then commitment" },
595 } else if $resend_commitment { "commitment" }
596 else if $resend_raa { "RAA" }
598 (&$failed_forwards as &Vec<(PendingHTLCInfo, u64)>).len(),
599 (&$failed_fails as &Vec<(HTLCSource, PaymentHash, HTLCFailReason)>).len());
600 if !$resend_commitment {
601 debug_assert!($action_type == RAACommitmentOrder::RevokeAndACKFirst || !$resend_raa);
604 debug_assert!($action_type == RAACommitmentOrder::CommitmentFirst || !$resend_commitment);
606 $entry.get_mut().monitor_update_failed($resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
607 Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()))
613 macro_rules! return_monitor_err {
614 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
615 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment);
617 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
618 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
622 // Does not break in case of TemporaryFailure!
623 macro_rules! maybe_break_monitor_err {
624 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
625 match (handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment), $err) {
626 (e, ChannelMonitorUpdateErr::PermanentFailure) => {
629 (_, ChannelMonitorUpdateErr::TemporaryFailure) => { },
634 impl<ChanSigner: ChannelKeys, M: Deref> ChannelManager<ChanSigner, M> where M::Target: ManyChannelMonitor {
635 /// Constructs a new ChannelManager to hold several channels and route between them.
637 /// This is the main "logic hub" for all channel-related actions, and implements
638 /// ChannelMessageHandler.
640 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
642 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
644 /// Users must provide the current blockchain height from which to track onchain channel
645 /// funding outpoints and send payments with reliable timelocks.
647 /// Users need to notify the new ChannelManager when a new block is connected or
648 /// disconnected using its `block_connected` and `block_disconnected` methods.
649 /// However, rather than calling these methods directly, the user should register
650 /// the ChannelManager as a listener to the BlockNotifier and call the BlockNotifier's
651 /// `block_(dis)connected` methods, which will notify all registered listeners in one
653 pub fn new(network: Network, feeest: Arc<FeeEstimator>, monitor: M, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>,keys_manager: Arc<KeysInterface<ChanKeySigner = ChanSigner>>, config: UserConfig, current_blockchain_height: usize) -> Result<ChannelManager<ChanSigner, M>, secp256k1::Error> {
654 let secp_ctx = Secp256k1::new();
656 let res = ChannelManager {
657 default_configuration: config.clone(),
658 genesis_hash: genesis_block(network).header.bitcoin_hash(),
659 fee_estimator: feeest.clone(),
663 latest_block_height: AtomicUsize::new(current_blockchain_height),
664 last_block_hash: Mutex::new(Default::default()),
667 channel_state: Mutex::new(ChannelHolder{
668 by_id: HashMap::new(),
669 short_to_id: HashMap::new(),
670 forward_htlcs: HashMap::new(),
671 claimable_htlcs: HashMap::new(),
672 pending_msg_events: Vec::new(),
674 our_network_key: keys_manager.get_node_secret(),
676 last_node_announcement_serial: AtomicUsize::new(0),
678 per_peer_state: RwLock::new(HashMap::new()),
680 pending_events: Mutex::new(Vec::new()),
681 total_consistency_lock: RwLock::new(()),
691 /// Creates a new outbound channel to the given remote node and with the given value.
693 /// user_id will be provided back as user_channel_id in FundingGenerationReady and
694 /// FundingBroadcastSafe events to allow tracking of which events correspond with which
695 /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
696 /// may wish to avoid using 0 for user_id here.
698 /// If successful, will generate a SendOpenChannel message event, so you should probably poll
699 /// PeerManager::process_events afterwards.
701 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
702 /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
703 pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
704 if channel_value_satoshis < 1000 {
705 return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
708 let channel = Channel::new_outbound(&*self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, Arc::clone(&self.logger), &self.default_configuration)?;
709 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
711 let _ = self.total_consistency_lock.read().unwrap();
712 let mut channel_state = self.channel_state.lock().unwrap();
713 match channel_state.by_id.entry(channel.channel_id()) {
714 hash_map::Entry::Occupied(_) => {
715 if cfg!(feature = "fuzztarget") {
716 return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
718 panic!("RNG is bad???");
721 hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
723 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
724 node_id: their_network_key,
730 fn list_channels_with_filter<F: FnMut(&(&[u8; 32], &Channel<ChanSigner>)) -> bool>(&self, f: F) -> Vec<ChannelDetails> {
731 let mut res = Vec::new();
733 let channel_state = self.channel_state.lock().unwrap();
734 res.reserve(channel_state.by_id.len());
735 for (channel_id, channel) in channel_state.by_id.iter().filter(f) {
736 let (inbound_capacity_msat, outbound_capacity_msat) = channel.get_inbound_outbound_available_balance_msat();
737 res.push(ChannelDetails {
738 channel_id: (*channel_id).clone(),
739 short_channel_id: channel.get_short_channel_id(),
740 remote_network_id: channel.get_their_node_id(),
741 counterparty_features: InitFeatures::empty(),
742 channel_value_satoshis: channel.get_value_satoshis(),
743 inbound_capacity_msat,
744 outbound_capacity_msat,
745 user_id: channel.get_user_id(),
746 is_live: channel.is_live(),
750 let per_peer_state = self.per_peer_state.read().unwrap();
751 for chan in res.iter_mut() {
752 if let Some(peer_state) = per_peer_state.get(&chan.remote_network_id) {
753 chan.counterparty_features = peer_state.lock().unwrap().latest_features.clone();
759 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
760 /// more information.
761 pub fn list_channels(&self) -> Vec<ChannelDetails> {
762 self.list_channels_with_filter(|_| true)
765 /// Gets the list of usable channels, in random order. Useful as an argument to
766 /// Router::get_route to ensure non-announced channels are used.
768 /// These are guaranteed to have their is_live value set to true, see the documentation for
769 /// ChannelDetails::is_live for more info on exactly what the criteria are.
770 pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
771 // Note we use is_live here instead of usable which leads to somewhat confused
772 // internal/external nomenclature, but that's ok cause that's probably what the user
773 // really wanted anyway.
774 self.list_channels_with_filter(|&(_, ref channel)| channel.is_live())
777 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
778 /// will be accepted on the given channel, and after additional timeout/the closing of all
779 /// pending HTLCs, the channel will be closed on chain.
781 /// May generate a SendShutdown message event on success, which should be relayed.
782 pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
783 let _ = self.total_consistency_lock.read().unwrap();
785 let (mut failed_htlcs, chan_option) = {
786 let mut channel_state_lock = self.channel_state.lock().unwrap();
787 let channel_state = &mut *channel_state_lock;
788 match channel_state.by_id.entry(channel_id.clone()) {
789 hash_map::Entry::Occupied(mut chan_entry) => {
790 let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
791 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
792 node_id: chan_entry.get().get_their_node_id(),
795 if chan_entry.get().is_shutdown() {
796 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
797 channel_state.short_to_id.remove(&short_id);
799 (failed_htlcs, Some(chan_entry.remove_entry().1))
800 } else { (failed_htlcs, None) }
802 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
805 for htlc_source in failed_htlcs.drain(..) {
806 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
808 let chan_update = if let Some(chan) = chan_option {
809 if let Ok(update) = self.get_channel_update(&chan) {
814 if let Some(update) = chan_update {
815 let mut channel_state = self.channel_state.lock().unwrap();
816 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
825 fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
826 let (local_txn, mut failed_htlcs) = shutdown_res;
827 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
828 for htlc_source in failed_htlcs.drain(..) {
829 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
831 for tx in local_txn {
832 log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
833 self.tx_broadcaster.broadcast_transaction(&tx);
837 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
838 /// the chain and rejecting new HTLCs on the given channel.
839 pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
840 let _ = self.total_consistency_lock.read().unwrap();
843 let mut channel_state_lock = self.channel_state.lock().unwrap();
844 let channel_state = &mut *channel_state_lock;
845 if let Some(chan) = channel_state.by_id.remove(channel_id) {
846 if let Some(short_id) = chan.get_short_channel_id() {
847 channel_state.short_to_id.remove(&short_id);
854 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
855 self.finish_force_close_channel(chan.force_shutdown());
856 if let Ok(update) = self.get_channel_update(&chan) {
857 let mut channel_state = self.channel_state.lock().unwrap();
858 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
864 /// Force close all channels, immediately broadcasting the latest local commitment transaction
865 /// for each to the chain and rejecting new HTLCs on each.
866 pub fn force_close_all_channels(&self) {
867 for chan in self.list_channels() {
868 self.force_close_channel(&chan.channel_id);
872 fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder<ChanSigner>>) {
873 macro_rules! return_malformed_err {
874 ($msg: expr, $err_code: expr) => {
876 log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
877 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
878 channel_id: msg.channel_id,
879 htlc_id: msg.htlc_id,
880 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
881 failure_code: $err_code,
882 })), self.channel_state.lock().unwrap());
887 if let Err(_) = msg.onion_routing_packet.public_key {
888 return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
891 let shared_secret = {
892 let mut arr = [0; 32];
893 arr.copy_from_slice(&SharedSecret::new(&msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
896 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(&shared_secret);
898 if msg.onion_routing_packet.version != 0 {
899 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
900 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
901 //the hash doesn't really serve any purpose - in the case of hashing all data, the
902 //receiving node would have to brute force to figure out which version was put in the
903 //packet by the node that send us the message, in the case of hashing the hop_data, the
904 //node knows the HMAC matched, so they already know what is there...
905 return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
908 let mut hmac = HmacEngine::<Sha256>::new(&mu);
909 hmac.input(&msg.onion_routing_packet.hop_data);
910 hmac.input(&msg.payment_hash.0[..]);
911 if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
912 return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
915 let mut channel_state = None;
916 macro_rules! return_err {
917 ($msg: expr, $err_code: expr, $data: expr) => {
919 log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
920 if channel_state.is_none() {
921 channel_state = Some(self.channel_state.lock().unwrap());
923 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
924 channel_id: msg.channel_id,
925 htlc_id: msg.htlc_id,
926 reason: onion_utils::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
927 })), channel_state.unwrap());
932 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
933 let mut chacha_stream = ChaChaReader { chacha: &mut chacha, read: Cursor::new(&msg.onion_routing_packet.hop_data[..]) };
934 let (next_hop_data, next_hop_hmac) = {
935 match msgs::OnionHopData::read(&mut chacha_stream) {
937 let error_code = match err {
938 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
939 msgs::DecodeError::UnknownRequiredFeature|
940 msgs::DecodeError::InvalidValue|
941 msgs::DecodeError::ShortRead => 0x4000 | 22, // invalid_onion_payload
942 _ => 0x2000 | 2, // Should never happen
944 return_err!("Unable to decode our hop data", error_code, &[0;0]);
947 let mut hmac = [0; 32];
948 if let Err(_) = chacha_stream.read_exact(&mut hmac[..]) {
949 return_err!("Unable to decode our hop data", 0x4000 | 22, &[0;0]);
956 let pending_forward_info = if next_hop_hmac == [0; 32] {
959 // In tests, make sure that the initial onion pcket data is, at least, non-0.
960 // We could do some fancy randomness test here, but, ehh, whatever.
961 // This checks for the issue where you can calculate the path length given the
962 // onion data as all the path entries that the originator sent will be here
963 // as-is (and were originally 0s).
964 // Of course reverse path calculation is still pretty easy given naive routing
965 // algorithms, but this fixes the most-obvious case.
966 let mut next_bytes = [0; 32];
967 chacha_stream.read_exact(&mut next_bytes).unwrap();
968 assert_ne!(next_bytes[..], [0; 32][..]);
969 chacha_stream.read_exact(&mut next_bytes).unwrap();
970 assert_ne!(next_bytes[..], [0; 32][..]);
974 // final_expiry_too_soon
975 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
976 return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
978 // final_incorrect_htlc_amount
979 if next_hop_data.amt_to_forward > msg.amount_msat {
980 return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
982 // final_incorrect_cltv_expiry
983 if next_hop_data.outgoing_cltv_value != msg.cltv_expiry {
984 return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
987 let payment_data = match next_hop_data.format {
988 msgs::OnionHopDataFormat::Legacy { .. } => None,
989 msgs::OnionHopDataFormat::NonFinalNode { .. } => return_err!("Got non final data with an HMAC of 0", 0x4000 | 22, &[0;0]),
990 msgs::OnionHopDataFormat::FinalNode { payment_data } => payment_data,
993 // Note that we could obviously respond immediately with an update_fulfill_htlc
994 // message, however that would leak that we are the recipient of this payment, so
995 // instead we stay symmetric with the forwarding case, only responding (after a
996 // delay) once they've send us a commitment_signed!
998 PendingHTLCStatus::Forward(PendingHTLCInfo {
999 type_data: PendingForwardReceiveHTLCInfo::Receive { payment_data },
1000 payment_hash: msg.payment_hash.clone(),
1001 incoming_shared_secret: shared_secret,
1002 amt_to_forward: next_hop_data.amt_to_forward,
1003 outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1006 let mut new_packet_data = [0; 20*65];
1007 let read_pos = chacha_stream.read(&mut new_packet_data).unwrap();
1008 #[cfg(debug_assertions)]
1010 // Check two things:
1011 // a) that the behavior of our stream here will return Ok(0) even if the TLV
1012 // read above emptied out our buffer and the unwrap() wont needlessly panic
1013 // b) that we didn't somehow magically end up with extra data.
1015 debug_assert!(chacha_stream.read(&mut t).unwrap() == 0);
1017 chacha_stream.chacha.process_inline(&mut new_packet_data[read_pos..]);
1019 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1021 let blinding_factor = {
1022 let mut sha = Sha256::engine();
1023 sha.input(&new_pubkey.serialize()[..]);
1024 sha.input(&shared_secret);
1025 Sha256::from_engine(sha).into_inner()
1028 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor[..]) {
1030 } else { Ok(new_pubkey) };
1032 let outgoing_packet = msgs::OnionPacket {
1035 hop_data: new_packet_data,
1036 hmac: next_hop_hmac.clone(),
1039 let short_channel_id = match next_hop_data.format {
1040 msgs::OnionHopDataFormat::Legacy { short_channel_id } => short_channel_id,
1041 msgs::OnionHopDataFormat::NonFinalNode { short_channel_id } => short_channel_id,
1042 msgs::OnionHopDataFormat::FinalNode { .. } => {
1043 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0;0]);
1047 PendingHTLCStatus::Forward(PendingHTLCInfo {
1048 type_data: PendingForwardReceiveHTLCInfo::Forward {
1049 onion_packet: outgoing_packet,
1050 short_channel_id: short_channel_id,
1052 payment_hash: msg.payment_hash.clone(),
1053 incoming_shared_secret: shared_secret,
1054 amt_to_forward: next_hop_data.amt_to_forward,
1055 outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1059 channel_state = Some(self.channel_state.lock().unwrap());
1060 if let &PendingHTLCStatus::Forward(PendingHTLCInfo { ref type_data, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1061 // If short_channel_id is 0 here, we'll reject them in the body here (which is
1062 // important as various things later assume we are a ::Receive if short_channel_id is
1064 if let &PendingForwardReceiveHTLCInfo::Forward { ref short_channel_id, .. } = type_data {
1065 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1066 let forwarding_id = match id_option {
1067 None => { // unknown_next_peer
1068 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1070 Some(id) => id.clone(),
1072 if let Some((err, code, chan_update)) = loop {
1073 let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1075 // Note that we could technically not return an error yet here and just hope
1076 // that the connection is reestablished or monitor updated by the time we get
1077 // around to doing the actual forward, but better to fail early if we can and
1078 // hopefully an attacker trying to path-trace payments cannot make this occur
1079 // on a small/per-node/per-channel scale.
1080 if !chan.is_live() { // channel_disabled
1081 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1083 if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1084 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1086 let fee = amt_to_forward.checked_mul(chan.get_fee_proportional_millionths() as u64).and_then(|prop_fee| { (prop_fee / 1000000).checked_add(chan.get_our_fee_base_msat(&*self.fee_estimator) as u64) });
1087 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1088 break Some(("Prior hop has deviated from specified fees parameters or origin node has obsolete ones", 0x1000 | 12, Some(self.get_channel_update(chan).unwrap())));
1090 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1091 break Some(("Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta", 0x1000 | 13, Some(self.get_channel_update(chan).unwrap())));
1093 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1094 // We want to have at least LATENCY_GRACE_PERIOD_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1095 if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS as u32 { // expiry_too_soon
1096 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1098 if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1099 break Some(("CLTV expiry is too far in the future", 21, None));
1104 let mut res = Vec::with_capacity(8 + 128);
1105 if let Some(chan_update) = chan_update {
1106 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1107 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1109 else if code == 0x1000 | 13 {
1110 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1112 else if code == 0x1000 | 20 {
1113 res.extend_from_slice(&byte_utils::be16_to_array(chan_update.contents.flags));
1115 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1117 return_err!(err, code, &res[..]);
1122 (pending_forward_info, channel_state.unwrap())
1125 /// only fails if the channel does not yet have an assigned short_id
1126 /// May be called with channel_state already locked!
1127 fn get_channel_update(&self, chan: &Channel<ChanSigner>) -> Result<msgs::ChannelUpdate, LightningError> {
1128 let short_channel_id = match chan.get_short_channel_id() {
1129 None => return Err(LightningError{err: "Channel not yet established", action: msgs::ErrorAction::IgnoreError}),
1133 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1135 let unsigned = msgs::UnsignedChannelUpdate {
1136 chain_hash: self.genesis_hash,
1137 short_channel_id: short_channel_id,
1138 timestamp: chan.get_channel_update_count(),
1139 flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1140 cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1141 htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1142 fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1143 fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1144 excess_data: Vec::new(),
1147 let msg_hash = Sha256dHash::hash(&unsigned.encode()[..]);
1148 let sig = self.secp_ctx.sign(&hash_to_message!(&msg_hash[..]), &self.our_network_key);
1150 Ok(msgs::ChannelUpdate {
1156 /// Sends a payment along a given route.
1158 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1159 /// fields for more info.
1161 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1162 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1163 /// next hop knows the preimage to payment_hash they can claim an additional amount as
1164 /// specified in the last hop in the route! Thus, you should probably do your own
1165 /// payment_preimage tracking (which you should already be doing as they represent "proof of
1166 /// payment") and prevent double-sends yourself.
1168 /// May generate a SendHTLCs message event on success, which should be relayed.
1170 /// Raises APIError::RoutError when invalid route or forward parameter
1171 /// (cltv_delta, fee, node public key) is specified.
1172 /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1173 /// (including due to previous monitor update failure or new permanent monitor update failure).
1174 /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1175 /// relevant updates.
1177 /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1178 /// and you may wish to retry via a different route immediately.
1179 /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1180 /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1181 /// the payment via a different route unless you intend to pay twice!
1183 /// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
1184 /// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
1185 /// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
1186 /// must not contain multiple paths as otherwise the multipath data cannot be sent.
1187 /// If a payment_secret *is* provided, we assume that the invoice had the basic_mpp feature bit
1188 /// set (either as required or as available).
1189 pub fn send_payment(&self, route: Route, payment_hash: PaymentHash, payment_secret: Option<&[u8; 32]>) -> Result<(), APIError> {
1190 if route.hops.len() < 1 || route.hops.len() > 20 {
1191 return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1193 let our_node_id = self.get_our_node_id();
1194 for (idx, hop) in route.hops.iter().enumerate() {
1195 if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1196 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1200 let (session_priv, prng_seed) = self.keys_manager.get_onion_rand();
1202 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1204 let onion_keys = secp_call!(onion_utils::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1205 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1206 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, payment_secret, cur_height)?;
1207 if onion_utils::route_size_insane(&onion_payloads) {
1208 return Err(APIError::RouteError{err: "Route had too large size once"});
1210 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, &payment_hash);
1212 let _ = self.total_consistency_lock.read().unwrap();
1214 let mut channel_lock = self.channel_state.lock().unwrap();
1215 let err: Result<(), _> = loop {
1217 let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1218 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1219 Some(id) => id.clone(),
1222 let channel_state = &mut *channel_lock;
1223 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1225 if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1226 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1228 if !chan.get().is_live() {
1229 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1231 break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1232 route: route.clone(),
1233 session_priv: session_priv.clone(),
1234 first_hop_htlc_msat: htlc_msat,
1235 }, onion_packet), channel_state, chan)
1237 Some((update_add, commitment_signed, chan_monitor)) => {
1238 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1239 maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true);
1240 // Note that MonitorUpdateFailed here indicates (per function docs)
1241 // that we will resent the commitment update once we unfree monitor
1242 // updating, so we have to take special care that we don't return
1243 // something else in case we will resend later!
1244 return Err(APIError::MonitorUpdateFailed);
1247 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1248 node_id: route.hops.first().unwrap().pubkey,
1249 updates: msgs::CommitmentUpdate {
1250 update_add_htlcs: vec![update_add],
1251 update_fulfill_htlcs: Vec::new(),
1252 update_fail_htlcs: Vec::new(),
1253 update_fail_malformed_htlcs: Vec::new(),
1261 } else { unreachable!(); }
1265 match handle_error!(self, err, route.hops.first().unwrap().pubkey, channel_lock) {
1266 Ok(_) => unreachable!(),
1267 Err(e) => { Err(APIError::ChannelUnavailable { err: e.err }) }
1271 /// Call this upon creation of a funding transaction for the given channel.
1273 /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1274 /// or your counterparty can steal your funds!
1276 /// Panics if a funding transaction has already been provided for this channel.
1278 /// May panic if the funding_txo is duplicative with some other channel (note that this should
1279 /// be trivially prevented by using unique funding transaction keys per-channel).
1280 pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1281 let _ = self.total_consistency_lock.read().unwrap();
1283 let (mut chan, msg, chan_monitor) = {
1284 let mut channel_state = self.channel_state.lock().unwrap();
1285 let (res, chan) = match channel_state.by_id.remove(temporary_channel_id) {
1287 (chan.get_outbound_funding_created(funding_txo)
1288 .map_err(|e| if let ChannelError::Close(msg) = e {
1289 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1290 } else { unreachable!(); })
1295 match handle_error!(self, res, chan.get_their_node_id(), channel_state) {
1296 Ok(funding_msg) => {
1297 (chan, funding_msg.0, funding_msg.1)
1299 Err(_) => { return; }
1302 // Because we have exclusive ownership of the channel here we can release the channel_state
1303 // lock before add_update_monitor
1304 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1306 ChannelMonitorUpdateErr::PermanentFailure => {
1308 let mut channel_state = self.channel_state.lock().unwrap();
1309 match handle_error!(self, Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", *temporary_channel_id, chan.force_shutdown(), None)), chan.get_their_node_id(), channel_state) {
1310 Err(_) => { return; },
1311 Ok(()) => unreachable!(),
1315 ChannelMonitorUpdateErr::TemporaryFailure => {
1316 // Its completely fine to continue with a FundingCreated until the monitor
1317 // update is persisted, as long as we don't generate the FundingBroadcastSafe
1318 // until the monitor has been safely persisted (as funding broadcast is not,
1320 chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
1325 let mut channel_state = self.channel_state.lock().unwrap();
1326 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1327 node_id: chan.get_their_node_id(),
1330 match channel_state.by_id.entry(chan.channel_id()) {
1331 hash_map::Entry::Occupied(_) => {
1332 panic!("Generated duplicate funding txid?");
1334 hash_map::Entry::Vacant(e) => {
1340 fn get_announcement_sigs(&self, chan: &Channel<ChanSigner>) -> Option<msgs::AnnouncementSignatures> {
1341 if !chan.should_announce() { return None }
1343 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1345 Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1347 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1348 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1350 Some(msgs::AnnouncementSignatures {
1351 channel_id: chan.channel_id(),
1352 short_channel_id: chan.get_short_channel_id().unwrap(),
1353 node_signature: our_node_sig,
1354 bitcoin_signature: our_bitcoin_sig,
1358 /// Generates a signed node_announcement from the given arguments and creates a
1359 /// BroadcastNodeAnnouncement event.
1361 /// RGB is a node "color" and alias a printable human-readable string to describe this node to
1362 /// humans. They carry no in-protocol meaning.
1364 /// addresses represent the set (possibly empty) of socket addresses on which this node accepts
1365 /// incoming connections.
1366 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: msgs::NetAddressSet) {
1367 let _ = self.total_consistency_lock.read().unwrap();
1369 let announcement = msgs::UnsignedNodeAnnouncement {
1370 features: NodeFeatures::supported(),
1371 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1372 node_id: self.get_our_node_id(),
1374 addresses: addresses.to_vec(),
1375 excess_address_data: Vec::new(),
1376 excess_data: Vec::new(),
1378 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1380 let mut channel_state = self.channel_state.lock().unwrap();
1381 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
1382 msg: msgs::NodeAnnouncement {
1383 signature: self.secp_ctx.sign(&msghash, &self.our_network_key),
1384 contents: announcement
1389 /// Processes HTLCs which are pending waiting on random forward delay.
1391 /// Should only really ever be called in response to a PendingHTLCsForwardable event.
1392 /// Will likely generate further events.
1393 pub fn process_pending_htlc_forwards(&self) {
1394 let _ = self.total_consistency_lock.read().unwrap();
1396 let mut new_events = Vec::new();
1397 let mut failed_forwards = Vec::new();
1398 let mut handle_errors = Vec::new();
1400 let mut channel_state_lock = self.channel_state.lock().unwrap();
1401 let channel_state = &mut *channel_state_lock;
1403 for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1404 if short_chan_id != 0 {
1405 let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1406 Some(chan_id) => chan_id.clone(),
1408 failed_forwards.reserve(pending_forwards.len());
1409 for forward_info in pending_forwards.drain(..) {
1410 match forward_info {
1411 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info } => {
1412 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1413 short_channel_id: prev_short_channel_id,
1414 htlc_id: prev_htlc_id,
1415 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1417 failed_forwards.push((htlc_source, forward_info.payment_hash,
1418 HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: Vec::new() }
1421 HTLCForwardInfo::FailHTLC { .. } => {
1422 // Channel went away before we could fail it. This implies
1423 // the channel is now on chain and our counterparty is
1424 // trying to broadcast the HTLC-Timeout, but that's their
1425 // problem, not ours.
1432 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(forward_chan_id) {
1433 let mut add_htlc_msgs = Vec::new();
1434 let mut fail_htlc_msgs = Vec::new();
1435 for forward_info in pending_forwards.drain(..) {
1436 match forward_info {
1437 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1438 type_data: PendingForwardReceiveHTLCInfo::Forward {
1440 }, incoming_shared_secret, payment_hash, amt_to_forward, outgoing_cltv_value }, } => {
1441 log_trace!(self, "Adding HTLC from short id {} with payment_hash {} to channel with short id {} after delay", log_bytes!(payment_hash.0), prev_short_channel_id, short_chan_id);
1442 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1443 short_channel_id: prev_short_channel_id,
1444 htlc_id: prev_htlc_id,
1445 incoming_packet_shared_secret: incoming_shared_secret,
1447 match chan.get_mut().send_htlc(amt_to_forward, payment_hash, outgoing_cltv_value, htlc_source.clone(), onion_packet) {
1449 if let ChannelError::Ignore(msg) = e {
1450 log_trace!(self, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
1452 panic!("Stated return value requirements in send_htlc() were not met");
1454 let chan_update = self.get_channel_update(chan.get()).unwrap();
1455 failed_forwards.push((htlc_source, payment_hash,
1456 HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.encode_with_len() }
1462 Some(msg) => { add_htlc_msgs.push(msg); },
1464 // Nothing to do here...we're waiting on a remote
1465 // revoke_and_ack before we can add anymore HTLCs. The Channel
1466 // will automatically handle building the update_add_htlc and
1467 // commitment_signed messages when we can.
1468 // TODO: Do some kind of timer to set the channel as !is_live()
1469 // as we don't really want others relying on us relaying through
1470 // this channel currently :/.
1476 HTLCForwardInfo::AddHTLC { .. } => {
1477 panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
1479 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
1480 log_trace!(self, "Failing HTLC back to channel with short id {} after delay", short_chan_id);
1481 match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet) {
1483 if let ChannelError::Ignore(msg) = e {
1484 log_trace!(self, "Failed to fail backwards to short_id {}: {}", short_chan_id, msg);
1486 panic!("Stated return value requirements in get_update_fail_htlc() were not met");
1488 // fail-backs are best-effort, we probably already have one
1489 // pending, and if not that's OK, if not, the channel is on
1490 // the chain and sending the HTLC-Timeout is their problem.
1493 Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
1495 // Nothing to do here...we're waiting on a remote
1496 // revoke_and_ack before we can update the commitment
1497 // transaction. The Channel will automatically handle
1498 // building the update_fail_htlc and commitment_signed
1499 // messages when we can.
1500 // We don't need any kind of timer here as they should fail
1501 // the channel onto the chain if they can't get our
1502 // update_fail_htlc in time, it's not our problem.
1509 if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
1510 let (commitment_msg, monitor) = match chan.get_mut().send_commitment() {
1513 // We surely failed send_commitment due to bad keys, in that case
1514 // close channel and then send error message to peer.
1515 let their_node_id = chan.get().get_their_node_id();
1516 let err: Result<(), _> = match e {
1517 ChannelError::Ignore(_) => {
1518 panic!("Stated return value requirements in send_commitment() were not met");
1520 ChannelError::Close(msg) => {
1521 log_trace!(self, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
1522 let (channel_id, mut channel) = chan.remove_entry();
1523 if let Some(short_id) = channel.get_short_channel_id() {
1524 channel_state.short_to_id.remove(&short_id);
1526 Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, channel.force_shutdown(), self.get_channel_update(&channel).ok()))
1528 ChannelError::CloseDelayBroadcast { .. } => { panic!("Wait is only generated on receipt of channel_reestablish, which is handled by try_chan_entry, we don't bother to support it here"); }
1530 match handle_error!(self, err, their_node_id, channel_state) {
1531 Ok(_) => unreachable!(),
1532 Err(_) => { continue; },
1536 if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1537 handle_errors.push((chan.get().get_their_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
1540 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1541 node_id: chan.get().get_their_node_id(),
1542 updates: msgs::CommitmentUpdate {
1543 update_add_htlcs: add_htlc_msgs,
1544 update_fulfill_htlcs: Vec::new(),
1545 update_fail_htlcs: fail_htlc_msgs,
1546 update_fail_malformed_htlcs: Vec::new(),
1548 commitment_signed: commitment_msg,
1556 for forward_info in pending_forwards.drain(..) {
1557 match forward_info {
1558 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1559 type_data: PendingForwardReceiveHTLCInfo::Receive { payment_data },
1560 incoming_shared_secret, payment_hash, amt_to_forward, .. }, } => {
1561 let prev_hop_data = HTLCPreviousHopData {
1562 short_channel_id: prev_short_channel_id,
1563 htlc_id: prev_htlc_id,
1564 incoming_packet_shared_secret: incoming_shared_secret,
1567 let mut total_value = 0;
1568 let htlcs = channel_state.claimable_htlcs.entry((payment_hash, if let &Some(ref data) = &payment_data {
1569 Some(data.payment_secret.clone()) } else { None }))
1570 .or_insert(Vec::new());
1571 htlcs.push(ClaimableHTLC {
1573 value: amt_to_forward,
1574 payment_data: payment_data.clone(),
1576 if let &Some(ref data) = &payment_data {
1577 for htlc in htlcs.iter() {
1578 total_value += htlc.value;
1579 if htlc.payment_data.as_ref().unwrap().total_msat != data.total_msat {
1580 total_value = msgs::MAX_VALUE_MSAT;
1582 if total_value >= msgs::MAX_VALUE_MSAT { break; }
1584 if total_value >= msgs::MAX_VALUE_MSAT {
1585 for htlc in htlcs.iter() {
1586 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
1587 short_channel_id: htlc.src.short_channel_id,
1588 htlc_id: htlc.src.htlc_id,
1589 incoming_packet_shared_secret: htlc.src.incoming_packet_shared_secret,
1591 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(htlc.value).to_vec() }
1594 } else if total_value >= data.total_msat {
1595 new_events.push(events::Event::PaymentReceived {
1596 payment_hash: payment_hash,
1597 payment_secret: Some(data.payment_secret),
1602 new_events.push(events::Event::PaymentReceived {
1603 payment_hash: payment_hash,
1604 payment_secret: None,
1605 amt: amt_to_forward,
1609 HTLCForwardInfo::AddHTLC { .. } => {
1610 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
1612 HTLCForwardInfo::FailHTLC { .. } => {
1613 panic!("Got pending fail of our own HTLC");
1621 for (htlc_source, payment_hash, failure_reason) in failed_forwards.drain(..) {
1622 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, failure_reason);
1625 if handle_errors.len() > 0 {
1626 let mut channel_state_lock = self.channel_state.lock().unwrap();
1627 for (their_node_id, err) in handle_errors.drain(..) {
1628 let _ = handle_error!(self, err, their_node_id, channel_state_lock);
1632 if new_events.is_empty() { return }
1633 let mut events = self.pending_events.lock().unwrap();
1634 events.append(&mut new_events);
1637 /// If a peer is disconnected we mark any channels with that peer as 'disabled'.
1638 /// After some time, if channels are still disabled we need to broadcast a ChannelUpdate
1639 /// to inform the network about the uselessness of these channels.
1641 /// This method handles all the details, and must be called roughly once per minute.
1642 pub fn timer_chan_freshness_every_min(&self) {
1643 let _ = self.total_consistency_lock.read().unwrap();
1644 let mut channel_state_lock = self.channel_state.lock().unwrap();
1645 let channel_state = &mut *channel_state_lock;
1646 for (_, chan) in channel_state.by_id.iter_mut() {
1647 if chan.is_disabled_staged() && !chan.is_live() {
1648 if let Ok(update) = self.get_channel_update(&chan) {
1649 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1654 } else if chan.is_disabled_staged() && chan.is_live() {
1656 } else if chan.is_disabled_marked() {
1657 chan.to_disabled_staged();
1662 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1663 /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
1664 /// along the path (including in our own channel on which we received it).
1665 /// Returns false if no payment was found to fail backwards, true if the process of failing the
1666 /// HTLC backwards has been started.
1667 pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, payment_secret: &Option<[u8; 32]>) -> bool {
1668 let _ = self.total_consistency_lock.read().unwrap();
1670 let mut channel_state = Some(self.channel_state.lock().unwrap());
1671 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(*payment_hash, *payment_secret));
1672 if let Some(mut sources) = removed_source {
1673 for htlc in sources.drain(..) {
1674 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1675 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1676 HTLCSource::PreviousHopData(htlc.src), payment_hash,
1677 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(htlc.value).to_vec() });
1683 /// Fails an HTLC backwards to the sender of it to us.
1684 /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1685 /// There are several callsites that do stupid things like loop over a list of payment_hashes
1686 /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1687 /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1688 /// still-available channels.
1689 fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<ChanSigner>>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1690 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
1691 //identify whether we sent it or not based on the (I presume) very different runtime
1692 //between the branches here. We should make this async and move it into the forward HTLCs
1695 HTLCSource::OutboundRoute { ref route, .. } => {
1696 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1697 mem::drop(channel_state_lock);
1698 match &onion_error {
1699 &HTLCFailReason::LightningError { ref err } => {
1701 let (channel_update, payment_retryable, onion_error_code) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
1703 let (channel_update, payment_retryable, _) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
1704 // TODO: If we decided to blame ourselves (or one of our channels) in
1705 // process_onion_failure we should close that channel as it implies our
1706 // next-hop is needlessly blaming us!
1707 if let Some(update) = channel_update {
1708 self.channel_state.lock().unwrap().pending_msg_events.push(
1709 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1714 self.pending_events.lock().unwrap().push(
1715 events::Event::PaymentFailed {
1716 payment_hash: payment_hash.clone(),
1717 rejected_by_dest: !payment_retryable,
1719 error_code: onion_error_code
1723 &HTLCFailReason::Reason {
1727 // we get a fail_malformed_htlc from the first hop
1728 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1729 // failures here, but that would be insufficient as Router::get_route
1730 // generally ignores its view of our own channels as we provide them via
1732 // TODO: For non-temporary failures, we really should be closing the
1733 // channel here as we apparently can't relay through them anyway.
1734 self.pending_events.lock().unwrap().push(
1735 events::Event::PaymentFailed {
1736 payment_hash: payment_hash.clone(),
1737 rejected_by_dest: route.hops.len() == 1,
1739 error_code: Some(*failure_code),
1745 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1746 let err_packet = match onion_error {
1747 HTLCFailReason::Reason { failure_code, data } => {
1748 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1749 let packet = onion_utils::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1750 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1752 HTLCFailReason::LightningError { err } => {
1753 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built LightningError", log_bytes!(payment_hash.0));
1754 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1758 let mut forward_event = None;
1759 if channel_state_lock.forward_htlcs.is_empty() {
1760 forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
1762 match channel_state_lock.forward_htlcs.entry(short_channel_id) {
1763 hash_map::Entry::Occupied(mut entry) => {
1764 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id, err_packet });
1766 hash_map::Entry::Vacant(entry) => {
1767 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id, err_packet }));
1770 mem::drop(channel_state_lock);
1771 if let Some(time) = forward_event {
1772 let mut pending_events = self.pending_events.lock().unwrap();
1773 pending_events.push(events::Event::PendingHTLCsForwardable {
1774 time_forwardable: time
1781 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1782 /// generating message events for the net layer to claim the payment, if possible. Thus, you
1783 /// should probably kick the net layer to go send messages if this returns true!
1785 /// You must specify the expected amounts for this HTLC, and we will only claim HTLCs
1786 /// available within a few percent of the expected amount. This is critical for several
1787 /// reasons : a) it avoids providing senders with `proof-of-payment` (in the form of the
1788 /// payment_preimage without having provided the full value and b) it avoids certain
1789 /// privacy-breaking recipient-probing attacks which may reveal payment activity to
1790 /// motivated attackers.
1792 /// May panic if called except in response to a PaymentReceived event.
1793 pub fn claim_funds(&self, payment_preimage: PaymentPreimage, payment_secret: &Option<[u8; 32]>, expected_amount: u64) -> bool {
1794 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1796 let _ = self.total_consistency_lock.read().unwrap();
1798 let mut channel_state = Some(self.channel_state.lock().unwrap());
1799 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(payment_hash, *payment_secret));
1800 if let Some(mut sources) = removed_source {
1801 for htlc in sources.drain(..) {
1802 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1803 if htlc.value < expected_amount || htlc.value > expected_amount * 2 {
1804 let mut htlc_msat_data = byte_utils::be64_to_array(htlc.value).to_vec();
1805 let mut height_data = byte_utils::be32_to_array(self.latest_block_height.load(Ordering::Acquire) as u32).to_vec();
1806 htlc_msat_data.append(&mut height_data);
1807 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1808 HTLCSource::PreviousHopData(htlc.src), &payment_hash,
1809 HTLCFailReason::Reason { failure_code: 0x4000|15, data: htlc_msat_data });
1811 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc.src), payment_preimage);
1817 fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<ChanSigner>>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1818 let (their_node_id, err) = loop {
1820 HTLCSource::OutboundRoute { .. } => {
1821 mem::drop(channel_state_lock);
1822 let mut pending_events = self.pending_events.lock().unwrap();
1823 pending_events.push(events::Event::PaymentSent {
1827 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1828 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1829 let channel_state = &mut *channel_state_lock;
1831 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1832 Some(chan_id) => chan_id.clone(),
1834 // TODO: There is probably a channel manager somewhere that needs to
1835 // learn the preimage as the channel already hit the chain and that's
1836 // why it's missing.
1841 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(chan_id) {
1842 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
1843 match chan.get_mut().get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1844 Ok((msgs, monitor_option)) => {
1845 if let Some(chan_monitor) = monitor_option {
1846 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1847 if was_frozen_for_monitor {
1848 assert!(msgs.is_none());
1850 break (chan.get().get_their_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, msgs.is_some()));
1854 if let Some((msg, commitment_signed)) = msgs {
1855 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1856 node_id: chan.get().get_their_node_id(),
1857 updates: msgs::CommitmentUpdate {
1858 update_add_htlcs: Vec::new(),
1859 update_fulfill_htlcs: vec![msg],
1860 update_fail_htlcs: Vec::new(),
1861 update_fail_malformed_htlcs: Vec::new(),
1869 // TODO: There is probably a channel manager somewhere that needs to
1870 // learn the preimage as the channel may be about to hit the chain.
1871 //TODO: Do something with e?
1875 } else { unreachable!(); }
1881 let _ = handle_error!(self, err, their_node_id, channel_state_lock);
1884 /// Gets the node_id held by this ChannelManager
1885 pub fn get_our_node_id(&self) -> PublicKey {
1886 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1889 /// Used to restore channels to normal operation after a
1890 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1892 pub fn test_restore_channel_monitor(&self) {
1893 let mut close_results = Vec::new();
1894 let mut htlc_forwards = Vec::new();
1895 let mut htlc_failures = Vec::new();
1896 let mut pending_events = Vec::new();
1897 let _ = self.total_consistency_lock.read().unwrap();
1900 let mut channel_lock = self.channel_state.lock().unwrap();
1901 let channel_state = &mut *channel_lock;
1902 let short_to_id = &mut channel_state.short_to_id;
1903 let pending_msg_events = &mut channel_state.pending_msg_events;
1904 channel_state.by_id.retain(|_, channel| {
1905 if channel.is_awaiting_monitor_update() {
1906 let chan_monitor = channel.channel_monitor().clone();
1907 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1909 ChannelMonitorUpdateErr::PermanentFailure => {
1910 // TODO: There may be some pending HTLCs that we intended to fail
1911 // backwards when a monitor update failed. We should make sure
1912 // knowledge of those gets moved into the appropriate in-memory
1913 // ChannelMonitor and they get failed backwards once we get
1914 // on-chain confirmations.
1915 // Note I think #198 addresses this, so once it's merged a test
1916 // should be written.
1917 if let Some(short_id) = channel.get_short_channel_id() {
1918 short_to_id.remove(&short_id);
1920 close_results.push(channel.force_shutdown());
1921 if let Ok(update) = self.get_channel_update(&channel) {
1922 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1928 ChannelMonitorUpdateErr::TemporaryFailure => true,
1931 let (raa, commitment_update, order, pending_forwards, mut pending_failures, needs_broadcast_safe, funding_locked) = channel.monitor_updating_restored();
1932 if !pending_forwards.is_empty() {
1933 htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1935 htlc_failures.append(&mut pending_failures);
1937 macro_rules! handle_cs { () => {
1938 if let Some(update) = commitment_update {
1939 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1940 node_id: channel.get_their_node_id(),
1945 macro_rules! handle_raa { () => {
1946 if let Some(revoke_and_ack) = raa {
1947 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1948 node_id: channel.get_their_node_id(),
1949 msg: revoke_and_ack,
1954 RAACommitmentOrder::CommitmentFirst => {
1958 RAACommitmentOrder::RevokeAndACKFirst => {
1963 if needs_broadcast_safe {
1964 pending_events.push(events::Event::FundingBroadcastSafe {
1965 funding_txo: channel.get_funding_txo().unwrap(),
1966 user_channel_id: channel.get_user_id(),
1969 if let Some(msg) = funding_locked {
1970 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
1971 node_id: channel.get_their_node_id(),
1974 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
1975 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1976 node_id: channel.get_their_node_id(),
1977 msg: announcement_sigs,
1980 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
1988 self.pending_events.lock().unwrap().append(&mut pending_events);
1990 for failure in htlc_failures.drain(..) {
1991 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1993 self.forward_htlcs(&mut htlc_forwards[..]);
1995 for res in close_results.drain(..) {
1996 self.finish_force_close_channel(res);
2000 fn internal_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
2001 if msg.chain_hash != self.genesis_hash {
2002 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
2005 let channel = Channel::new_from_req(&*self.fee_estimator, &self.keys_manager, their_node_id.clone(), their_features, msg, 0, Arc::clone(&self.logger), &self.default_configuration)
2006 .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
2007 let mut channel_state_lock = self.channel_state.lock().unwrap();
2008 let channel_state = &mut *channel_state_lock;
2009 match channel_state.by_id.entry(channel.channel_id()) {
2010 hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
2011 hash_map::Entry::Vacant(entry) => {
2012 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
2013 node_id: their_node_id.clone(),
2014 msg: channel.get_accept_channel(),
2016 entry.insert(channel);
2022 fn internal_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
2023 let (value, output_script, user_id) = {
2024 let mut channel_lock = self.channel_state.lock().unwrap();
2025 let channel_state = &mut *channel_lock;
2026 match channel_state.by_id.entry(msg.temporary_channel_id) {
2027 hash_map::Entry::Occupied(mut chan) => {
2028 if chan.get().get_their_node_id() != *their_node_id {
2029 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
2031 try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration, their_features), channel_state, chan);
2032 (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
2034 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
2037 let mut pending_events = self.pending_events.lock().unwrap();
2038 pending_events.push(events::Event::FundingGenerationReady {
2039 temporary_channel_id: msg.temporary_channel_id,
2040 channel_value_satoshis: value,
2041 output_script: output_script,
2042 user_channel_id: user_id,
2047 fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
2048 let ((funding_msg, monitor_update), mut chan) = {
2049 let mut channel_lock = self.channel_state.lock().unwrap();
2050 let channel_state = &mut *channel_lock;
2051 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
2052 hash_map::Entry::Occupied(mut chan) => {
2053 if chan.get().get_their_node_id() != *their_node_id {
2054 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
2056 (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
2058 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
2061 // Because we have exclusive ownership of the channel here we can release the channel_state
2062 // lock before add_update_monitor
2063 if let Err(e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
2065 ChannelMonitorUpdateErr::PermanentFailure => {
2066 // Note that we reply with the new channel_id in error messages if we gave up on the
2067 // channel, not the temporary_channel_id. This is compatible with ourselves, but the
2068 // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
2069 // any messages referencing a previously-closed channel anyway.
2070 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", funding_msg.channel_id, chan.force_shutdown(), None));
2072 ChannelMonitorUpdateErr::TemporaryFailure => {
2073 // There's no problem signing a counterparty's funding transaction if our monitor
2074 // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
2075 // accepted payment from yet. We do, however, need to wait to send our funding_locked
2076 // until we have persisted our monitor.
2077 chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
2081 let mut channel_state_lock = self.channel_state.lock().unwrap();
2082 let channel_state = &mut *channel_state_lock;
2083 match channel_state.by_id.entry(funding_msg.channel_id) {
2084 hash_map::Entry::Occupied(_) => {
2085 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
2087 hash_map::Entry::Vacant(e) => {
2088 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
2089 node_id: their_node_id.clone(),
2098 fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
2099 let (funding_txo, user_id) = {
2100 let mut channel_lock = self.channel_state.lock().unwrap();
2101 let channel_state = &mut *channel_lock;
2102 match channel_state.by_id.entry(msg.channel_id) {
2103 hash_map::Entry::Occupied(mut chan) => {
2104 if chan.get().get_their_node_id() != *their_node_id {
2105 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2107 let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
2108 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2109 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
2111 (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
2113 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2116 let mut pending_events = self.pending_events.lock().unwrap();
2117 pending_events.push(events::Event::FundingBroadcastSafe {
2118 funding_txo: funding_txo,
2119 user_channel_id: user_id,
2124 fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
2125 let mut channel_state_lock = self.channel_state.lock().unwrap();
2126 let channel_state = &mut *channel_state_lock;
2127 match channel_state.by_id.entry(msg.channel_id) {
2128 hash_map::Entry::Occupied(mut chan) => {
2129 if chan.get().get_their_node_id() != *their_node_id {
2130 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2132 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
2133 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
2134 // If we see locking block before receiving remote funding_locked, we broadcast our
2135 // announcement_sigs at remote funding_locked reception. If we receive remote
2136 // funding_locked before seeing locking block, we broadcast our announcement_sigs at locking
2137 // block connection. We should guanrantee to broadcast announcement_sigs to our peer whatever
2138 // the order of the events but our peer may not receive it due to disconnection. The specs
2139 // lacking an acknowledgement for announcement_sigs we may have to re-send them at peer
2140 // connection in the future if simultaneous misses by both peers due to network/hardware
2141 // failures is an issue. Note, to achieve its goal, only one of the announcement_sigs needs
2142 // to be received, from then sigs are going to be flood to the whole network.
2143 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2144 node_id: their_node_id.clone(),
2145 msg: announcement_sigs,
2150 hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2154 fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
2155 let (mut dropped_htlcs, chan_option) = {
2156 let mut channel_state_lock = self.channel_state.lock().unwrap();
2157 let channel_state = &mut *channel_state_lock;
2159 match channel_state.by_id.entry(msg.channel_id.clone()) {
2160 hash_map::Entry::Occupied(mut chan_entry) => {
2161 if chan_entry.get().get_their_node_id() != *their_node_id {
2162 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2164 let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
2165 if let Some(msg) = shutdown {
2166 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2167 node_id: their_node_id.clone(),
2171 if let Some(msg) = closing_signed {
2172 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2173 node_id: their_node_id.clone(),
2177 if chan_entry.get().is_shutdown() {
2178 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2179 channel_state.short_to_id.remove(&short_id);
2181 (dropped_htlcs, Some(chan_entry.remove_entry().1))
2182 } else { (dropped_htlcs, None) }
2184 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2187 for htlc_source in dropped_htlcs.drain(..) {
2188 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2190 if let Some(chan) = chan_option {
2191 if let Ok(update) = self.get_channel_update(&chan) {
2192 let mut channel_state = self.channel_state.lock().unwrap();
2193 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2201 fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
2202 let (tx, chan_option) = {
2203 let mut channel_state_lock = self.channel_state.lock().unwrap();
2204 let channel_state = &mut *channel_state_lock;
2205 match channel_state.by_id.entry(msg.channel_id.clone()) {
2206 hash_map::Entry::Occupied(mut chan_entry) => {
2207 if chan_entry.get().get_their_node_id() != *their_node_id {
2208 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2210 let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
2211 if let Some(msg) = closing_signed {
2212 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2213 node_id: their_node_id.clone(),
2218 // We're done with this channel, we've got a signed closing transaction and
2219 // will send the closing_signed back to the remote peer upon return. This
2220 // also implies there are no pending HTLCs left on the channel, so we can
2221 // fully delete it from tracking (the channel monitor is still around to
2222 // watch for old state broadcasts)!
2223 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2224 channel_state.short_to_id.remove(&short_id);
2226 (tx, Some(chan_entry.remove_entry().1))
2227 } else { (tx, None) }
2229 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2232 if let Some(broadcast_tx) = tx {
2233 log_trace!(self, "Broadcast onchain {}", log_tx!(broadcast_tx));
2234 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2236 if let Some(chan) = chan_option {
2237 if let Ok(update) = self.get_channel_update(&chan) {
2238 let mut channel_state = self.channel_state.lock().unwrap();
2239 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2247 fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2248 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2249 //determine the state of the payment based on our response/if we forward anything/the time
2250 //we take to respond. We should take care to avoid allowing such an attack.
2252 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2253 //us repeatedly garbled in different ways, and compare our error messages, which are
2254 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
2255 //but we should prevent it anyway.
2257 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2258 let channel_state = &mut *channel_state_lock;
2260 match channel_state.by_id.entry(msg.channel_id) {
2261 hash_map::Entry::Occupied(mut chan) => {
2262 if chan.get().get_their_node_id() != *their_node_id {
2263 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2265 if !chan.get().is_usable() {
2266 // If the update_add is completely bogus, the call will Err and we will close,
2267 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2268 // want to reject the new HTLC and fail it backwards instead of forwarding.
2269 if let PendingHTLCStatus::Forward(PendingHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2270 let chan_update = self.get_channel_update(chan.get());
2271 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2272 channel_id: msg.channel_id,
2273 htlc_id: msg.htlc_id,
2274 reason: if let Ok(update) = chan_update {
2275 // TODO: Note that |20 is defined as "channel FROM the processing
2276 // node has been disabled" (emphasis mine), which seems to imply
2277 // that we can't return |20 for an inbound channel being disabled.
2278 // This probably needs a spec update but should definitely be
2280 onion_utils::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &{
2281 let mut res = Vec::with_capacity(8 + 128);
2282 res.extend_from_slice(&byte_utils::be16_to_array(update.contents.flags));
2283 res.extend_from_slice(&update.encode_with_len()[..]);
2287 // This can only happen if the channel isn't in the fully-funded
2288 // state yet, implying our counterparty is trying to route payments
2289 // over the channel back to themselves (cause no one else should
2290 // know the short_id is a lightning channel yet). We should have no
2291 // problem just calling this unknown_next_peer
2292 onion_utils::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2297 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2299 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2304 fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2305 let mut channel_lock = self.channel_state.lock().unwrap();
2307 let channel_state = &mut *channel_lock;
2308 match channel_state.by_id.entry(msg.channel_id) {
2309 hash_map::Entry::Occupied(mut chan) => {
2310 if chan.get().get_their_node_id() != *their_node_id {
2311 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2313 try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2315 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2318 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2322 fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2323 let mut channel_lock = self.channel_state.lock().unwrap();
2324 let channel_state = &mut *channel_lock;
2325 match channel_state.by_id.entry(msg.channel_id) {
2326 hash_map::Entry::Occupied(mut chan) => {
2327 if chan.get().get_their_node_id() != *their_node_id {
2328 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2330 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::LightningError { err: msg.reason.clone() }), channel_state, chan);
2332 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2337 fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2338 let mut channel_lock = self.channel_state.lock().unwrap();
2339 let channel_state = &mut *channel_lock;
2340 match channel_state.by_id.entry(msg.channel_id) {
2341 hash_map::Entry::Occupied(mut chan) => {
2342 if chan.get().get_their_node_id() != *their_node_id {
2343 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2345 if (msg.failure_code & 0x8000) == 0 {
2346 try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2348 try_chan_entry!(self, chan.get_mut().update_fail_malformed_htlc(&msg, HTLCFailReason::Reason { failure_code: msg.failure_code, data: Vec::new() }), channel_state, chan);
2351 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2355 fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2356 let mut channel_state_lock = self.channel_state.lock().unwrap();
2357 let channel_state = &mut *channel_state_lock;
2358 match channel_state.by_id.entry(msg.channel_id) {
2359 hash_map::Entry::Occupied(mut chan) => {
2360 if chan.get().get_their_node_id() != *their_node_id {
2361 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2363 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2364 try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2365 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2366 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some());
2367 //TODO: Rebroadcast closing_signed if present on monitor update restoration
2369 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2370 node_id: their_node_id.clone(),
2371 msg: revoke_and_ack,
2373 if let Some(msg) = commitment_signed {
2374 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2375 node_id: their_node_id.clone(),
2376 updates: msgs::CommitmentUpdate {
2377 update_add_htlcs: Vec::new(),
2378 update_fulfill_htlcs: Vec::new(),
2379 update_fail_htlcs: Vec::new(),
2380 update_fail_malformed_htlcs: Vec::new(),
2382 commitment_signed: msg,
2386 if let Some(msg) = closing_signed {
2387 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2388 node_id: their_node_id.clone(),
2394 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2399 fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingHTLCInfo, u64)>)]) {
2400 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2401 let mut forward_event = None;
2402 if !pending_forwards.is_empty() {
2403 let mut channel_state = self.channel_state.lock().unwrap();
2404 if channel_state.forward_htlcs.is_empty() {
2405 forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS))
2407 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2408 match channel_state.forward_htlcs.entry(match forward_info.type_data {
2409 PendingForwardReceiveHTLCInfo::Forward { short_channel_id, .. } => short_channel_id,
2410 PendingForwardReceiveHTLCInfo::Receive { .. } => 0,
2412 hash_map::Entry::Occupied(mut entry) => {
2413 entry.get_mut().push(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info });
2415 hash_map::Entry::Vacant(entry) => {
2416 entry.insert(vec!(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info }));
2421 match forward_event {
2423 let mut pending_events = self.pending_events.lock().unwrap();
2424 pending_events.push(events::Event::PendingHTLCsForwardable {
2425 time_forwardable: time
2433 fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2434 let (pending_forwards, mut pending_failures, short_channel_id) = {
2435 let mut channel_state_lock = self.channel_state.lock().unwrap();
2436 let channel_state = &mut *channel_state_lock;
2437 match channel_state.by_id.entry(msg.channel_id) {
2438 hash_map::Entry::Occupied(mut chan) => {
2439 if chan.get().get_their_node_id() != *their_node_id {
2440 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2442 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2443 let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2444 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2445 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2446 if was_frozen_for_monitor {
2447 assert!(commitment_update.is_none() && closing_signed.is_none() && pending_forwards.is_empty() && pending_failures.is_empty());
2448 return Err(MsgHandleErrInternal::ignore_no_close("Previous monitor update failure prevented responses to RAA"));
2450 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, commitment_update.is_some(), pending_forwards, pending_failures);
2453 if let Some(updates) = commitment_update {
2454 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2455 node_id: their_node_id.clone(),
2459 if let Some(msg) = closing_signed {
2460 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2461 node_id: their_node_id.clone(),
2465 (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2467 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2470 for failure in pending_failures.drain(..) {
2471 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2473 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2478 fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2479 let mut channel_lock = self.channel_state.lock().unwrap();
2480 let channel_state = &mut *channel_lock;
2481 match channel_state.by_id.entry(msg.channel_id) {
2482 hash_map::Entry::Occupied(mut chan) => {
2483 if chan.get().get_their_node_id() != *their_node_id {
2484 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2486 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2488 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2493 fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2494 let mut channel_state_lock = self.channel_state.lock().unwrap();
2495 let channel_state = &mut *channel_state_lock;
2497 match channel_state.by_id.entry(msg.channel_id) {
2498 hash_map::Entry::Occupied(mut chan) => {
2499 if chan.get().get_their_node_id() != *their_node_id {
2500 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2502 if !chan.get().is_usable() {
2503 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it", action: msgs::ErrorAction::IgnoreError}));
2506 let our_node_id = self.get_our_node_id();
2507 let (announcement, our_bitcoin_sig) =
2508 try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2510 let were_node_one = announcement.node_id_1 == our_node_id;
2511 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
2512 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2513 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2514 try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2517 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2519 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2520 msg: msgs::ChannelAnnouncement {
2521 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2522 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2523 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2524 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2525 contents: announcement,
2527 update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2530 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2535 fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2536 let mut channel_state_lock = self.channel_state.lock().unwrap();
2537 let channel_state = &mut *channel_state_lock;
2539 match channel_state.by_id.entry(msg.channel_id) {
2540 hash_map::Entry::Occupied(mut chan) => {
2541 if chan.get().get_their_node_id() != *their_node_id {
2542 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2544 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2545 try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2546 if let Some(monitor) = channel_monitor {
2547 if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2548 // channel_reestablish doesn't guarantee the order it returns is sensical
2549 // for the messages it returns, but if we're setting what messages to
2550 // re-transmit on monitor update success, we need to make sure it is sane.
2551 if revoke_and_ack.is_none() {
2552 order = RAACommitmentOrder::CommitmentFirst;
2554 if commitment_update.is_none() {
2555 order = RAACommitmentOrder::RevokeAndACKFirst;
2557 return_monitor_err!(self, e, channel_state, chan, order, revoke_and_ack.is_some(), commitment_update.is_some());
2558 //TODO: Resend the funding_locked if needed once we get the monitor running again
2561 if let Some(msg) = funding_locked {
2562 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2563 node_id: their_node_id.clone(),
2567 macro_rules! send_raa { () => {
2568 if let Some(msg) = revoke_and_ack {
2569 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2570 node_id: their_node_id.clone(),
2575 macro_rules! send_cu { () => {
2576 if let Some(updates) = commitment_update {
2577 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2578 node_id: their_node_id.clone(),
2584 RAACommitmentOrder::RevokeAndACKFirst => {
2588 RAACommitmentOrder::CommitmentFirst => {
2593 if let Some(msg) = shutdown {
2594 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2595 node_id: their_node_id.clone(),
2601 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2605 /// Begin Update fee process. Allowed only on an outbound channel.
2606 /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2607 /// PeerManager::process_events afterwards.
2608 /// Note: This API is likely to change!
2610 pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2611 let _ = self.total_consistency_lock.read().unwrap();
2612 let mut channel_state_lock = self.channel_state.lock().unwrap();
2614 let err: Result<(), _> = loop {
2615 let channel_state = &mut *channel_state_lock;
2617 match channel_state.by_id.entry(channel_id) {
2618 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2619 hash_map::Entry::Occupied(mut chan) => {
2620 if !chan.get().is_outbound() {
2621 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2623 if chan.get().is_awaiting_monitor_update() {
2624 return Err(APIError::MonitorUpdateFailed);
2626 if !chan.get().is_live() {
2627 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2629 their_node_id = chan.get().get_their_node_id();
2630 if let Some((update_fee, commitment_signed, chan_monitor)) =
2631 break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2633 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2636 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2637 node_id: chan.get().get_their_node_id(),
2638 updates: msgs::CommitmentUpdate {
2639 update_add_htlcs: Vec::new(),
2640 update_fulfill_htlcs: Vec::new(),
2641 update_fail_htlcs: Vec::new(),
2642 update_fail_malformed_htlcs: Vec::new(),
2643 update_fee: Some(update_fee),
2653 match handle_error!(self, err, their_node_id, channel_state_lock) {
2654 Ok(_) => unreachable!(),
2655 Err(e) => { Err(APIError::APIMisuseError { err: e.err })}
2660 impl<ChanSigner: ChannelKeys, M: Deref> events::MessageSendEventsProvider for ChannelManager<ChanSigner, M> where M::Target: ManyChannelMonitor {
2661 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2662 // TODO: Event release to users and serialization is currently race-y: it's very easy for a
2663 // user to serialize a ChannelManager with pending events in it and lose those events on
2664 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2666 //TODO: This behavior should be documented.
2667 for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2668 if let Some(preimage) = htlc_update.payment_preimage {
2669 log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2670 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2672 log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2673 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2678 let mut ret = Vec::new();
2679 let mut channel_state = self.channel_state.lock().unwrap();
2680 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2685 impl<ChanSigner: ChannelKeys, M: Deref> events::EventsProvider for ChannelManager<ChanSigner, M> where M::Target: ManyChannelMonitor {
2686 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2687 // TODO: Event release to users and serialization is currently race-y: it's very easy for a
2688 // user to serialize a ChannelManager with pending events in it and lose those events on
2689 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2691 //TODO: This behavior should be documented.
2692 for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2693 if let Some(preimage) = htlc_update.payment_preimage {
2694 log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2695 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2697 log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2698 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2703 let mut ret = Vec::new();
2704 let mut pending_events = self.pending_events.lock().unwrap();
2705 mem::swap(&mut ret, &mut *pending_events);
2710 impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send> ChainListener for ChannelManager<ChanSigner, M> where M::Target: ManyChannelMonitor {
2711 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2712 let header_hash = header.bitcoin_hash();
2713 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2714 let _ = self.total_consistency_lock.read().unwrap();
2715 let mut failed_channels = Vec::new();
2717 let mut channel_lock = self.channel_state.lock().unwrap();
2718 let channel_state = &mut *channel_lock;
2719 let short_to_id = &mut channel_state.short_to_id;
2720 let pending_msg_events = &mut channel_state.pending_msg_events;
2721 channel_state.by_id.retain(|_, channel| {
2722 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2723 if let Ok(Some(funding_locked)) = chan_res {
2724 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2725 node_id: channel.get_their_node_id(),
2726 msg: funding_locked,
2728 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2729 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2730 node_id: channel.get_their_node_id(),
2731 msg: announcement_sigs,
2734 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2735 } else if let Err(e) = chan_res {
2736 pending_msg_events.push(events::MessageSendEvent::HandleError {
2737 node_id: channel.get_their_node_id(),
2738 action: msgs::ErrorAction::SendErrorMessage { msg: e },
2742 if let Some(funding_txo) = channel.get_funding_txo() {
2743 for tx in txn_matched {
2744 for inp in tx.input.iter() {
2745 if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2746 log_trace!(self, "Detected channel-closing tx {} spending {}:{}, closing channel {}", tx.txid(), inp.previous_output.txid, inp.previous_output.vout, log_bytes!(channel.channel_id()));
2747 if let Some(short_id) = channel.get_short_channel_id() {
2748 short_to_id.remove(&short_id);
2750 // It looks like our counterparty went on-chain. We go ahead and
2751 // broadcast our latest local state as well here, just in case its
2752 // some kind of SPV attack, though we expect these to be dropped.
2753 failed_channels.push(channel.force_shutdown());
2754 if let Ok(update) = self.get_channel_update(&channel) {
2755 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2764 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2765 if let Some(short_id) = channel.get_short_channel_id() {
2766 short_to_id.remove(&short_id);
2768 failed_channels.push(channel.force_shutdown());
2769 // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2770 // the latest local tx for us, so we should skip that here (it doesn't really
2771 // hurt anything, but does make tests a bit simpler).
2772 failed_channels.last_mut().unwrap().0 = Vec::new();
2773 if let Ok(update) = self.get_channel_update(&channel) {
2774 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2783 for failure in failed_channels.drain(..) {
2784 self.finish_force_close_channel(failure);
2786 self.latest_block_height.store(height as usize, Ordering::Release);
2787 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2790 /// We force-close the channel without letting our counterparty participate in the shutdown
2791 fn block_disconnected(&self, header: &BlockHeader, _: u32) {
2792 let _ = self.total_consistency_lock.read().unwrap();
2793 let mut failed_channels = Vec::new();
2795 let mut channel_lock = self.channel_state.lock().unwrap();
2796 let channel_state = &mut *channel_lock;
2797 let short_to_id = &mut channel_state.short_to_id;
2798 let pending_msg_events = &mut channel_state.pending_msg_events;
2799 channel_state.by_id.retain(|_, v| {
2800 if v.block_disconnected(header) {
2801 if let Some(short_id) = v.get_short_channel_id() {
2802 short_to_id.remove(&short_id);
2804 failed_channels.push(v.force_shutdown());
2805 if let Ok(update) = self.get_channel_update(&v) {
2806 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2816 for failure in failed_channels.drain(..) {
2817 self.finish_force_close_channel(failure);
2819 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2820 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2824 impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send> ChannelMessageHandler for ChannelManager<ChanSigner, M> where M::Target: ManyChannelMonitor {
2825 fn handle_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) {
2826 let _ = self.total_consistency_lock.read().unwrap();
2827 let res = self.internal_open_channel(their_node_id, their_features, msg);
2829 let mut channel_state_lock = self.channel_state.lock().unwrap();
2830 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2834 fn handle_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) {
2835 let _ = self.total_consistency_lock.read().unwrap();
2836 let res = self.internal_accept_channel(their_node_id, their_features, msg);
2838 let mut channel_state_lock = self.channel_state.lock().unwrap();
2839 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2843 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
2844 let _ = self.total_consistency_lock.read().unwrap();
2845 let res = self.internal_funding_created(their_node_id, msg);
2847 let mut channel_state_lock = self.channel_state.lock().unwrap();
2848 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2852 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
2853 let _ = self.total_consistency_lock.read().unwrap();
2854 let res = self.internal_funding_signed(their_node_id, msg);
2856 let mut channel_state_lock = self.channel_state.lock().unwrap();
2857 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2861 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) {
2862 let _ = self.total_consistency_lock.read().unwrap();
2863 let res = self.internal_funding_locked(their_node_id, msg);
2865 let mut channel_state_lock = self.channel_state.lock().unwrap();
2866 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2870 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) {
2871 let _ = self.total_consistency_lock.read().unwrap();
2872 let res = self.internal_shutdown(their_node_id, msg);
2874 let mut channel_state_lock = self.channel_state.lock().unwrap();
2875 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2879 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
2880 let _ = self.total_consistency_lock.read().unwrap();
2881 let res = self.internal_closing_signed(their_node_id, msg);
2883 let mut channel_state_lock = self.channel_state.lock().unwrap();
2884 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2888 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
2889 let _ = self.total_consistency_lock.read().unwrap();
2890 let res = self.internal_update_add_htlc(their_node_id, msg);
2892 let mut channel_state_lock = self.channel_state.lock().unwrap();
2893 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2897 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
2898 let _ = self.total_consistency_lock.read().unwrap();
2899 let res = self.internal_update_fulfill_htlc(their_node_id, msg);
2901 let mut channel_state_lock = self.channel_state.lock().unwrap();
2902 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2906 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
2907 let _ = self.total_consistency_lock.read().unwrap();
2908 let res = self.internal_update_fail_htlc(their_node_id, msg);
2910 let mut channel_state_lock = self.channel_state.lock().unwrap();
2911 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2915 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
2916 let _ = self.total_consistency_lock.read().unwrap();
2917 let res = self.internal_update_fail_malformed_htlc(their_node_id, msg);
2919 let mut channel_state_lock = self.channel_state.lock().unwrap();
2920 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2924 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
2925 let _ = self.total_consistency_lock.read().unwrap();
2926 let res = self.internal_commitment_signed(their_node_id, msg);
2928 let mut channel_state_lock = self.channel_state.lock().unwrap();
2929 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2933 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
2934 let _ = self.total_consistency_lock.read().unwrap();
2935 let res = self.internal_revoke_and_ack(their_node_id, msg);
2937 let mut channel_state_lock = self.channel_state.lock().unwrap();
2938 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2942 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
2943 let _ = self.total_consistency_lock.read().unwrap();
2944 let res = self.internal_update_fee(their_node_id, msg);
2946 let mut channel_state_lock = self.channel_state.lock().unwrap();
2947 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2951 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
2952 let _ = self.total_consistency_lock.read().unwrap();
2953 let res = self.internal_announcement_signatures(their_node_id, msg);
2955 let mut channel_state_lock = self.channel_state.lock().unwrap();
2956 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2960 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
2961 let _ = self.total_consistency_lock.read().unwrap();
2962 let res = self.internal_channel_reestablish(their_node_id, msg);
2964 let mut channel_state_lock = self.channel_state.lock().unwrap();
2965 let _ = handle_error!(self, res, *their_node_id, channel_state_lock);
2969 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2970 let _ = self.total_consistency_lock.read().unwrap();
2971 let mut failed_channels = Vec::new();
2972 let mut failed_payments = Vec::new();
2973 let mut no_channels_remain = true;
2975 let mut channel_state_lock = self.channel_state.lock().unwrap();
2976 let channel_state = &mut *channel_state_lock;
2977 let short_to_id = &mut channel_state.short_to_id;
2978 let pending_msg_events = &mut channel_state.pending_msg_events;
2979 if no_connection_possible {
2980 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2981 channel_state.by_id.retain(|_, chan| {
2982 if chan.get_their_node_id() == *their_node_id {
2983 if let Some(short_id) = chan.get_short_channel_id() {
2984 short_to_id.remove(&short_id);
2986 failed_channels.push(chan.force_shutdown());
2987 if let Ok(update) = self.get_channel_update(&chan) {
2988 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2998 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2999 channel_state.by_id.retain(|_, chan| {
3000 if chan.get_their_node_id() == *their_node_id {
3001 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
3002 chan.to_disabled_marked();
3003 if !failed_adds.is_empty() {
3004 let chan_update = self.get_channel_update(&chan).map(|u| u.encode_with_len()).unwrap(); // Cannot add/recv HTLCs before we have a short_id so unwrap is safe
3005 failed_payments.push((chan_update, failed_adds));
3007 if chan.is_shutdown() {
3008 if let Some(short_id) = chan.get_short_channel_id() {
3009 short_to_id.remove(&short_id);
3013 no_channels_remain = false;
3019 pending_msg_events.retain(|msg| {
3021 &events::MessageSendEvent::SendAcceptChannel { ref node_id, .. } => node_id != their_node_id,
3022 &events::MessageSendEvent::SendOpenChannel { ref node_id, .. } => node_id != their_node_id,
3023 &events::MessageSendEvent::SendFundingCreated { ref node_id, .. } => node_id != their_node_id,
3024 &events::MessageSendEvent::SendFundingSigned { ref node_id, .. } => node_id != their_node_id,
3025 &events::MessageSendEvent::SendFundingLocked { ref node_id, .. } => node_id != their_node_id,
3026 &events::MessageSendEvent::SendAnnouncementSignatures { ref node_id, .. } => node_id != their_node_id,
3027 &events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => node_id != their_node_id,
3028 &events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => node_id != their_node_id,
3029 &events::MessageSendEvent::SendClosingSigned { ref node_id, .. } => node_id != their_node_id,
3030 &events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != their_node_id,
3031 &events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != their_node_id,
3032 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
3033 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
3034 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
3035 &events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != their_node_id,
3036 &events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
3040 if no_channels_remain {
3041 self.per_peer_state.write().unwrap().remove(their_node_id);
3044 for failure in failed_channels.drain(..) {
3045 self.finish_force_close_channel(failure);
3047 for (chan_update, mut htlc_sources) in failed_payments {
3048 for (htlc_source, payment_hash) in htlc_sources.drain(..) {
3049 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
3054 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init) {
3055 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
3057 let _ = self.total_consistency_lock.read().unwrap();
3060 let mut peer_state_lock = self.per_peer_state.write().unwrap();
3061 match peer_state_lock.entry(their_node_id.clone()) {
3062 hash_map::Entry::Vacant(e) => {
3063 e.insert(Mutex::new(PeerState {
3064 latest_features: init_msg.features.clone(),
3067 hash_map::Entry::Occupied(e) => {
3068 e.get().lock().unwrap().latest_features = init_msg.features.clone();
3073 let mut channel_state_lock = self.channel_state.lock().unwrap();
3074 let channel_state = &mut *channel_state_lock;
3075 let pending_msg_events = &mut channel_state.pending_msg_events;
3076 channel_state.by_id.retain(|_, chan| {
3077 if chan.get_their_node_id() == *their_node_id {
3078 if !chan.have_received_message() {
3079 // If we created this (outbound) channel while we were disconnected from the
3080 // peer we probably failed to send the open_channel message, which is now
3081 // lost. We can't have had anything pending related to this channel, so we just
3085 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
3086 node_id: chan.get_their_node_id(),
3087 msg: chan.get_channel_reestablish(),
3093 //TODO: Also re-broadcast announcement_signatures
3096 fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
3097 let _ = self.total_consistency_lock.read().unwrap();
3099 if msg.channel_id == [0; 32] {
3100 for chan in self.list_channels() {
3101 if chan.remote_network_id == *their_node_id {
3102 self.force_close_channel(&chan.channel_id);
3106 self.force_close_channel(&msg.channel_id);
3111 const SERIALIZATION_VERSION: u8 = 1;
3112 const MIN_SERIALIZATION_VERSION: u8 = 1;
3114 impl Writeable for PendingHTLCInfo {
3115 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3116 match &self.type_data {
3117 &PendingForwardReceiveHTLCInfo::Forward { ref onion_packet, ref short_channel_id } => {
3119 onion_packet.write(writer)?;
3120 short_channel_id.write(writer)?;
3122 &PendingForwardReceiveHTLCInfo::Receive { ref payment_data } => {
3124 payment_data.write(writer)?;
3127 self.incoming_shared_secret.write(writer)?;
3128 self.payment_hash.write(writer)?;
3129 self.amt_to_forward.write(writer)?;
3130 self.outgoing_cltv_value.write(writer)?;
3135 impl<R: ::std::io::Read> Readable<R> for PendingHTLCInfo {
3136 fn read(reader: &mut R) -> Result<PendingHTLCInfo, DecodeError> {
3137 Ok(PendingHTLCInfo {
3138 type_data: match Readable::read(reader)? {
3139 0u8 => PendingForwardReceiveHTLCInfo::Forward {
3140 onion_packet: Readable::read(reader)?,
3141 short_channel_id: Readable::read(reader)?,
3143 1u8 => PendingForwardReceiveHTLCInfo::Receive {
3144 payment_data: Readable::read(reader)?,
3146 _ => return Err(DecodeError::InvalidValue),
3148 incoming_shared_secret: Readable::read(reader)?,
3149 payment_hash: Readable::read(reader)?,
3150 amt_to_forward: Readable::read(reader)?,
3151 outgoing_cltv_value: Readable::read(reader)?,
3156 impl Writeable for HTLCFailureMsg {
3157 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3159 &HTLCFailureMsg::Relay(ref fail_msg) => {
3161 fail_msg.write(writer)?;
3163 &HTLCFailureMsg::Malformed(ref fail_msg) => {
3165 fail_msg.write(writer)?;
3172 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3173 fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3174 match <u8 as Readable<R>>::read(reader)? {
3175 0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3176 1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3177 _ => Err(DecodeError::InvalidValue),
3182 impl Writeable for PendingHTLCStatus {
3183 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3185 &PendingHTLCStatus::Forward(ref forward_info) => {
3187 forward_info.write(writer)?;
3189 &PendingHTLCStatus::Fail(ref fail_msg) => {
3191 fail_msg.write(writer)?;
3198 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3199 fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3200 match <u8 as Readable<R>>::read(reader)? {
3201 0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3202 1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3203 _ => Err(DecodeError::InvalidValue),
3208 impl_writeable!(HTLCPreviousHopData, 0, {
3211 incoming_packet_shared_secret
3214 impl Writeable for HTLCSource {
3215 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3217 &HTLCSource::PreviousHopData(ref hop_data) => {
3219 hop_data.write(writer)?;
3221 &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3223 route.write(writer)?;
3224 session_priv.write(writer)?;
3225 first_hop_htlc_msat.write(writer)?;
3232 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3233 fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3234 match <u8 as Readable<R>>::read(reader)? {
3235 0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3236 1 => Ok(HTLCSource::OutboundRoute {
3237 route: Readable::read(reader)?,
3238 session_priv: Readable::read(reader)?,
3239 first_hop_htlc_msat: Readable::read(reader)?,
3241 _ => Err(DecodeError::InvalidValue),
3246 impl Writeable for HTLCFailReason {
3247 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3249 &HTLCFailReason::LightningError { ref err } => {
3253 &HTLCFailReason::Reason { ref failure_code, ref data } => {
3255 failure_code.write(writer)?;
3256 data.write(writer)?;
3263 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3264 fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3265 match <u8 as Readable<R>>::read(reader)? {
3266 0 => Ok(HTLCFailReason::LightningError { err: Readable::read(reader)? }),
3267 1 => Ok(HTLCFailReason::Reason {
3268 failure_code: Readable::read(reader)?,
3269 data: Readable::read(reader)?,
3271 _ => Err(DecodeError::InvalidValue),
3276 impl Writeable for HTLCForwardInfo {
3277 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3279 &HTLCForwardInfo::AddHTLC { ref prev_short_channel_id, ref prev_htlc_id, ref forward_info } => {
3281 prev_short_channel_id.write(writer)?;
3282 prev_htlc_id.write(writer)?;
3283 forward_info.write(writer)?;
3285 &HTLCForwardInfo::FailHTLC { ref htlc_id, ref err_packet } => {
3287 htlc_id.write(writer)?;
3288 err_packet.write(writer)?;
3295 impl<R: ::std::io::Read> Readable<R> for HTLCForwardInfo {
3296 fn read(reader: &mut R) -> Result<HTLCForwardInfo, DecodeError> {
3297 match <u8 as Readable<R>>::read(reader)? {
3298 0 => Ok(HTLCForwardInfo::AddHTLC {
3299 prev_short_channel_id: Readable::read(reader)?,
3300 prev_htlc_id: Readable::read(reader)?,
3301 forward_info: Readable::read(reader)?,
3303 1 => Ok(HTLCForwardInfo::FailHTLC {
3304 htlc_id: Readable::read(reader)?,
3305 err_packet: Readable::read(reader)?,
3307 _ => Err(DecodeError::InvalidValue),
3312 impl<ChanSigner: ChannelKeys + Writeable, M: Deref> Writeable for ChannelManager<ChanSigner, M> where M::Target: ManyChannelMonitor {
3313 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3314 let _ = self.total_consistency_lock.write().unwrap();
3316 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3317 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3319 self.genesis_hash.write(writer)?;
3320 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3321 self.last_block_hash.lock().unwrap().write(writer)?;
3323 let channel_state = self.channel_state.lock().unwrap();
3324 let mut unfunded_channels = 0;
3325 for (_, channel) in channel_state.by_id.iter() {
3326 if !channel.is_funding_initiated() {
3327 unfunded_channels += 1;
3330 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3331 for (_, channel) in channel_state.by_id.iter() {
3332 if channel.is_funding_initiated() {
3333 channel.write(writer)?;
3337 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3338 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3339 short_channel_id.write(writer)?;
3340 (pending_forwards.len() as u64).write(writer)?;
3341 for forward in pending_forwards {
3342 forward.write(writer)?;
3346 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3347 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3348 payment_hash.write(writer)?;
3349 (previous_hops.len() as u64).write(writer)?;
3350 for htlc in previous_hops.iter() {
3351 htlc.src.write(writer)?;
3352 htlc.value.write(writer)?;
3353 htlc.payment_data.write(writer)?;
3357 let per_peer_state = self.per_peer_state.write().unwrap();
3358 (per_peer_state.len() as u64).write(writer)?;
3359 for (peer_pubkey, peer_state_mutex) in per_peer_state.iter() {
3360 peer_pubkey.write(writer)?;
3361 let peer_state = peer_state_mutex.lock().unwrap();
3362 peer_state.latest_features.write(writer)?;
3365 (self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
3371 /// Arguments for the creation of a ChannelManager that are not deserialized.
3373 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3375 /// 1) Deserialize all stored ChannelMonitors.
3376 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3377 /// ChannelManager)>::read(reader, args).
3378 /// This may result in closing some Channels if the ChannelMonitor is newer than the stored
3379 /// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3380 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3381 /// ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3382 /// 4) Reconnect blocks on your ChannelMonitors.
3383 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3384 /// 6) Disconnect/connect blocks on the ChannelManager.
3385 /// 7) Register the new ChannelManager with your ChainWatchInterface.
3386 pub struct ChannelManagerReadArgs<'a, ChanSigner: ChannelKeys, M: Deref> where M::Target: ManyChannelMonitor {
3387 /// The keys provider which will give us relevant keys. Some keys will be loaded during
3388 /// deserialization.
3389 pub keys_manager: Arc<KeysInterface<ChanKeySigner = ChanSigner>>,
3391 /// The fee_estimator for use in the ChannelManager in the future.
3393 /// No calls to the FeeEstimator will be made during deserialization.
3394 pub fee_estimator: Arc<FeeEstimator>,
3395 /// The ManyChannelMonitor for use in the ChannelManager in the future.
3397 /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3398 /// you have deserialized ChannelMonitors separately and will add them to your
3399 /// ManyChannelMonitor after deserializing this ChannelManager.
3402 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3403 /// used to broadcast the latest local commitment transactions of channels which must be
3404 /// force-closed during deserialization.
3405 pub tx_broadcaster: Arc<BroadcasterInterface>,
3406 /// The Logger for use in the ChannelManager and which may be used to log information during
3407 /// deserialization.
3408 pub logger: Arc<Logger>,
3409 /// Default settings used for new channels. Any existing channels will continue to use the
3410 /// runtime settings which were stored when the ChannelManager was serialized.
3411 pub default_config: UserConfig,
3413 /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3414 /// value.get_funding_txo() should be the key).
3416 /// If a monitor is inconsistent with the channel state during deserialization the channel will
3417 /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
3418 /// is true for missing channels as well. If there is a monitor missing for which we find
3419 /// channel data Err(DecodeError::InvalidValue) will be returned.
3421 /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3423 pub channel_monitors: &'a mut HashMap<OutPoint, &'a mut ChannelMonitor>,
3426 impl<'a, R : ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>, M: Deref> ReadableArgs<R, ChannelManagerReadArgs<'a, ChanSigner, M>> for (Sha256dHash, ChannelManager<ChanSigner, M>) where M::Target: ManyChannelMonitor {
3427 fn read(reader: &mut R, args: ChannelManagerReadArgs<'a, ChanSigner, M>) -> Result<Self, DecodeError> {
3428 let _ver: u8 = Readable::read(reader)?;
3429 let min_ver: u8 = Readable::read(reader)?;
3430 if min_ver > SERIALIZATION_VERSION {
3431 return Err(DecodeError::UnknownVersion);
3434 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3435 let latest_block_height: u32 = Readable::read(reader)?;
3436 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3438 let mut closed_channels = Vec::new();
3440 let channel_count: u64 = Readable::read(reader)?;
3441 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3442 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3443 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3444 for _ in 0..channel_count {
3445 let mut channel: Channel<ChanSigner> = ReadableArgs::read(reader, args.logger.clone())?;
3446 if channel.last_block_connected != last_block_hash {
3447 return Err(DecodeError::InvalidValue);
3450 let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3451 funding_txo_set.insert(funding_txo.clone());
3452 if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
3453 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3454 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3455 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3456 let mut force_close_res = channel.force_shutdown();
3457 force_close_res.0 = monitor.get_latest_local_commitment_txn();
3458 closed_channels.push(force_close_res);
3460 if let Some(short_channel_id) = channel.get_short_channel_id() {
3461 short_to_id.insert(short_channel_id, channel.channel_id());
3463 by_id.insert(channel.channel_id(), channel);
3466 return Err(DecodeError::InvalidValue);
3470 for (ref funding_txo, ref mut monitor) in args.channel_monitors.iter_mut() {
3471 if !funding_txo_set.contains(funding_txo) {
3472 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3476 let forward_htlcs_count: u64 = Readable::read(reader)?;
3477 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3478 for _ in 0..forward_htlcs_count {
3479 let short_channel_id = Readable::read(reader)?;
3480 let pending_forwards_count: u64 = Readable::read(reader)?;
3481 let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3482 for _ in 0..pending_forwards_count {
3483 pending_forwards.push(Readable::read(reader)?);
3485 forward_htlcs.insert(short_channel_id, pending_forwards);
3488 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3489 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3490 for _ in 0..claimable_htlcs_count {
3491 let payment_hash = Readable::read(reader)?;
3492 let previous_hops_len: u64 = Readable::read(reader)?;
3493 let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3494 for _ in 0..previous_hops_len {
3495 previous_hops.push(ClaimableHTLC {
3496 src: Readable::read(reader)?,
3497 value: Readable::read(reader)?,
3498 payment_data: Readable::read(reader)?,
3501 claimable_htlcs.insert(payment_hash, previous_hops);
3504 let peer_count: u64 = Readable::read(reader)?;
3505 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, 128));
3506 for _ in 0..peer_count {
3507 let peer_pubkey = Readable::read(reader)?;
3508 let peer_state = PeerState {
3509 latest_features: Readable::read(reader)?,
3511 per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
3514 let last_node_announcement_serial: u32 = Readable::read(reader)?;
3516 let channel_manager = ChannelManager {
3518 fee_estimator: args.fee_estimator,
3519 monitor: args.monitor,
3520 tx_broadcaster: args.tx_broadcaster,
3522 latest_block_height: AtomicUsize::new(latest_block_height as usize),
3523 last_block_hash: Mutex::new(last_block_hash),
3524 secp_ctx: Secp256k1::new(),
3526 channel_state: Mutex::new(ChannelHolder {
3531 pending_msg_events: Vec::new(),
3533 our_network_key: args.keys_manager.get_node_secret(),
3535 last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
3537 per_peer_state: RwLock::new(per_peer_state),
3539 pending_events: Mutex::new(Vec::new()),
3540 total_consistency_lock: RwLock::new(()),
3541 keys_manager: args.keys_manager,
3542 logger: args.logger,
3543 default_configuration: args.default_config,
3546 for close_res in closed_channels.drain(..) {
3547 channel_manager.finish_force_close_channel(close_res);
3548 //TODO: Broadcast channel update for closed channels, but only after we've made a
3549 //connection or two.
3552 Ok((last_block_hash.clone(), channel_manager))