1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level channel management and payment tracking stuff lives here.
12 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
13 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
14 //! upon reconnect to the relevant peer(s).
16 //! It does not manage routing logic (see routing::router::get_route for that) nor does it manage constructing
17 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
18 //! imply it needs to fail HTLCs/payments/channels it manages).
20 use bitcoin::blockdata::block::BlockHeader;
21 use bitcoin::blockdata::transaction::Transaction;
22 use bitcoin::blockdata::constants::genesis_block;
23 use bitcoin::network::constants::Network;
24 use bitcoin::util::hash::BitcoinHash;
26 use bitcoin::hashes::{Hash, HashEngine};
27 use bitcoin::hashes::hmac::{Hmac, HmacEngine};
28 use bitcoin::hashes::sha256::Hash as Sha256;
29 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
30 use bitcoin::hashes::cmp::fixed_time_eq;
31 use bitcoin::hash_types::BlockHash;
33 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
34 use bitcoin::secp256k1::Secp256k1;
35 use bitcoin::secp256k1::ecdh::SharedSecret;
36 use bitcoin::secp256k1;
38 use chain::chaininterface::{BroadcasterInterface,ChainListener,FeeEstimator};
39 use chain::transaction::OutPoint;
40 use ln::channel::{Channel, ChannelError};
41 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, ManyChannelMonitor, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent};
42 use ln::features::{InitFeatures, NodeFeatures};
43 use routing::router::{Route, RouteHop};
46 use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, OptionalField};
47 use chain::keysinterface::{ChannelKeys, KeysInterface, KeysManager, InMemoryChannelKeys};
48 use util::config::UserConfig;
49 use util::{byte_utils, events};
50 use util::ser::{Readable, ReadableArgs, MaybeReadable, Writeable, Writer};
51 use util::chacha20::{ChaCha20, ChaChaReader};
52 use util::logger::Logger;
53 use util::errors::APIError;
56 use std::collections::{HashMap, hash_map, HashSet};
57 use std::io::{Cursor, Read};
58 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
59 use std::sync::atomic::{AtomicUsize, Ordering};
60 use std::time::Duration;
61 use std::marker::{Sync, Send};
63 use bitcoin::hashes::hex::ToHex;
65 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
67 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
68 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
69 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
71 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
72 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
73 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
74 // before we forward it.
76 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
77 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
78 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
79 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
80 // our payment, which we can use to decode errors or inform the user that the payment was sent.
82 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
83 enum PendingHTLCRouting {
85 onion_packet: msgs::OnionPacket,
86 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
89 payment_data: Option<msgs::FinalOnionHopData>,
90 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
94 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
95 pub(super) struct PendingHTLCInfo {
96 routing: PendingHTLCRouting,
97 incoming_shared_secret: [u8; 32],
98 payment_hash: PaymentHash,
99 pub(super) amt_to_forward: u64,
100 pub(super) outgoing_cltv_value: u32,
103 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
104 pub(super) enum HTLCFailureMsg {
105 Relay(msgs::UpdateFailHTLC),
106 Malformed(msgs::UpdateFailMalformedHTLC),
109 /// Stores whether we can't forward an HTLC or relevant forwarding info
110 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
111 pub(super) enum PendingHTLCStatus {
112 Forward(PendingHTLCInfo),
113 Fail(HTLCFailureMsg),
116 pub(super) enum HTLCForwardInfo {
118 prev_short_channel_id: u64,
120 forward_info: PendingHTLCInfo,
124 err_packet: msgs::OnionErrorPacket,
128 /// Tracks the inbound corresponding to an outbound HTLC
129 #[derive(Clone, PartialEq)]
130 pub(super) struct HTLCPreviousHopData {
131 short_channel_id: u64,
133 incoming_packet_shared_secret: [u8; 32],
136 struct ClaimableHTLC {
137 prev_hop: HTLCPreviousHopData,
139 /// Filled in when the HTLC was received with a payment_secret packet, which contains a
140 /// total_msat (which may differ from value if this is a Multi-Path Payment) and a
141 /// payment_secret which prevents path-probing attacks and can associate different HTLCs which
142 /// are part of the same payment.
143 payment_data: Option<msgs::FinalOnionHopData>,
147 /// Tracks the inbound corresponding to an outbound HTLC
148 #[derive(Clone, PartialEq)]
149 pub(super) enum HTLCSource {
150 PreviousHopData(HTLCPreviousHopData),
153 session_priv: SecretKey,
154 /// Technically we can recalculate this from the route, but we cache it here to avoid
155 /// doing a double-pass on route when we get a failure back
156 first_hop_htlc_msat: u64,
161 pub fn dummy() -> Self {
162 HTLCSource::OutboundRoute {
164 session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
165 first_hop_htlc_msat: 0,
170 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
171 pub(super) enum HTLCFailReason {
173 err: msgs::OnionErrorPacket,
181 /// payment_hash type, use to cross-lock hop
182 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
183 pub struct PaymentHash(pub [u8;32]);
184 /// payment_preimage type, use to route payment between hop
185 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
186 pub struct PaymentPreimage(pub [u8;32]);
187 /// payment_secret type, use to authenticate sender to the receiver and tie MPP HTLCs together
188 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
189 pub struct PaymentSecret(pub [u8;32]);
191 type ShutdownResult = (Option<OutPoint>, ChannelMonitorUpdate, Vec<(HTLCSource, PaymentHash)>);
193 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
194 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
195 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
196 /// channel_state lock. We then return the set of things that need to be done outside the lock in
197 /// this struct and call handle_error!() on it.
199 struct MsgHandleErrInternal {
200 err: msgs::LightningError,
201 shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
203 impl MsgHandleErrInternal {
205 fn send_err_msg_no_close(err: String, channel_id: [u8; 32]) -> Self {
207 err: LightningError {
209 action: msgs::ErrorAction::SendErrorMessage {
210 msg: msgs::ErrorMessage {
216 shutdown_finish: None,
220 fn ignore_no_close(err: String) -> Self {
222 err: LightningError {
224 action: msgs::ErrorAction::IgnoreError,
226 shutdown_finish: None,
230 fn from_no_close(err: msgs::LightningError) -> Self {
231 Self { err, shutdown_finish: None }
234 fn from_finish_shutdown(err: String, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
236 err: LightningError {
238 action: msgs::ErrorAction::SendErrorMessage {
239 msg: msgs::ErrorMessage {
245 shutdown_finish: Some((shutdown_res, channel_update)),
249 fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
252 ChannelError::Ignore(msg) => LightningError {
254 action: msgs::ErrorAction::IgnoreError,
256 ChannelError::Close(msg) => LightningError {
258 action: msgs::ErrorAction::SendErrorMessage {
259 msg: msgs::ErrorMessage {
265 ChannelError::CloseDelayBroadcast(msg) => LightningError {
267 action: msgs::ErrorAction::SendErrorMessage {
268 msg: msgs::ErrorMessage {
275 shutdown_finish: None,
280 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
281 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
282 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
283 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
284 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
286 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
287 /// be sent in the order they appear in the return value, however sometimes the order needs to be
288 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
289 /// they were originally sent). In those cases, this enum is also returned.
290 #[derive(Clone, PartialEq)]
291 pub(super) enum RAACommitmentOrder {
292 /// Send the CommitmentUpdate messages first
294 /// Send the RevokeAndACK message first
298 // Note this is only exposed in cfg(test):
299 pub(super) struct ChannelHolder<ChanSigner: ChannelKeys> {
300 pub(super) by_id: HashMap<[u8; 32], Channel<ChanSigner>>,
301 pub(super) short_to_id: HashMap<u64, [u8; 32]>,
302 /// short channel id -> forward infos. Key of 0 means payments received
303 /// Note that while this is held in the same mutex as the channels themselves, no consistency
304 /// guarantees are made about the existence of a channel with the short id here, nor the short
305 /// ids in the PendingHTLCInfo!
306 pub(super) forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
307 /// (payment_hash, payment_secret) -> Vec<HTLCs> for tracking HTLCs that
308 /// were to us and can be failed/claimed by the user
309 /// Note that while this is held in the same mutex as the channels themselves, no consistency
310 /// guarantees are made about the channels given here actually existing anymore by the time you
312 claimable_htlcs: HashMap<(PaymentHash, Option<PaymentSecret>), Vec<ClaimableHTLC>>,
313 /// Messages to send to peers - pushed to in the same lock that they are generated in (except
314 /// for broadcast messages, where ordering isn't as strict).
315 pub(super) pending_msg_events: Vec<events::MessageSendEvent>,
318 /// State we hold per-peer. In the future we should put channels in here, but for now we only hold
319 /// the latest Init features we heard from the peer.
321 latest_features: InitFeatures,
324 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
325 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
327 /// SimpleArcChannelManager is useful when you need a ChannelManager with a static lifetime, e.g.
328 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
329 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
330 /// SimpleRefChannelManager is the more appropriate type. Defining these type aliases prevents
331 /// issues such as overly long function definitions. Note that the ChannelManager can take any
332 /// type that implements KeysInterface for its keys manager, but this type alias chooses the
333 /// concrete type of the KeysManager.
334 pub type SimpleArcChannelManager<M, T, F, L> = Arc<ChannelManager<InMemoryChannelKeys, Arc<M>, Arc<T>, Arc<KeysManager>, Arc<F>, Arc<L>>>;
336 /// SimpleRefChannelManager is a type alias for a ChannelManager reference, and is the reference
337 /// counterpart to the SimpleArcChannelManager type alias. Use this type by default when you don't
338 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
339 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
340 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
341 /// helps with issues such as long function definitions. Note that the ChannelManager can take any
342 /// type that implements KeysInterface for its keys manager, but this type alias chooses the
343 /// concrete type of the KeysManager.
344 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManager<InMemoryChannelKeys, &'a M, &'b T, &'c KeysManager, &'d F, &'e L>;
346 /// Manager which keeps track of a number of channels and sends messages to the appropriate
347 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
349 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
350 /// to individual Channels.
352 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
353 /// all peers during write/read (though does not modify this instance, only the instance being
354 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
355 /// called funding_transaction_generated for outbound channels).
357 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
358 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
359 /// returning from ManyChannelMonitor::add_/update_monitor, with ChannelManagers, writing updates
360 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
361 /// the serialization process). If the deserialized version is out-of-date compared to the
362 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
363 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
365 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
366 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
367 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
368 /// block_connected() to step towards your best block) upon deserialization before using the
371 /// Note that ChannelManager is responsible for tracking liveness of its channels and generating
372 /// ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid
373 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
374 /// offline for a full minute. In order to track this, you must call
375 /// timer_chan_freshness_every_min roughly once per minute, though it doesn't have to be perfect.
377 /// Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager
378 /// a SimpleRefChannelManager, for conciseness. See their documentation for more details, but
379 /// essentially you should default to using a SimpleRefChannelManager, and use a
380 /// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
381 /// you're using lightning-net-tokio.
382 pub struct ChannelManager<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
383 where M::Target: ManyChannelMonitor<Keys=ChanSigner>,
384 T::Target: BroadcasterInterface,
385 K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
386 F::Target: FeeEstimator,
389 default_configuration: UserConfig,
390 genesis_hash: BlockHash,
396 pub(super) latest_block_height: AtomicUsize,
398 latest_block_height: AtomicUsize,
399 last_block_hash: Mutex<BlockHash>,
400 secp_ctx: Secp256k1<secp256k1::All>,
403 pub(super) channel_state: Mutex<ChannelHolder<ChanSigner>>,
405 channel_state: Mutex<ChannelHolder<ChanSigner>>,
406 our_network_key: SecretKey,
408 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
409 /// value increases strictly since we don't assume access to a time source.
410 last_node_announcement_serial: AtomicUsize,
412 /// The bulk of our storage will eventually be here (channels and message queues and the like).
413 /// If we are connected to a peer we always at least have an entry here, even if no channels
414 /// are currently open with that peer.
415 /// Because adding or removing an entry is rare, we usually take an outer read lock and then
416 /// operate on the inner value freely. Sadly, this prevents parallel operation when opening a
418 per_peer_state: RwLock<HashMap<PublicKey, Mutex<PeerState>>>,
420 pending_events: Mutex<Vec<events::Event>>,
421 /// Used when we have to take a BIG lock to make sure everything is self-consistent.
422 /// Essentially just when we're serializing ourselves out.
423 /// Taken first everywhere where we are making changes before any other locks.
424 total_consistency_lock: RwLock<()>,
431 /// The amount of time we require our counterparty wait to claim their money (ie time between when
432 /// we, or our watchtower, must check for them having broadcast a theft transaction).
433 pub(crate) const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
434 /// The amount of time we're willing to wait to claim money back to us
435 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 6 * 24 * 7;
437 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
438 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
439 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
440 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
441 /// CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
442 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
443 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
445 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
446 // ie that if the next-hop peer fails the HTLC within
447 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
448 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
449 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
450 // LATENCY_GRACE_PERIOD_BLOCKS.
453 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;
455 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
456 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
459 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
461 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
462 pub struct ChannelDetails {
463 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
464 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
465 /// Note that this means this value is *not* persistent - it can change once during the
466 /// lifetime of the channel.
467 pub channel_id: [u8; 32],
468 /// The position of the funding transaction in the chain. None if the funding transaction has
469 /// not yet been confirmed and the channel fully opened.
470 pub short_channel_id: Option<u64>,
471 /// The node_id of our counterparty
472 pub remote_network_id: PublicKey,
473 /// The Features the channel counterparty provided upon last connection.
474 /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
475 /// many routing-relevant features are present in the init context.
476 pub counterparty_features: InitFeatures,
477 /// The value, in satoshis, of this channel as appears in the funding output
478 pub channel_value_satoshis: u64,
479 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
481 /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
482 /// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
483 /// available for inclusion in new outbound HTLCs). This further does not include any pending
484 /// outgoing HTLCs which are awaiting some other resolution to be sent.
485 pub outbound_capacity_msat: u64,
486 /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
487 /// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
488 /// available for inclusion in new inbound HTLCs).
489 /// Note that there are some corner cases not fully handled here, so the actual available
490 /// inbound capacity may be slightly higher than this.
491 pub inbound_capacity_msat: u64,
492 /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
493 /// the peer is connected, and (c) no monitor update failure is pending resolution.
497 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
498 /// Err() type describing which state the payment is in, see the description of individual enum
501 pub enum PaymentSendFailure {
502 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
503 /// send the payment at all. No channel state has been changed or messages sent to peers, and
504 /// once you've changed the parameter at error, you can freely retry the payment in full.
505 ParameterError(APIError),
506 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
507 /// from attempting to send the payment at all. No channel state has been changed or messages
508 /// sent to peers, and once you've changed the parameter at error, you can freely retry the
511 /// The results here are ordered the same as the paths in the route object which was passed to
513 PathParameterError(Vec<Result<(), APIError>>),
514 /// All paths which were attempted failed to send, with no channel state change taking place.
515 /// You can freely retry the payment in full (though you probably want to do so over different
516 /// paths than the ones selected).
517 AllFailedRetrySafe(Vec<APIError>),
518 /// Some paths which were attempted failed to send, though possibly not all. At least some
519 /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
520 /// in over-/re-payment.
522 /// The results here are ordered the same as the paths in the route object which was passed to
523 /// send_payment, and any Errs which are not APIError::MonitorUpdateFailed can be safely
524 /// retried (though there is currently no API with which to do so).
526 /// Any entries which contain Err(APIError::MonitorUpdateFailed) or Ok(()) MUST NOT be retried
527 /// as they will result in over-/re-payment. These HTLCs all either successfully sent (in the
528 /// case of Ok(())) or will send once channel_monitor_updated is called on the next-hop channel
529 /// with the latest update_id.
530 PartialFailure(Vec<Result<(), APIError>>),
533 macro_rules! handle_error {
534 ($self: ident, $internal: expr, $their_node_id: expr) => {
537 Err(MsgHandleErrInternal { err, shutdown_finish }) => {
538 #[cfg(debug_assertions)]
540 // In testing, ensure there are no deadlocks where the lock is already held upon
541 // entering the macro.
542 assert!($self.channel_state.try_lock().is_ok());
545 let mut msg_events = Vec::with_capacity(2);
547 if let Some((shutdown_res, update_option)) = shutdown_finish {
548 $self.finish_force_close_channel(shutdown_res);
549 if let Some(update) = update_option {
550 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
556 log_error!($self.logger, "{}", err.err);
557 if let msgs::ErrorAction::IgnoreError = err.action {
559 msg_events.push(events::MessageSendEvent::HandleError {
560 node_id: $their_node_id,
561 action: err.action.clone()
565 if !msg_events.is_empty() {
566 $self.channel_state.lock().unwrap().pending_msg_events.append(&mut msg_events);
569 // Return error in case higher-API need one
576 macro_rules! break_chan_entry {
577 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
580 Err(ChannelError::Ignore(msg)) => {
581 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
583 Err(ChannelError::Close(msg)) => {
584 log_trace!($self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
585 let (channel_id, mut chan) = $entry.remove_entry();
586 if let Some(short_id) = chan.get_short_channel_id() {
587 $channel_state.short_to_id.remove(&short_id);
589 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()))
591 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"); }
596 macro_rules! try_chan_entry {
597 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
600 Err(ChannelError::Ignore(msg)) => {
601 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
603 Err(ChannelError::Close(msg)) => {
604 log_trace!($self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
605 let (channel_id, mut chan) = $entry.remove_entry();
606 if let Some(short_id) = chan.get_short_channel_id() {
607 $channel_state.short_to_id.remove(&short_id);
609 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()))
611 Err(ChannelError::CloseDelayBroadcast(msg)) => {
612 log_error!($self.logger, "Channel {} need to be shutdown but closing transactions not broadcast due to {}", log_bytes!($entry.key()[..]), msg);
613 let (channel_id, mut chan) = $entry.remove_entry();
614 if let Some(short_id) = chan.get_short_channel_id() {
615 $channel_state.short_to_id.remove(&short_id);
617 let shutdown_res = chan.force_shutdown(false);
618 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, shutdown_res, $self.get_channel_update(&chan).ok()))
624 macro_rules! handle_monitor_err {
625 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
626 handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, Vec::new(), Vec::new())
628 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
630 ChannelMonitorUpdateErr::PermanentFailure => {
631 log_error!($self.logger, "Closing channel {} due to monitor update PermanentFailure", log_bytes!($entry.key()[..]));
632 let (channel_id, mut chan) = $entry.remove_entry();
633 if let Some(short_id) = chan.get_short_channel_id() {
634 $channel_state.short_to_id.remove(&short_id);
636 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
637 // chain in a confused state! We need to move them into the ChannelMonitor which
638 // will be responsible for failing backwards once things confirm on-chain.
639 // It's ok that we drop $failed_forwards here - at this point we'd rather they
640 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
641 // us bother trying to claim it just to forward on to another peer. If we're
642 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
643 // given up the preimage yet, so might as well just wait until the payment is
644 // retried, avoiding the on-chain fees.
645 let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure".to_owned(), channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()));
648 ChannelMonitorUpdateErr::TemporaryFailure => {
649 log_info!($self.logger, "Disabling channel {} due to monitor update TemporaryFailure. On restore will send {} and process {} forwards and {} fails",
650 log_bytes!($entry.key()[..]),
651 if $resend_commitment && $resend_raa {
653 RAACommitmentOrder::CommitmentFirst => { "commitment then RAA" },
654 RAACommitmentOrder::RevokeAndACKFirst => { "RAA then commitment" },
656 } else if $resend_commitment { "commitment" }
657 else if $resend_raa { "RAA" }
659 (&$failed_forwards as &Vec<(PendingHTLCInfo, u64)>).len(),
660 (&$failed_fails as &Vec<(HTLCSource, PaymentHash, HTLCFailReason)>).len());
661 if !$resend_commitment {
662 debug_assert!($action_type == RAACommitmentOrder::RevokeAndACKFirst || !$resend_raa);
665 debug_assert!($action_type == RAACommitmentOrder::CommitmentFirst || !$resend_commitment);
667 $entry.get_mut().monitor_update_failed($resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
668 Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor".to_owned()), *$entry.key()))
674 macro_rules! return_monitor_err {
675 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
676 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment);
678 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
679 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
683 // Does not break in case of TemporaryFailure!
684 macro_rules! maybe_break_monitor_err {
685 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
686 match (handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment), $err) {
687 (e, ChannelMonitorUpdateErr::PermanentFailure) => {
690 (_, ChannelMonitorUpdateErr::TemporaryFailure) => { },
695 impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<ChanSigner, M, T, K, F, L>
696 where M::Target: ManyChannelMonitor<Keys=ChanSigner>,
697 T::Target: BroadcasterInterface,
698 K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
699 F::Target: FeeEstimator,
702 /// Constructs a new ChannelManager to hold several channels and route between them.
704 /// This is the main "logic hub" for all channel-related actions, and implements
705 /// ChannelMessageHandler.
707 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
709 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
711 /// Users must provide the current blockchain height from which to track onchain channel
712 /// funding outpoints and send payments with reliable timelocks.
714 /// Users need to notify the new ChannelManager when a new block is connected or
715 /// disconnected using its `block_connected` and `block_disconnected` methods.
716 /// However, rather than calling these methods directly, the user should register
717 /// the ChannelManager as a listener to the BlockNotifier and call the BlockNotifier's
718 /// `block_(dis)connected` methods, which will notify all registered listeners in one
720 pub fn new(network: Network, fee_est: F, monitor: M, tx_broadcaster: T, logger: L, keys_manager: K, config: UserConfig, current_blockchain_height: usize) -> Self {
721 let secp_ctx = Secp256k1::new();
724 default_configuration: config.clone(),
725 genesis_hash: genesis_block(network).header.bitcoin_hash(),
726 fee_estimator: fee_est,
730 latest_block_height: AtomicUsize::new(current_blockchain_height),
731 last_block_hash: Mutex::new(Default::default()),
734 channel_state: Mutex::new(ChannelHolder{
735 by_id: HashMap::new(),
736 short_to_id: HashMap::new(),
737 forward_htlcs: HashMap::new(),
738 claimable_htlcs: HashMap::new(),
739 pending_msg_events: Vec::new(),
741 our_network_key: keys_manager.get_node_secret(),
743 last_node_announcement_serial: AtomicUsize::new(0),
745 per_peer_state: RwLock::new(HashMap::new()),
747 pending_events: Mutex::new(Vec::new()),
748 total_consistency_lock: RwLock::new(()),
756 /// Creates a new outbound channel to the given remote node and with the given value.
758 /// user_id will be provided back as user_channel_id in FundingGenerationReady and
759 /// FundingBroadcastSafe events to allow tracking of which events correspond with which
760 /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
761 /// may wish to avoid using 0 for user_id here.
763 /// If successful, will generate a SendOpenChannel message event, so you should probably poll
764 /// PeerManager::process_events afterwards.
766 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
767 /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
768 pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64, override_config: Option<UserConfig>) -> Result<(), APIError> {
769 if channel_value_satoshis < 1000 {
770 return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
773 let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
774 let channel = Channel::new_outbound(&self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, config)?;
775 let res = channel.get_open_channel(self.genesis_hash.clone());
777 let _ = self.total_consistency_lock.read().unwrap();
778 let mut channel_state = self.channel_state.lock().unwrap();
779 match channel_state.by_id.entry(channel.channel_id()) {
780 hash_map::Entry::Occupied(_) => {
781 if cfg!(feature = "fuzztarget") {
782 return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
784 panic!("RNG is bad???");
787 hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
789 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
790 node_id: their_network_key,
796 fn list_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<ChanSigner>)) -> bool>(&self, f: Fn) -> Vec<ChannelDetails> {
797 let mut res = Vec::new();
799 let channel_state = self.channel_state.lock().unwrap();
800 res.reserve(channel_state.by_id.len());
801 for (channel_id, channel) in channel_state.by_id.iter().filter(f) {
802 let (inbound_capacity_msat, outbound_capacity_msat) = channel.get_inbound_outbound_available_balance_msat();
803 res.push(ChannelDetails {
804 channel_id: (*channel_id).clone(),
805 short_channel_id: channel.get_short_channel_id(),
806 remote_network_id: channel.get_their_node_id(),
807 counterparty_features: InitFeatures::empty(),
808 channel_value_satoshis: channel.get_value_satoshis(),
809 inbound_capacity_msat,
810 outbound_capacity_msat,
811 user_id: channel.get_user_id(),
812 is_live: channel.is_live(),
816 let per_peer_state = self.per_peer_state.read().unwrap();
817 for chan in res.iter_mut() {
818 if let Some(peer_state) = per_peer_state.get(&chan.remote_network_id) {
819 chan.counterparty_features = peer_state.lock().unwrap().latest_features.clone();
825 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
826 /// more information.
827 pub fn list_channels(&self) -> Vec<ChannelDetails> {
828 self.list_channels_with_filter(|_| true)
831 /// Gets the list of usable channels, in random order. Useful as an argument to
832 /// get_route to ensure non-announced channels are used.
834 /// These are guaranteed to have their is_live value set to true, see the documentation for
835 /// ChannelDetails::is_live for more info on exactly what the criteria are.
836 pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
837 // Note we use is_live here instead of usable which leads to somewhat confused
838 // internal/external nomenclature, but that's ok cause that's probably what the user
839 // really wanted anyway.
840 self.list_channels_with_filter(|&(_, ref channel)| channel.is_live())
843 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
844 /// will be accepted on the given channel, and after additional timeout/the closing of all
845 /// pending HTLCs, the channel will be closed on chain.
847 /// May generate a SendShutdown message event on success, which should be relayed.
848 pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
849 let _ = self.total_consistency_lock.read().unwrap();
851 let (mut failed_htlcs, chan_option) = {
852 let mut channel_state_lock = self.channel_state.lock().unwrap();
853 let channel_state = &mut *channel_state_lock;
854 match channel_state.by_id.entry(channel_id.clone()) {
855 hash_map::Entry::Occupied(mut chan_entry) => {
856 let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
857 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
858 node_id: chan_entry.get().get_their_node_id(),
861 if chan_entry.get().is_shutdown() {
862 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
863 channel_state.short_to_id.remove(&short_id);
865 (failed_htlcs, Some(chan_entry.remove_entry().1))
866 } else { (failed_htlcs, None) }
868 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()})
871 for htlc_source in failed_htlcs.drain(..) {
872 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() });
874 let chan_update = if let Some(chan) = chan_option {
875 if let Ok(update) = self.get_channel_update(&chan) {
880 if let Some(update) = chan_update {
881 let mut channel_state = self.channel_state.lock().unwrap();
882 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
891 fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
892 let (funding_txo_option, monitor_update, mut failed_htlcs) = shutdown_res;
893 log_trace!(self.logger, "Finishing force-closure of channel {} HTLCs to fail", failed_htlcs.len());
894 for htlc_source in failed_htlcs.drain(..) {
895 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() });
897 if let Some(funding_txo) = funding_txo_option {
898 // There isn't anything we can do if we get an update failure - we're already
899 // force-closing. The monitor update on the required in-memory copy should broadcast
900 // the latest local state, which is the best we can do anyway. Thus, it is safe to
901 // ignore the result here.
902 let _ = self.monitor.update_monitor(funding_txo, monitor_update);
906 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
907 /// the chain and rejecting new HTLCs on the given channel.
908 pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
909 let _ = self.total_consistency_lock.read().unwrap();
912 let mut channel_state_lock = self.channel_state.lock().unwrap();
913 let channel_state = &mut *channel_state_lock;
914 if let Some(chan) = channel_state.by_id.remove(channel_id) {
915 if let Some(short_id) = chan.get_short_channel_id() {
916 channel_state.short_to_id.remove(&short_id);
923 log_trace!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
924 self.finish_force_close_channel(chan.force_shutdown(true));
925 if let Ok(update) = self.get_channel_update(&chan) {
926 let mut channel_state = self.channel_state.lock().unwrap();
927 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
933 /// Force close all channels, immediately broadcasting the latest local commitment transaction
934 /// for each to the chain and rejecting new HTLCs on each.
935 pub fn force_close_all_channels(&self) {
936 for chan in self.list_channels() {
937 self.force_close_channel(&chan.channel_id);
941 fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder<ChanSigner>>) {
942 macro_rules! return_malformed_err {
943 ($msg: expr, $err_code: expr) => {
945 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
946 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
947 channel_id: msg.channel_id,
948 htlc_id: msg.htlc_id,
949 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
950 failure_code: $err_code,
951 })), self.channel_state.lock().unwrap());
956 if let Err(_) = msg.onion_routing_packet.public_key {
957 return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
960 let shared_secret = {
961 let mut arr = [0; 32];
962 arr.copy_from_slice(&SharedSecret::new(&msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
965 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(&shared_secret);
967 if msg.onion_routing_packet.version != 0 {
968 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
969 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
970 //the hash doesn't really serve any purpose - in the case of hashing all data, the
971 //receiving node would have to brute force to figure out which version was put in the
972 //packet by the node that send us the message, in the case of hashing the hop_data, the
973 //node knows the HMAC matched, so they already know what is there...
974 return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
977 let mut hmac = HmacEngine::<Sha256>::new(&mu);
978 hmac.input(&msg.onion_routing_packet.hop_data);
979 hmac.input(&msg.payment_hash.0[..]);
980 if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
981 return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
984 let mut channel_state = None;
985 macro_rules! return_err {
986 ($msg: expr, $err_code: expr, $data: expr) => {
988 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
989 if channel_state.is_none() {
990 channel_state = Some(self.channel_state.lock().unwrap());
992 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
993 channel_id: msg.channel_id,
994 htlc_id: msg.htlc_id,
995 reason: onion_utils::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
996 })), channel_state.unwrap());
1001 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1002 let mut chacha_stream = ChaChaReader { chacha: &mut chacha, read: Cursor::new(&msg.onion_routing_packet.hop_data[..]) };
1003 let (next_hop_data, next_hop_hmac) = {
1004 match msgs::OnionHopData::read(&mut chacha_stream) {
1006 let error_code = match err {
1007 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1008 msgs::DecodeError::UnknownRequiredFeature|
1009 msgs::DecodeError::InvalidValue|
1010 msgs::DecodeError::ShortRead => 0x4000 | 22, // invalid_onion_payload
1011 _ => 0x2000 | 2, // Should never happen
1013 return_err!("Unable to decode our hop data", error_code, &[0;0]);
1016 let mut hmac = [0; 32];
1017 if let Err(_) = chacha_stream.read_exact(&mut hmac[..]) {
1018 return_err!("Unable to decode hop data", 0x4000 | 22, &[0;0]);
1025 let pending_forward_info = if next_hop_hmac == [0; 32] {
1028 // In tests, make sure that the initial onion pcket data is, at least, non-0.
1029 // We could do some fancy randomness test here, but, ehh, whatever.
1030 // This checks for the issue where you can calculate the path length given the
1031 // onion data as all the path entries that the originator sent will be here
1032 // as-is (and were originally 0s).
1033 // Of course reverse path calculation is still pretty easy given naive routing
1034 // algorithms, but this fixes the most-obvious case.
1035 let mut next_bytes = [0; 32];
1036 chacha_stream.read_exact(&mut next_bytes).unwrap();
1037 assert_ne!(next_bytes[..], [0; 32][..]);
1038 chacha_stream.read_exact(&mut next_bytes).unwrap();
1039 assert_ne!(next_bytes[..], [0; 32][..]);
1043 // final_expiry_too_soon
1044 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure we have at least
1045 // HTLC_FAIL_BACK_BUFFER blocks to go.
1046 // Also, ensure that, in the case of an unknown payment hash, our payment logic has enough time to fail the HTLC backward
1047 // before our onchain logic triggers a channel closure (see HTLC_FAIL_BACK_BUFFER rational).
1048 if (msg.cltv_expiry as u64) <= self.latest_block_height.load(Ordering::Acquire) as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1 {
1049 return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1051 // final_incorrect_htlc_amount
1052 if next_hop_data.amt_to_forward > msg.amount_msat {
1053 return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1055 // final_incorrect_cltv_expiry
1056 if next_hop_data.outgoing_cltv_value != msg.cltv_expiry {
1057 return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1060 let payment_data = match next_hop_data.format {
1061 msgs::OnionHopDataFormat::Legacy { .. } => None,
1062 msgs::OnionHopDataFormat::NonFinalNode { .. } => return_err!("Got non final data with an HMAC of 0", 0x4000 | 22, &[0;0]),
1063 msgs::OnionHopDataFormat::FinalNode { payment_data } => payment_data,
1066 // Note that we could obviously respond immediately with an update_fulfill_htlc
1067 // message, however that would leak that we are the recipient of this payment, so
1068 // instead we stay symmetric with the forwarding case, only responding (after a
1069 // delay) once they've send us a commitment_signed!
1071 PendingHTLCStatus::Forward(PendingHTLCInfo {
1072 routing: PendingHTLCRouting::Receive {
1074 incoming_cltv_expiry: msg.cltv_expiry,
1076 payment_hash: msg.payment_hash.clone(),
1077 incoming_shared_secret: shared_secret,
1078 amt_to_forward: next_hop_data.amt_to_forward,
1079 outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1082 let mut new_packet_data = [0; 20*65];
1083 let read_pos = chacha_stream.read(&mut new_packet_data).unwrap();
1084 #[cfg(debug_assertions)]
1086 // Check two things:
1087 // a) that the behavior of our stream here will return Ok(0) even if the TLV
1088 // read above emptied out our buffer and the unwrap() wont needlessly panic
1089 // b) that we didn't somehow magically end up with extra data.
1091 debug_assert!(chacha_stream.read(&mut t).unwrap() == 0);
1093 // Once we've emptied the set of bytes our peer gave us, encrypt 0 bytes until we
1094 // fill the onion hop data we'll forward to our next-hop peer.
1095 chacha_stream.chacha.process_in_place(&mut new_packet_data[read_pos..]);
1097 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1099 let blinding_factor = {
1100 let mut sha = Sha256::engine();
1101 sha.input(&new_pubkey.serialize()[..]);
1102 sha.input(&shared_secret);
1103 Sha256::from_engine(sha).into_inner()
1106 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor[..]) {
1108 } else { Ok(new_pubkey) };
1110 let outgoing_packet = msgs::OnionPacket {
1113 hop_data: new_packet_data,
1114 hmac: next_hop_hmac.clone(),
1117 let short_channel_id = match next_hop_data.format {
1118 msgs::OnionHopDataFormat::Legacy { short_channel_id } => short_channel_id,
1119 msgs::OnionHopDataFormat::NonFinalNode { short_channel_id } => short_channel_id,
1120 msgs::OnionHopDataFormat::FinalNode { .. } => {
1121 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0;0]);
1125 PendingHTLCStatus::Forward(PendingHTLCInfo {
1126 routing: PendingHTLCRouting::Forward {
1127 onion_packet: outgoing_packet,
1128 short_channel_id: short_channel_id,
1130 payment_hash: msg.payment_hash.clone(),
1131 incoming_shared_secret: shared_secret,
1132 amt_to_forward: next_hop_data.amt_to_forward,
1133 outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1137 channel_state = Some(self.channel_state.lock().unwrap());
1138 if let &PendingHTLCStatus::Forward(PendingHTLCInfo { ref routing, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1139 // If short_channel_id is 0 here, we'll reject the HTLC as there cannot be a channel
1140 // with a short_channel_id of 0. This is important as various things later assume
1141 // short_channel_id is non-0 in any ::Forward.
1142 if let &PendingHTLCRouting::Forward { ref short_channel_id, .. } = routing {
1143 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1144 let forwarding_id = match id_option {
1145 None => { // unknown_next_peer
1146 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1148 Some(id) => id.clone(),
1150 if let Some((err, code, chan_update)) = loop {
1151 let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1153 // Note that we could technically not return an error yet here and just hope
1154 // that the connection is reestablished or monitor updated by the time we get
1155 // around to doing the actual forward, but better to fail early if we can and
1156 // hopefully an attacker trying to path-trace payments cannot make this occur
1157 // on a small/per-node/per-channel scale.
1158 if !chan.is_live() { // channel_disabled
1159 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1161 if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1162 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1164 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) });
1165 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1166 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())));
1168 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1169 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())));
1171 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1172 // Theoretically, channel counterparty shouldn't send us a HTLC expiring now, but we want to be robust wrt to counterparty
1173 // packet sanitization (see HTLC_FAIL_BACK_BUFFER rational)
1174 if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
1175 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1177 if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1178 break Some(("CLTV expiry is too far in the future", 21, None));
1180 // In theory, we would be safe against unitentional channel-closure, if we only required a margin of LATENCY_GRACE_PERIOD_BLOCKS.
1181 // But, to be safe against policy reception, we use a longuer delay.
1182 if (*outgoing_cltv_value) as u64 <= (cur_height + HTLC_FAIL_BACK_BUFFER) as u64 {
1183 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1189 let mut res = Vec::with_capacity(8 + 128);
1190 if let Some(chan_update) = chan_update {
1191 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1192 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1194 else if code == 0x1000 | 13 {
1195 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1197 else if code == 0x1000 | 20 {
1198 // TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
1199 res.extend_from_slice(&byte_utils::be16_to_array(0));
1201 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1203 return_err!(err, code, &res[..]);
1208 (pending_forward_info, channel_state.unwrap())
1211 /// only fails if the channel does not yet have an assigned short_id
1212 /// May be called with channel_state already locked!
1213 fn get_channel_update(&self, chan: &Channel<ChanSigner>) -> Result<msgs::ChannelUpdate, LightningError> {
1214 let short_channel_id = match chan.get_short_channel_id() {
1215 None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
1219 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1221 let unsigned = msgs::UnsignedChannelUpdate {
1222 chain_hash: self.genesis_hash,
1223 short_channel_id: short_channel_id,
1224 timestamp: chan.get_update_time_counter(),
1225 flags: (!were_node_one) as u8 | ((!chan.is_live() as u8) << 1),
1226 cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1227 htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1228 htlc_maximum_msat: OptionalField::Present(chan.get_announced_htlc_max_msat()),
1229 fee_base_msat: chan.get_our_fee_base_msat(&self.fee_estimator),
1230 fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1231 excess_data: Vec::new(),
1234 let msg_hash = Sha256dHash::hash(&unsigned.encode()[..]);
1235 let sig = self.secp_ctx.sign(&hash_to_message!(&msg_hash[..]), &self.our_network_key);
1237 Ok(msgs::ChannelUpdate {
1243 // Only public for testing, this should otherwise never be called direcly
1244 pub(crate) fn send_payment_along_path(&self, path: &Vec<RouteHop>, payment_hash: &PaymentHash, payment_secret: &Option<PaymentSecret>, total_value: u64, cur_height: u32) -> Result<(), APIError> {
1245 log_trace!(self.logger, "Attempting to send payment for path with next hop {}", path.first().unwrap().short_channel_id);
1246 let prng_seed = self.keys_manager.get_secure_random_bytes();
1247 let session_priv = SecretKey::from_slice(&self.keys_manager.get_secure_random_bytes()[..]).expect("RNG is busted");
1249 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
1250 .map_err(|_| APIError::RouteError{err: "Pubkey along hop was maliciously selected"})?;
1251 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, payment_secret, cur_height)?;
1252 if onion_utils::route_size_insane(&onion_payloads) {
1253 return Err(APIError::RouteError{err: "Route size too large considering onion data"});
1255 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash);
1257 let _ = self.total_consistency_lock.read().unwrap();
1259 let err: Result<(), _> = loop {
1260 let mut channel_lock = self.channel_state.lock().unwrap();
1261 let id = match channel_lock.short_to_id.get(&path.first().unwrap().short_channel_id) {
1262 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
1263 Some(id) => id.clone(),
1266 let channel_state = &mut *channel_lock;
1267 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1269 if chan.get().get_their_node_id() != path.first().unwrap().pubkey {
1270 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1272 if !chan.get().is_live() {
1273 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!".to_owned()});
1275 break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1277 session_priv: session_priv.clone(),
1278 first_hop_htlc_msat: htlc_msat,
1279 }, onion_packet, &self.logger), channel_state, chan)
1281 Some((update_add, commitment_signed, monitor_update)) => {
1282 if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) {
1283 maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true);
1284 // Note that MonitorUpdateFailed here indicates (per function docs)
1285 // that we will resend the commitment update once monitor updating
1286 // is restored. Therefore, we must return an error indicating that
1287 // it is unsafe to retry the payment wholesale, which we do in the
1288 // send_payment check for MonitorUpdateFailed, below.
1289 return Err(APIError::MonitorUpdateFailed);
1292 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1293 node_id: path.first().unwrap().pubkey,
1294 updates: msgs::CommitmentUpdate {
1295 update_add_htlcs: vec![update_add],
1296 update_fulfill_htlcs: Vec::new(),
1297 update_fail_htlcs: Vec::new(),
1298 update_fail_malformed_htlcs: Vec::new(),
1306 } else { unreachable!(); }
1310 match handle_error!(self, err, path.first().unwrap().pubkey) {
1311 Ok(_) => unreachable!(),
1313 Err(APIError::ChannelUnavailable { err: e.err })
1318 /// Sends a payment along a given route.
1320 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1321 /// fields for more info.
1323 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1324 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1325 /// next hop knows the preimage to payment_hash they can claim an additional amount as
1326 /// specified in the last hop in the route! Thus, you should probably do your own
1327 /// payment_preimage tracking (which you should already be doing as they represent "proof of
1328 /// payment") and prevent double-sends yourself.
1330 /// May generate SendHTLCs message(s) event on success, which should be relayed.
1332 /// Each path may have a different return value, and PaymentSendValue may return a Vec with
1333 /// each entry matching the corresponding-index entry in the route paths, see
1334 /// PaymentSendFailure for more info.
1336 /// In general, a path may raise:
1337 /// * APIError::RouteError when an invalid route or forwarding parameter (cltv_delta, fee,
1338 /// node public key) is specified.
1339 /// * APIError::ChannelUnavailable if the next-hop channel is not available for updates
1340 /// (including due to previous monitor update failure or new permanent monitor update
1342 /// * APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1343 /// relevant updates.
1345 /// Note that depending on the type of the PaymentSendFailure the HTLC may have been
1346 /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
1347 /// different route unless you intend to pay twice!
1349 /// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
1350 /// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
1351 /// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
1352 /// must not contain multiple paths as multi-path payments require a recipient-provided
1354 /// If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
1355 /// bit set (either as required or as available). If multiple paths are present in the Route,
1356 /// we assume the invoice had the basic_mpp feature set.
1357 pub fn send_payment(&self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>) -> Result<(), PaymentSendFailure> {
1358 if route.paths.len() < 1 {
1359 return Err(PaymentSendFailure::ParameterError(APIError::RouteError{err: "There must be at least one path to send over"}));
1361 if route.paths.len() > 10 {
1362 // This limit is completely arbitrary - there aren't any real fundamental path-count
1363 // limits. After we support retrying individual paths we should likely bump this, but
1364 // for now more than 10 paths likely carries too much one-path failure.
1365 return Err(PaymentSendFailure::ParameterError(APIError::RouteError{err: "Sending over more than 10 paths is not currently supported"}));
1367 let mut total_value = 0;
1368 let our_node_id = self.get_our_node_id();
1369 let mut path_errs = Vec::with_capacity(route.paths.len());
1370 'path_check: for path in route.paths.iter() {
1371 if path.len() < 1 || path.len() > 20 {
1372 path_errs.push(Err(APIError::RouteError{err: "Path didn't go anywhere/had bogus size"}));
1373 continue 'path_check;
1375 for (idx, hop) in path.iter().enumerate() {
1376 if idx != path.len() - 1 && hop.pubkey == our_node_id {
1377 path_errs.push(Err(APIError::RouteError{err: "Path went through us but wasn't a simple rebalance loop to us"}));
1378 continue 'path_check;
1381 total_value += path.last().unwrap().fee_msat;
1382 path_errs.push(Ok(()));
1384 if path_errs.iter().any(|e| e.is_err()) {
1385 return Err(PaymentSendFailure::PathParameterError(path_errs));
1388 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1389 let mut results = Vec::new();
1390 for path in route.paths.iter() {
1391 results.push(self.send_payment_along_path(&path, &payment_hash, payment_secret, total_value, cur_height));
1393 let mut has_ok = false;
1394 let mut has_err = false;
1395 for res in results.iter() {
1396 if res.is_ok() { has_ok = true; }
1397 if res.is_err() { has_err = true; }
1398 if let &Err(APIError::MonitorUpdateFailed) = res {
1399 // MonitorUpdateFailed is inherently unsafe to retry, so we call it a
1406 if has_err && has_ok {
1407 Err(PaymentSendFailure::PartialFailure(results))
1409 Err(PaymentSendFailure::AllFailedRetrySafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1415 /// Call this upon creation of a funding transaction for the given channel.
1417 /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1418 /// or your counterparty can steal your funds!
1420 /// Panics if a funding transaction has already been provided for this channel.
1422 /// May panic if the funding_txo is duplicative with some other channel (note that this should
1423 /// be trivially prevented by using unique funding transaction keys per-channel).
1424 pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1425 let _ = self.total_consistency_lock.read().unwrap();
1428 let (res, chan) = match self.channel_state.lock().unwrap().by_id.remove(temporary_channel_id) {
1430 (chan.get_outbound_funding_created(funding_txo, &self.logger)
1431 .map_err(|e| if let ChannelError::Close(msg) = e {
1432 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(true), None)
1433 } else { unreachable!(); })
1438 match handle_error!(self, res, chan.get_their_node_id()) {
1439 Ok(funding_msg) => {
1442 Err(_) => { return; }
1446 let mut channel_state = self.channel_state.lock().unwrap();
1447 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1448 node_id: chan.get_their_node_id(),
1451 match channel_state.by_id.entry(chan.channel_id()) {
1452 hash_map::Entry::Occupied(_) => {
1453 panic!("Generated duplicate funding txid?");
1455 hash_map::Entry::Vacant(e) => {
1461 fn get_announcement_sigs(&self, chan: &Channel<ChanSigner>) -> Option<msgs::AnnouncementSignatures> {
1462 if !chan.should_announce() {
1463 log_trace!(self.logger, "Can't send announcement_signatures for private channel {}", log_bytes!(chan.channel_id()));
1467 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1469 Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1471 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1472 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1474 Some(msgs::AnnouncementSignatures {
1475 channel_id: chan.channel_id(),
1476 short_channel_id: chan.get_short_channel_id().unwrap(),
1477 node_signature: our_node_sig,
1478 bitcoin_signature: our_bitcoin_sig,
1483 // Messages of up to 64KB should never end up more than half full with addresses, as that would
1484 // be absurd. We ensure this by checking that at least 500 (our stated public contract on when
1485 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
1487 const HALF_MESSAGE_IS_ADDRS: u32 = ::std::u16::MAX as u32 / (msgs::NetAddress::MAX_LEN as u32 + 1) / 2;
1490 // ...by failing to compile if the number of addresses that would be half of a message is
1491 // smaller than 500:
1492 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 500;
1494 /// Generates a signed node_announcement from the given arguments and creates a
1495 /// BroadcastNodeAnnouncement event. Note that such messages will be ignored unless peers have
1496 /// seen a channel_announcement from us (ie unless we have public channels open).
1498 /// RGB is a node "color" and alias is a printable human-readable string to describe this node
1499 /// to humans. They carry no in-protocol meaning.
1501 /// addresses represent the set (possibly empty) of socket addresses on which this node accepts
1502 /// incoming connections. These will be broadcast to the network, publicly tying these
1503 /// addresses together. If you wish to preserve user privacy, addresses should likely contain
1504 /// only Tor Onion addresses.
1506 /// Panics if addresses is absurdly large (more than 500).
1507 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: Vec<msgs::NetAddress>) {
1508 let _ = self.total_consistency_lock.read().unwrap();
1510 if addresses.len() > 500 {
1511 panic!("More than half the message size was taken up by public addresses!");
1514 let announcement = msgs::UnsignedNodeAnnouncement {
1515 features: NodeFeatures::known(),
1516 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1517 node_id: self.get_our_node_id(),
1518 rgb, alias, addresses,
1519 excess_address_data: Vec::new(),
1520 excess_data: Vec::new(),
1522 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1524 let mut channel_state = self.channel_state.lock().unwrap();
1525 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
1526 msg: msgs::NodeAnnouncement {
1527 signature: self.secp_ctx.sign(&msghash, &self.our_network_key),
1528 contents: announcement
1533 /// Processes HTLCs which are pending waiting on random forward delay.
1535 /// Should only really ever be called in response to a PendingHTLCsForwardable event.
1536 /// Will likely generate further events.
1537 pub fn process_pending_htlc_forwards(&self) {
1538 let _ = self.total_consistency_lock.read().unwrap();
1540 let mut new_events = Vec::new();
1541 let mut failed_forwards = Vec::new();
1542 let mut handle_errors = Vec::new();
1544 let mut channel_state_lock = self.channel_state.lock().unwrap();
1545 let channel_state = &mut *channel_state_lock;
1547 for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1548 if short_chan_id != 0 {
1549 let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1550 Some(chan_id) => chan_id.clone(),
1552 failed_forwards.reserve(pending_forwards.len());
1553 for forward_info in pending_forwards.drain(..) {
1554 match forward_info {
1555 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info } => {
1556 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1557 short_channel_id: prev_short_channel_id,
1558 htlc_id: prev_htlc_id,
1559 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1561 failed_forwards.push((htlc_source, forward_info.payment_hash,
1562 HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() }
1565 HTLCForwardInfo::FailHTLC { .. } => {
1566 // Channel went away before we could fail it. This implies
1567 // the channel is now on chain and our counterparty is
1568 // trying to broadcast the HTLC-Timeout, but that's their
1569 // problem, not ours.
1576 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(forward_chan_id) {
1577 let mut add_htlc_msgs = Vec::new();
1578 let mut fail_htlc_msgs = Vec::new();
1579 for forward_info in pending_forwards.drain(..) {
1580 match forward_info {
1581 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1582 routing: PendingHTLCRouting::Forward {
1584 }, incoming_shared_secret, payment_hash, amt_to_forward, outgoing_cltv_value }, } => {
1585 log_trace!(self.logger, "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);
1586 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1587 short_channel_id: prev_short_channel_id,
1588 htlc_id: prev_htlc_id,
1589 incoming_packet_shared_secret: incoming_shared_secret,
1591 match chan.get_mut().send_htlc(amt_to_forward, payment_hash, outgoing_cltv_value, htlc_source.clone(), onion_packet) {
1593 if let ChannelError::Ignore(msg) = e {
1594 log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
1596 panic!("Stated return value requirements in send_htlc() were not met");
1598 let chan_update = self.get_channel_update(chan.get()).unwrap();
1599 failed_forwards.push((htlc_source, payment_hash,
1600 HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.encode_with_len() }
1606 Some(msg) => { add_htlc_msgs.push(msg); },
1608 // Nothing to do here...we're waiting on a remote
1609 // revoke_and_ack before we can add anymore HTLCs. The Channel
1610 // will automatically handle building the update_add_htlc and
1611 // commitment_signed messages when we can.
1612 // TODO: Do some kind of timer to set the channel as !is_live()
1613 // as we don't really want others relying on us relaying through
1614 // this channel currently :/.
1620 HTLCForwardInfo::AddHTLC { .. } => {
1621 panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
1623 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
1624 log_trace!(self.logger, "Failing HTLC back to channel with short id {} after delay", short_chan_id);
1625 match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet) {
1627 if let ChannelError::Ignore(msg) = e {
1628 log_trace!(self.logger, "Failed to fail backwards to short_id {}: {}", short_chan_id, msg);
1630 panic!("Stated return value requirements in get_update_fail_htlc() were not met");
1632 // fail-backs are best-effort, we probably already have one
1633 // pending, and if not that's OK, if not, the channel is on
1634 // the chain and sending the HTLC-Timeout is their problem.
1637 Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
1639 // Nothing to do here...we're waiting on a remote
1640 // revoke_and_ack before we can update the commitment
1641 // transaction. The Channel will automatically handle
1642 // building the update_fail_htlc and commitment_signed
1643 // messages when we can.
1644 // We don't need any kind of timer here as they should fail
1645 // the channel onto the chain if they can't get our
1646 // update_fail_htlc in time, it's not our problem.
1653 if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
1654 let (commitment_msg, monitor_update) = match chan.get_mut().send_commitment(&self.logger) {
1657 // We surely failed send_commitment due to bad keys, in that case
1658 // close channel and then send error message to peer.
1659 let their_node_id = chan.get().get_their_node_id();
1660 let err: Result<(), _> = match e {
1661 ChannelError::Ignore(_) => {
1662 panic!("Stated return value requirements in send_commitment() were not met");
1664 ChannelError::Close(msg) => {
1665 log_trace!(self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
1666 let (channel_id, mut channel) = chan.remove_entry();
1667 if let Some(short_id) = channel.get_short_channel_id() {
1668 channel_state.short_to_id.remove(&short_id);
1670 Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, channel.force_shutdown(true), self.get_channel_update(&channel).ok()))
1672 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"); }
1674 handle_errors.push((their_node_id, err));
1678 if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) {
1679 handle_errors.push((chan.get().get_their_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
1682 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1683 node_id: chan.get().get_their_node_id(),
1684 updates: msgs::CommitmentUpdate {
1685 update_add_htlcs: add_htlc_msgs,
1686 update_fulfill_htlcs: Vec::new(),
1687 update_fail_htlcs: fail_htlc_msgs,
1688 update_fail_malformed_htlcs: Vec::new(),
1690 commitment_signed: commitment_msg,
1698 for forward_info in pending_forwards.drain(..) {
1699 match forward_info {
1700 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1701 routing: PendingHTLCRouting::Receive { payment_data, incoming_cltv_expiry },
1702 incoming_shared_secret, payment_hash, amt_to_forward, .. }, } => {
1703 let prev_hop = HTLCPreviousHopData {
1704 short_channel_id: prev_short_channel_id,
1705 htlc_id: prev_htlc_id,
1706 incoming_packet_shared_secret: incoming_shared_secret,
1709 let mut total_value = 0;
1710 let payment_secret_opt =
1711 if let &Some(ref data) = &payment_data { Some(data.payment_secret.clone()) } else { None };
1712 let htlcs = channel_state.claimable_htlcs.entry((payment_hash, payment_secret_opt))
1713 .or_insert(Vec::new());
1714 htlcs.push(ClaimableHTLC {
1716 value: amt_to_forward,
1717 payment_data: payment_data.clone(),
1718 cltv_expiry: incoming_cltv_expiry,
1720 if let &Some(ref data) = &payment_data {
1721 for htlc in htlcs.iter() {
1722 total_value += htlc.value;
1723 if htlc.payment_data.as_ref().unwrap().total_msat != data.total_msat {
1724 total_value = msgs::MAX_VALUE_MSAT;
1726 if total_value >= msgs::MAX_VALUE_MSAT { break; }
1728 if total_value >= msgs::MAX_VALUE_MSAT || total_value > data.total_msat {
1729 for htlc in htlcs.iter() {
1730 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
1731 htlc_msat_height_data.extend_from_slice(
1732 &byte_utils::be32_to_array(
1733 self.latest_block_height.load(Ordering::Acquire)
1737 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
1738 short_channel_id: htlc.prev_hop.short_channel_id,
1739 htlc_id: htlc.prev_hop.htlc_id,
1740 incoming_packet_shared_secret: htlc.prev_hop.incoming_packet_shared_secret,
1742 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data }
1745 } else if total_value == data.total_msat {
1746 new_events.push(events::Event::PaymentReceived {
1747 payment_hash: payment_hash,
1748 payment_secret: Some(data.payment_secret),
1753 new_events.push(events::Event::PaymentReceived {
1754 payment_hash: payment_hash,
1755 payment_secret: None,
1756 amt: amt_to_forward,
1760 HTLCForwardInfo::AddHTLC { .. } => {
1761 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
1763 HTLCForwardInfo::FailHTLC { .. } => {
1764 panic!("Got pending fail of our own HTLC");
1772 for (htlc_source, payment_hash, failure_reason) in failed_forwards.drain(..) {
1773 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, failure_reason);
1776 for (their_node_id, err) in handle_errors.drain(..) {
1777 let _ = handle_error!(self, err, their_node_id);
1780 if new_events.is_empty() { return }
1781 let mut events = self.pending_events.lock().unwrap();
1782 events.append(&mut new_events);
1785 /// If a peer is disconnected we mark any channels with that peer as 'disabled'.
1786 /// After some time, if channels are still disabled we need to broadcast a ChannelUpdate
1787 /// to inform the network about the uselessness of these channels.
1789 /// This method handles all the details, and must be called roughly once per minute.
1790 pub fn timer_chan_freshness_every_min(&self) {
1791 let _ = self.total_consistency_lock.read().unwrap();
1792 let mut channel_state_lock = self.channel_state.lock().unwrap();
1793 let channel_state = &mut *channel_state_lock;
1794 for (_, chan) in channel_state.by_id.iter_mut() {
1795 if chan.is_disabled_staged() && !chan.is_live() {
1796 if let Ok(update) = self.get_channel_update(&chan) {
1797 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1802 } else if chan.is_disabled_staged() && chan.is_live() {
1804 } else if chan.is_disabled_marked() {
1805 chan.to_disabled_staged();
1810 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1811 /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
1812 /// along the path (including in our own channel on which we received it).
1813 /// Returns false if no payment was found to fail backwards, true if the process of failing the
1814 /// HTLC backwards has been started.
1815 pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, payment_secret: &Option<PaymentSecret>) -> bool {
1816 let _ = self.total_consistency_lock.read().unwrap();
1818 let mut channel_state = Some(self.channel_state.lock().unwrap());
1819 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(*payment_hash, *payment_secret));
1820 if let Some(mut sources) = removed_source {
1821 for htlc in sources.drain(..) {
1822 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1823 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
1824 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
1825 self.latest_block_height.load(Ordering::Acquire) as u32,
1827 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1828 HTLCSource::PreviousHopData(htlc.prev_hop), payment_hash,
1829 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data });
1835 // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
1836 // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
1837 // be surfaced to the user.
1838 fn fail_holding_cell_htlcs(&self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: [u8; 32]) {
1839 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
1841 HTLCSource::PreviousHopData(HTLCPreviousHopData { .. }) => {
1842 let (failure_code, onion_failure_data) =
1843 match self.channel_state.lock().unwrap().by_id.entry(channel_id) {
1844 hash_map::Entry::Occupied(chan_entry) => {
1845 if let Ok(upd) = self.get_channel_update(&chan_entry.get()) {
1846 (0x1000|7, upd.encode_with_len())
1848 (0x4000|10, Vec::new())
1851 hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
1853 let channel_state = self.channel_state.lock().unwrap();
1854 self.fail_htlc_backwards_internal(channel_state,
1855 htlc_src, &payment_hash, HTLCFailReason::Reason { failure_code, data: onion_failure_data});
1857 HTLCSource::OutboundRoute { .. } => {
1858 self.pending_events.lock().unwrap().push(
1859 events::Event::PaymentFailed {
1861 rejected_by_dest: false,
1873 /// Fails an HTLC backwards to the sender of it to us.
1874 /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1875 /// There are several callsites that do stupid things like loop over a list of payment_hashes
1876 /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1877 /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1878 /// still-available channels.
1879 fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<ChanSigner>>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1880 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
1881 //identify whether we sent it or not based on the (I presume) very different runtime
1882 //between the branches here. We should make this async and move it into the forward HTLCs
1885 HTLCSource::OutboundRoute { ref path, .. } => {
1886 log_trace!(self.logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1887 mem::drop(channel_state_lock);
1888 match &onion_error {
1889 &HTLCFailReason::LightningError { ref err } => {
1891 let (channel_update, payment_retryable, onion_error_code, onion_error_data) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
1893 let (channel_update, payment_retryable, _, _) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
1894 // TODO: If we decided to blame ourselves (or one of our channels) in
1895 // process_onion_failure we should close that channel as it implies our
1896 // next-hop is needlessly blaming us!
1897 if let Some(update) = channel_update {
1898 self.channel_state.lock().unwrap().pending_msg_events.push(
1899 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1904 self.pending_events.lock().unwrap().push(
1905 events::Event::PaymentFailed {
1906 payment_hash: payment_hash.clone(),
1907 rejected_by_dest: !payment_retryable,
1909 error_code: onion_error_code,
1911 error_data: onion_error_data
1915 &HTLCFailReason::Reason {
1921 // we get a fail_malformed_htlc from the first hop
1922 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1923 // failures here, but that would be insufficient as get_route
1924 // generally ignores its view of our own channels as we provide them via
1926 // TODO: For non-temporary failures, we really should be closing the
1927 // channel here as we apparently can't relay through them anyway.
1928 self.pending_events.lock().unwrap().push(
1929 events::Event::PaymentFailed {
1930 payment_hash: payment_hash.clone(),
1931 rejected_by_dest: path.len() == 1,
1933 error_code: Some(*failure_code),
1935 error_data: Some(data.clone()),
1941 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1942 let err_packet = match onion_error {
1943 HTLCFailReason::Reason { failure_code, data } => {
1944 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1945 let packet = onion_utils::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1946 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1948 HTLCFailReason::LightningError { err } => {
1949 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards with pre-built LightningError", log_bytes!(payment_hash.0));
1950 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1954 let mut forward_event = None;
1955 if channel_state_lock.forward_htlcs.is_empty() {
1956 forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
1958 match channel_state_lock.forward_htlcs.entry(short_channel_id) {
1959 hash_map::Entry::Occupied(mut entry) => {
1960 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id, err_packet });
1962 hash_map::Entry::Vacant(entry) => {
1963 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id, err_packet }));
1966 mem::drop(channel_state_lock);
1967 if let Some(time) = forward_event {
1968 let mut pending_events = self.pending_events.lock().unwrap();
1969 pending_events.push(events::Event::PendingHTLCsForwardable {
1970 time_forwardable: time
1977 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1978 /// generating message events for the net layer to claim the payment, if possible. Thus, you
1979 /// should probably kick the net layer to go send messages if this returns true!
1981 /// You must specify the expected amounts for this HTLC, and we will only claim HTLCs
1982 /// available within a few percent of the expected amount. This is critical for several
1983 /// reasons : a) it avoids providing senders with `proof-of-payment` (in the form of the
1984 /// payment_preimage without having provided the full value and b) it avoids certain
1985 /// privacy-breaking recipient-probing attacks which may reveal payment activity to
1986 /// motivated attackers.
1988 /// Note that the privacy concerns in (b) are not relevant in payments with a payment_secret
1989 /// set. Thus, for such payments we will claim any payments which do not under-pay.
1991 /// May panic if called except in response to a PaymentReceived event.
1992 pub fn claim_funds(&self, payment_preimage: PaymentPreimage, payment_secret: &Option<PaymentSecret>, expected_amount: u64) -> bool {
1993 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1995 let _ = self.total_consistency_lock.read().unwrap();
1997 let mut channel_state = Some(self.channel_state.lock().unwrap());
1998 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(payment_hash, *payment_secret));
1999 if let Some(mut sources) = removed_source {
2000 assert!(!sources.is_empty());
2002 // If we are claiming an MPP payment, we have to take special care to ensure that each
2003 // channel exists before claiming all of the payments (inside one lock).
2004 // Note that channel existance is sufficient as we should always get a monitor update
2005 // which will take care of the real HTLC claim enforcement.
2007 // If we find an HTLC which we would need to claim but for which we do not have a
2008 // channel, we will fail all parts of the MPP payment. While we could wait and see if
2009 // the sender retries the already-failed path(s), it should be a pretty rare case where
2010 // we got all the HTLCs and then a channel closed while we were waiting for the user to
2011 // provide the preimage, so worrying too much about the optimal handling isn't worth
2014 let (is_mpp, mut valid_mpp) = if let &Some(ref data) = &sources[0].payment_data {
2015 assert!(payment_secret.is_some());
2016 (true, data.total_msat >= expected_amount)
2018 assert!(payment_secret.is_none());
2022 for htlc in sources.iter() {
2023 if !is_mpp || !valid_mpp { break; }
2024 if let None = channel_state.as_ref().unwrap().short_to_id.get(&htlc.prev_hop.short_channel_id) {
2029 let mut errs = Vec::new();
2030 let mut claimed_any_htlcs = false;
2031 for htlc in sources.drain(..) {
2032 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
2033 if (is_mpp && !valid_mpp) || (!is_mpp && (htlc.value < expected_amount || htlc.value > expected_amount * 2)) {
2034 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
2035 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
2036 self.latest_block_height.load(Ordering::Acquire) as u32,
2038 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
2039 HTLCSource::PreviousHopData(htlc.prev_hop), &payment_hash,
2040 HTLCFailReason::Reason { failure_code: 0x4000|15, data: htlc_msat_height_data });
2042 match self.claim_funds_from_hop(channel_state.as_mut().unwrap(), htlc.prev_hop, payment_preimage) {
2044 if let msgs::ErrorAction::IgnoreError = e.1.err.action {
2045 // We got a temporary failure updating monitor, but will claim the
2046 // HTLC when the monitor updating is restored (or on chain).
2047 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", e.1.err.err);
2048 claimed_any_htlcs = true;
2049 } else { errs.push(e); }
2051 Err(None) if is_mpp => unreachable!("We already checked for channel existence, we can't fail here!"),
2053 log_warn!(self.logger, "Channel we expected to claim an HTLC from was closed.");
2055 Ok(()) => claimed_any_htlcs = true,
2060 // Now that we've done the entire above loop in one lock, we can handle any errors
2061 // which were generated.
2062 channel_state.take();
2064 for (their_node_id, err) in errs.drain(..) {
2065 let res: Result<(), _> = Err(err);
2066 let _ = handle_error!(self, res, their_node_id);
2073 fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard<ChannelHolder<ChanSigner>>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> Result<(), Option<(PublicKey, MsgHandleErrInternal)>> {
2074 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
2075 let channel_state = &mut **channel_state_lock;
2076 let chan_id = match channel_state.short_to_id.get(&prev_hop.short_channel_id) {
2077 Some(chan_id) => chan_id.clone(),
2083 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(chan_id) {
2084 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2085 match chan.get_mut().get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger) {
2086 Ok((msgs, monitor_option)) => {
2087 if let Some(monitor_update) = monitor_option {
2088 if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) {
2089 if was_frozen_for_monitor {
2090 assert!(msgs.is_none());
2092 return Err(Some((chan.get().get_their_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, msgs.is_some()).unwrap_err())));
2096 if let Some((msg, commitment_signed)) = msgs {
2097 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2098 node_id: chan.get().get_their_node_id(),
2099 updates: msgs::CommitmentUpdate {
2100 update_add_htlcs: Vec::new(),
2101 update_fulfill_htlcs: vec![msg],
2102 update_fail_htlcs: Vec::new(),
2103 update_fail_malformed_htlcs: Vec::new(),
2112 // TODO: Do something with e?
2113 // This should only occur if we are claiming an HTLC at the same time as the
2114 // HTLC is being failed (eg because a block is being connected and this caused
2115 // an HTLC to time out). This should, of course, only occur if the user is the
2116 // one doing the claiming (as it being a part of a peer claim would imply we're
2117 // about to lose funds) and only if the lock in claim_funds was dropped as a
2118 // previous HTLC was failed (thus not for an MPP payment).
2119 debug_assert!(false, "This shouldn't be reachable except in absurdly rare cases between monitor updates and HTLC timeouts: {:?}", e);
2123 } else { unreachable!(); }
2126 fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<ChanSigner>>, source: HTLCSource, payment_preimage: PaymentPreimage) {
2128 HTLCSource::OutboundRoute { .. } => {
2129 mem::drop(channel_state_lock);
2130 let mut pending_events = self.pending_events.lock().unwrap();
2131 pending_events.push(events::Event::PaymentSent {
2135 HTLCSource::PreviousHopData(hop_data) => {
2136 if let Err((their_node_id, err)) = match self.claim_funds_from_hop(&mut channel_state_lock, hop_data, payment_preimage) {
2139 // TODO: There is probably a channel monitor somewhere that needs to
2140 // learn the preimage as the channel already hit the chain and that's
2141 // why it's missing.
2144 Err(Some(res)) => Err(res),
2146 mem::drop(channel_state_lock);
2147 let res: Result<(), _> = Err(err);
2148 let _ = handle_error!(self, res, their_node_id);
2154 /// Gets the node_id held by this ChannelManager
2155 pub fn get_our_node_id(&self) -> PublicKey {
2156 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
2159 /// Restores a single, given channel to normal operation after a
2160 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
2163 /// All ChannelMonitor updates up to and including highest_applied_update_id must have been
2164 /// fully committed in every copy of the given channels' ChannelMonitors.
2166 /// Note that there is no effect to calling with a highest_applied_update_id other than the
2167 /// current latest ChannelMonitorUpdate and one call to this function after multiple
2168 /// ChannelMonitorUpdateErr::TemporaryFailures is fine. The highest_applied_update_id field
2169 /// exists largely only to prevent races between this and concurrent update_monitor calls.
2171 /// Thus, the anticipated use is, at a high level:
2172 /// 1) You register a ManyChannelMonitor with this ChannelManager,
2173 /// 2) it stores each update to disk, and begins updating any remote (eg watchtower) copies of
2174 /// said ChannelMonitors as it can, returning ChannelMonitorUpdateErr::TemporaryFailures
2175 /// any time it cannot do so instantly,
2176 /// 3) update(s) are applied to each remote copy of a ChannelMonitor,
2177 /// 4) once all remote copies are updated, you call this function with the update_id that
2178 /// completed, and once it is the latest the Channel will be re-enabled.
2179 pub fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64) {
2180 let _ = self.total_consistency_lock.read().unwrap();
2182 let mut close_results = Vec::new();
2183 let mut htlc_forwards = Vec::new();
2184 let mut htlc_failures = Vec::new();
2185 let mut pending_events = Vec::new();
2188 let mut channel_lock = self.channel_state.lock().unwrap();
2189 let channel_state = &mut *channel_lock;
2190 let short_to_id = &mut channel_state.short_to_id;
2191 let pending_msg_events = &mut channel_state.pending_msg_events;
2192 let channel = match channel_state.by_id.get_mut(&funding_txo.to_channel_id()) {
2196 if !channel.is_awaiting_monitor_update() || channel.get_latest_monitor_update_id() != highest_applied_update_id {
2200 let (raa, commitment_update, order, pending_forwards, mut pending_failures, needs_broadcast_safe, funding_locked) = channel.monitor_updating_restored(&self.logger);
2201 if !pending_forwards.is_empty() {
2202 htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
2204 htlc_failures.append(&mut pending_failures);
2206 macro_rules! handle_cs { () => {
2207 if let Some(update) = commitment_update {
2208 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2209 node_id: channel.get_their_node_id(),
2214 macro_rules! handle_raa { () => {
2215 if let Some(revoke_and_ack) = raa {
2216 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2217 node_id: channel.get_their_node_id(),
2218 msg: revoke_and_ack,
2223 RAACommitmentOrder::CommitmentFirst => {
2227 RAACommitmentOrder::RevokeAndACKFirst => {
2232 if needs_broadcast_safe {
2233 pending_events.push(events::Event::FundingBroadcastSafe {
2234 funding_txo: channel.get_funding_txo().unwrap(),
2235 user_channel_id: channel.get_user_id(),
2238 if let Some(msg) = funding_locked {
2239 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2240 node_id: channel.get_their_node_id(),
2243 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2244 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2245 node_id: channel.get_their_node_id(),
2246 msg: announcement_sigs,
2249 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2253 self.pending_events.lock().unwrap().append(&mut pending_events);
2255 for failure in htlc_failures.drain(..) {
2256 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2258 self.forward_htlcs(&mut htlc_forwards[..]);
2260 for res in close_results.drain(..) {
2261 self.finish_force_close_channel(res);
2265 fn internal_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
2266 if msg.chain_hash != self.genesis_hash {
2267 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
2270 let channel = Channel::new_from_req(&self.fee_estimator, &self.keys_manager, their_node_id.clone(), their_features, msg, 0, &self.default_configuration)
2271 .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
2272 let mut channel_state_lock = self.channel_state.lock().unwrap();
2273 let channel_state = &mut *channel_state_lock;
2274 match channel_state.by_id.entry(channel.channel_id()) {
2275 hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!".to_owned(), msg.temporary_channel_id.clone())),
2276 hash_map::Entry::Vacant(entry) => {
2277 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
2278 node_id: their_node_id.clone(),
2279 msg: channel.get_accept_channel(),
2281 entry.insert(channel);
2287 fn internal_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
2288 let (value, output_script, user_id) = {
2289 let mut channel_lock = self.channel_state.lock().unwrap();
2290 let channel_state = &mut *channel_lock;
2291 match channel_state.by_id.entry(msg.temporary_channel_id) {
2292 hash_map::Entry::Occupied(mut chan) => {
2293 if chan.get().get_their_node_id() != *their_node_id {
2294 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
2296 try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration, their_features), channel_state, chan);
2297 (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
2299 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
2302 let mut pending_events = self.pending_events.lock().unwrap();
2303 pending_events.push(events::Event::FundingGenerationReady {
2304 temporary_channel_id: msg.temporary_channel_id,
2305 channel_value_satoshis: value,
2306 output_script: output_script,
2307 user_channel_id: user_id,
2312 fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
2313 let ((funding_msg, monitor_update), mut chan) = {
2314 let mut channel_lock = self.channel_state.lock().unwrap();
2315 let channel_state = &mut *channel_lock;
2316 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
2317 hash_map::Entry::Occupied(mut chan) => {
2318 if chan.get().get_their_node_id() != *their_node_id {
2319 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
2321 (try_chan_entry!(self, chan.get_mut().funding_created(msg, &self.logger), channel_state, chan), chan.remove())
2323 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
2326 // Because we have exclusive ownership of the channel here we can release the channel_state
2327 // lock before add_monitor
2328 if let Err(e) = self.monitor.add_monitor(monitor_update.get_funding_txo().0, monitor_update) {
2330 ChannelMonitorUpdateErr::PermanentFailure => {
2331 // Note that we reply with the new channel_id in error messages if we gave up on the
2332 // channel, not the temporary_channel_id. This is compatible with ourselves, but the
2333 // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
2334 // any messages referencing a previously-closed channel anyway.
2335 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure".to_owned(), funding_msg.channel_id, chan.force_shutdown(true), None));
2337 ChannelMonitorUpdateErr::TemporaryFailure => {
2338 // There's no problem signing a counterparty's funding transaction if our monitor
2339 // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
2340 // accepted payment from yet. We do, however, need to wait to send our funding_locked
2341 // until we have persisted our monitor.
2342 chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
2346 let mut channel_state_lock = self.channel_state.lock().unwrap();
2347 let channel_state = &mut *channel_state_lock;
2348 match channel_state.by_id.entry(funding_msg.channel_id) {
2349 hash_map::Entry::Occupied(_) => {
2350 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
2352 hash_map::Entry::Vacant(e) => {
2353 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
2354 node_id: their_node_id.clone(),
2363 fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
2364 let (funding_txo, user_id) = {
2365 let mut channel_lock = self.channel_state.lock().unwrap();
2366 let channel_state = &mut *channel_lock;
2367 match channel_state.by_id.entry(msg.channel_id) {
2368 hash_map::Entry::Occupied(mut chan) => {
2369 if chan.get().get_their_node_id() != *their_node_id {
2370 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2372 let monitor = match chan.get_mut().funding_signed(&msg, &self.logger) {
2373 Ok(update) => update,
2374 Err(e) => try_chan_entry!(self, Err(e), channel_state, chan),
2376 if let Err(e) = self.monitor.add_monitor(chan.get().get_funding_txo().unwrap(), monitor) {
2377 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
2379 (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
2381 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2384 let mut pending_events = self.pending_events.lock().unwrap();
2385 pending_events.push(events::Event::FundingBroadcastSafe {
2386 funding_txo: funding_txo,
2387 user_channel_id: user_id,
2392 fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
2393 let mut channel_state_lock = self.channel_state.lock().unwrap();
2394 let channel_state = &mut *channel_state_lock;
2395 match channel_state.by_id.entry(msg.channel_id) {
2396 hash_map::Entry::Occupied(mut chan) => {
2397 if chan.get().get_their_node_id() != *their_node_id {
2398 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2400 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
2401 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
2402 log_trace!(self.logger, "Sending announcement_signatures for {} in response to funding_locked", log_bytes!(chan.get().channel_id()));
2403 // If we see locking block before receiving remote funding_locked, we broadcast our
2404 // announcement_sigs at remote funding_locked reception. If we receive remote
2405 // funding_locked before seeing locking block, we broadcast our announcement_sigs at locking
2406 // block connection. We should guanrantee to broadcast announcement_sigs to our peer whatever
2407 // the order of the events but our peer may not receive it due to disconnection. The specs
2408 // lacking an acknowledgement for announcement_sigs we may have to re-send them at peer
2409 // connection in the future if simultaneous misses by both peers due to network/hardware
2410 // failures is an issue. Note, to achieve its goal, only one of the announcement_sigs needs
2411 // to be received, from then sigs are going to be flood to the whole network.
2412 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2413 node_id: their_node_id.clone(),
2414 msg: announcement_sigs,
2419 hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2423 fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
2424 let (mut dropped_htlcs, chan_option) = {
2425 let mut channel_state_lock = self.channel_state.lock().unwrap();
2426 let channel_state = &mut *channel_state_lock;
2428 match channel_state.by_id.entry(msg.channel_id.clone()) {
2429 hash_map::Entry::Occupied(mut chan_entry) => {
2430 if chan_entry.get().get_their_node_id() != *their_node_id {
2431 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2433 let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&self.fee_estimator, &msg), channel_state, chan_entry);
2434 if let Some(msg) = shutdown {
2435 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2436 node_id: their_node_id.clone(),
2440 if let Some(msg) = closing_signed {
2441 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2442 node_id: their_node_id.clone(),
2446 if chan_entry.get().is_shutdown() {
2447 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2448 channel_state.short_to_id.remove(&short_id);
2450 (dropped_htlcs, Some(chan_entry.remove_entry().1))
2451 } else { (dropped_htlcs, None) }
2453 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2456 for htlc_source in dropped_htlcs.drain(..) {
2457 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() });
2459 if let Some(chan) = chan_option {
2460 if let Ok(update) = self.get_channel_update(&chan) {
2461 let mut channel_state = self.channel_state.lock().unwrap();
2462 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2470 fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
2471 let (tx, chan_option) = {
2472 let mut channel_state_lock = self.channel_state.lock().unwrap();
2473 let channel_state = &mut *channel_state_lock;
2474 match channel_state.by_id.entry(msg.channel_id.clone()) {
2475 hash_map::Entry::Occupied(mut chan_entry) => {
2476 if chan_entry.get().get_their_node_id() != *their_node_id {
2477 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2479 let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&self.fee_estimator, &msg), channel_state, chan_entry);
2480 if let Some(msg) = closing_signed {
2481 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2482 node_id: their_node_id.clone(),
2487 // We're done with this channel, we've got a signed closing transaction and
2488 // will send the closing_signed back to the remote peer upon return. This
2489 // also implies there are no pending HTLCs left on the channel, so we can
2490 // fully delete it from tracking (the channel monitor is still around to
2491 // watch for old state broadcasts)!
2492 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2493 channel_state.short_to_id.remove(&short_id);
2495 (tx, Some(chan_entry.remove_entry().1))
2496 } else { (tx, None) }
2498 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2501 if let Some(broadcast_tx) = tx {
2502 log_trace!(self.logger, "Broadcast onchain {}", log_tx!(broadcast_tx));
2503 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2505 if let Some(chan) = chan_option {
2506 if let Ok(update) = self.get_channel_update(&chan) {
2507 let mut channel_state = self.channel_state.lock().unwrap();
2508 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2516 fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2517 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2518 //determine the state of the payment based on our response/if we forward anything/the time
2519 //we take to respond. We should take care to avoid allowing such an attack.
2521 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2522 //us repeatedly garbled in different ways, and compare our error messages, which are
2523 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
2524 //but we should prevent it anyway.
2526 let (pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2527 let channel_state = &mut *channel_state_lock;
2529 match channel_state.by_id.entry(msg.channel_id) {
2530 hash_map::Entry::Occupied(mut chan) => {
2531 if chan.get().get_their_node_id() != *their_node_id {
2532 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2535 let create_pending_htlc_status = |chan: &Channel<ChanSigner>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
2536 // Ensure error_code has the UPDATE flag set, since by default we send a
2537 // channel update along as part of failing the HTLC.
2538 assert!((error_code & 0x1000) != 0);
2539 // If the update_add is completely bogus, the call will Err and we will close,
2540 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2541 // want to reject the new HTLC and fail it backwards instead of forwarding.
2542 match pending_forward_info {
2543 PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
2544 let reason = if let Ok(upd) = self.get_channel_update(chan) {
2545 onion_utils::build_first_hop_failure_packet(incoming_shared_secret, error_code, &{
2546 let mut res = Vec::with_capacity(8 + 128);
2547 // TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
2548 res.extend_from_slice(&byte_utils::be16_to_array(0));
2549 res.extend_from_slice(&upd.encode_with_len()[..]);
2553 // The only case where we'd be unable to
2554 // successfully get a channel update is if the
2555 // channel isn't in the fully-funded state yet,
2556 // implying our counterparty is trying to route
2557 // payments over the channel back to themselves
2558 // (cause no one else should know the short_id
2559 // is a lightning channel yet). We should have
2560 // no problem just calling this
2561 // unknown_next_peer (0x4000|10).
2562 onion_utils::build_first_hop_failure_packet(incoming_shared_secret, 0x4000|10, &[])
2564 let msg = msgs::UpdateFailHTLC {
2565 channel_id: msg.channel_id,
2566 htlc_id: msg.htlc_id,
2569 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
2571 _ => pending_forward_info
2574 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.logger), channel_state, chan);
2576 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2581 fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2582 let mut channel_lock = self.channel_state.lock().unwrap();
2584 let channel_state = &mut *channel_lock;
2585 match channel_state.by_id.entry(msg.channel_id) {
2586 hash_map::Entry::Occupied(mut chan) => {
2587 if chan.get().get_their_node_id() != *their_node_id {
2588 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2590 try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2592 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2595 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2599 fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2600 let mut channel_lock = self.channel_state.lock().unwrap();
2601 let channel_state = &mut *channel_lock;
2602 match channel_state.by_id.entry(msg.channel_id) {
2603 hash_map::Entry::Occupied(mut chan) => {
2604 if chan.get().get_their_node_id() != *their_node_id {
2605 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2607 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::LightningError { err: msg.reason.clone() }), channel_state, chan);
2609 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2614 fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2615 let mut channel_lock = self.channel_state.lock().unwrap();
2616 let channel_state = &mut *channel_lock;
2617 match channel_state.by_id.entry(msg.channel_id) {
2618 hash_map::Entry::Occupied(mut chan) => {
2619 if chan.get().get_their_node_id() != *their_node_id {
2620 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2622 if (msg.failure_code & 0x8000) == 0 {
2623 let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
2624 try_chan_entry!(self, Err(chan_err), channel_state, chan);
2626 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);
2629 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2633 fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2634 let mut channel_state_lock = self.channel_state.lock().unwrap();
2635 let channel_state = &mut *channel_state_lock;
2636 match channel_state.by_id.entry(msg.channel_id) {
2637 hash_map::Entry::Occupied(mut chan) => {
2638 if chan.get().get_their_node_id() != *their_node_id {
2639 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2641 let (revoke_and_ack, commitment_signed, closing_signed, monitor_update) =
2642 match chan.get_mut().commitment_signed(&msg, &self.fee_estimator, &self.logger) {
2643 Err((None, e)) => try_chan_entry!(self, Err(e), channel_state, chan),
2644 Err((Some(update), e)) => {
2645 assert!(chan.get().is_awaiting_monitor_update());
2646 let _ = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), update);
2647 try_chan_entry!(self, Err(e), channel_state, chan);
2652 if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) {
2653 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some());
2654 //TODO: Rebroadcast closing_signed if present on monitor update restoration
2656 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2657 node_id: their_node_id.clone(),
2658 msg: revoke_and_ack,
2660 if let Some(msg) = commitment_signed {
2661 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2662 node_id: their_node_id.clone(),
2663 updates: msgs::CommitmentUpdate {
2664 update_add_htlcs: Vec::new(),
2665 update_fulfill_htlcs: Vec::new(),
2666 update_fail_htlcs: Vec::new(),
2667 update_fail_malformed_htlcs: Vec::new(),
2669 commitment_signed: msg,
2673 if let Some(msg) = closing_signed {
2674 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2675 node_id: their_node_id.clone(),
2681 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2686 fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingHTLCInfo, u64)>)]) {
2687 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2688 let mut forward_event = None;
2689 if !pending_forwards.is_empty() {
2690 let mut channel_state = self.channel_state.lock().unwrap();
2691 if channel_state.forward_htlcs.is_empty() {
2692 forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS))
2694 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2695 match channel_state.forward_htlcs.entry(match forward_info.routing {
2696 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
2697 PendingHTLCRouting::Receive { .. } => 0,
2699 hash_map::Entry::Occupied(mut entry) => {
2700 entry.get_mut().push(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info });
2702 hash_map::Entry::Vacant(entry) => {
2703 entry.insert(vec!(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info }));
2708 match forward_event {
2710 let mut pending_events = self.pending_events.lock().unwrap();
2711 pending_events.push(events::Event::PendingHTLCsForwardable {
2712 time_forwardable: time
2720 fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2721 let mut htlcs_to_fail = Vec::new();
2723 let mut channel_state_lock = self.channel_state.lock().unwrap();
2724 let channel_state = &mut *channel_state_lock;
2725 match channel_state.by_id.entry(msg.channel_id) {
2726 hash_map::Entry::Occupied(mut chan) => {
2727 if chan.get().get_their_node_id() != *their_node_id {
2728 break Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2730 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2731 let (commitment_update, pending_forwards, pending_failures, closing_signed, monitor_update, htlcs_to_fail_in) =
2732 break_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &self.fee_estimator, &self.logger), channel_state, chan);
2733 htlcs_to_fail = htlcs_to_fail_in;
2734 if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) {
2735 if was_frozen_for_monitor {
2736 assert!(commitment_update.is_none() && closing_signed.is_none() && pending_forwards.is_empty() && pending_failures.is_empty());
2737 break Err(MsgHandleErrInternal::ignore_no_close("Previous monitor update failure prevented responses to RAA".to_owned()));
2739 if let Err(e) = handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, commitment_update.is_some(), pending_forwards, pending_failures) {
2741 } else { unreachable!(); }
2744 if let Some(updates) = commitment_update {
2745 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2746 node_id: their_node_id.clone(),
2750 if let Some(msg) = closing_signed {
2751 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2752 node_id: their_node_id.clone(),
2756 break Ok((pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel")))
2758 hash_map::Entry::Vacant(_) => break Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2761 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id);
2763 Ok((pending_forwards, mut pending_failures, short_channel_id)) => {
2764 for failure in pending_failures.drain(..) {
2765 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2767 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2774 fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2775 let mut channel_lock = self.channel_state.lock().unwrap();
2776 let channel_state = &mut *channel_lock;
2777 match channel_state.by_id.entry(msg.channel_id) {
2778 hash_map::Entry::Occupied(mut chan) => {
2779 if chan.get().get_their_node_id() != *their_node_id {
2780 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2782 try_chan_entry!(self, chan.get_mut().update_fee(&self.fee_estimator, &msg), channel_state, chan);
2784 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2789 fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2790 let mut channel_state_lock = self.channel_state.lock().unwrap();
2791 let channel_state = &mut *channel_state_lock;
2793 match channel_state.by_id.entry(msg.channel_id) {
2794 hash_map::Entry::Occupied(mut chan) => {
2795 if chan.get().get_their_node_id() != *their_node_id {
2796 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2798 if !chan.get().is_usable() {
2799 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
2802 let our_node_id = self.get_our_node_id();
2803 let (announcement, our_bitcoin_sig) =
2804 try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2806 let were_node_one = announcement.node_id_1 == our_node_id;
2807 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
2809 let their_node_key = if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 };
2810 let their_bitcoin_key = if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 };
2811 match (self.secp_ctx.verify(&msghash, &msg.node_signature, their_node_key),
2812 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, their_bitcoin_key)) {
2814 let chan_err: ChannelError = ChannelError::Close(format!("Bad announcement_signatures. Failed to verify node_signature: {:?}. Maybe using different node_secret for transport and routing msg? UnsignedChannelAnnouncement used for verification is {:?}. their_node_key is {:?}", e, &announcement, their_node_key));
2815 try_chan_entry!(self, Err(chan_err), channel_state, chan);
2818 let chan_err: ChannelError = ChannelError::Close(format!("Bad announcement_signatures. Failed to verify bitcoin_signature: {:?}. UnsignedChannelAnnouncement used for verification is {:?}. their_bitcoin_key is ({:?})", e, &announcement, their_bitcoin_key));
2819 try_chan_entry!(self, Err(chan_err), channel_state, chan);
2825 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2827 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2828 msg: msgs::ChannelAnnouncement {
2829 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2830 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2831 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2832 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2833 contents: announcement,
2835 update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2838 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2843 fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2844 let mut channel_state_lock = self.channel_state.lock().unwrap();
2845 let channel_state = &mut *channel_state_lock;
2847 match channel_state.by_id.entry(msg.channel_id) {
2848 hash_map::Entry::Occupied(mut chan) => {
2849 if chan.get().get_their_node_id() != *their_node_id {
2850 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2852 // Currently, we expect all holding cell update_adds to be dropped on peer
2853 // disconnect, so Channel's reestablish will never hand us any holding cell
2854 // freed HTLCs to fail backwards. If in the future we no longer drop pending
2855 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
2856 let (funding_locked, revoke_and_ack, commitment_update, monitor_update_opt, mut order, shutdown) =
2857 try_chan_entry!(self, chan.get_mut().channel_reestablish(msg, &self.logger), channel_state, chan);
2858 if let Some(monitor_update) = monitor_update_opt {
2859 if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) {
2860 // channel_reestablish doesn't guarantee the order it returns is sensical
2861 // for the messages it returns, but if we're setting what messages to
2862 // re-transmit on monitor update success, we need to make sure it is sane.
2863 if revoke_and_ack.is_none() {
2864 order = RAACommitmentOrder::CommitmentFirst;
2866 if commitment_update.is_none() {
2867 order = RAACommitmentOrder::RevokeAndACKFirst;
2869 return_monitor_err!(self, e, channel_state, chan, order, revoke_and_ack.is_some(), commitment_update.is_some());
2870 //TODO: Resend the funding_locked if needed once we get the monitor running again
2873 if let Some(msg) = funding_locked {
2874 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2875 node_id: their_node_id.clone(),
2879 macro_rules! send_raa { () => {
2880 if let Some(msg) = revoke_and_ack {
2881 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2882 node_id: their_node_id.clone(),
2887 macro_rules! send_cu { () => {
2888 if let Some(updates) = commitment_update {
2889 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2890 node_id: their_node_id.clone(),
2896 RAACommitmentOrder::RevokeAndACKFirst => {
2900 RAACommitmentOrder::CommitmentFirst => {
2905 if let Some(msg) = shutdown {
2906 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2907 node_id: their_node_id.clone(),
2913 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2917 /// Begin Update fee process. Allowed only on an outbound channel.
2918 /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2919 /// PeerManager::process_events afterwards.
2920 /// Note: This API is likely to change!
2922 pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u32) -> Result<(), APIError> {
2923 let _ = self.total_consistency_lock.read().unwrap();
2925 let err: Result<(), _> = loop {
2926 let mut channel_state_lock = self.channel_state.lock().unwrap();
2927 let channel_state = &mut *channel_state_lock;
2929 match channel_state.by_id.entry(channel_id) {
2930 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: format!("Failed to find corresponding channel for id {}", channel_id.to_hex())}),
2931 hash_map::Entry::Occupied(mut chan) => {
2932 if !chan.get().is_outbound() {
2933 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel".to_owned()});
2935 if chan.get().is_awaiting_monitor_update() {
2936 return Err(APIError::MonitorUpdateFailed);
2938 if !chan.get().is_live() {
2939 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected".to_owned()});
2941 their_node_id = chan.get().get_their_node_id();
2942 if let Some((update_fee, commitment_signed, monitor_update)) =
2943 break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw, &self.logger), channel_state, chan)
2945 if let Err(_e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) {
2948 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2949 node_id: chan.get().get_their_node_id(),
2950 updates: msgs::CommitmentUpdate {
2951 update_add_htlcs: Vec::new(),
2952 update_fulfill_htlcs: Vec::new(),
2953 update_fail_htlcs: Vec::new(),
2954 update_fail_malformed_htlcs: Vec::new(),
2955 update_fee: Some(update_fee),
2965 match handle_error!(self, err, their_node_id) {
2966 Ok(_) => unreachable!(),
2967 Err(e) => { Err(APIError::APIMisuseError { err: e.err })}
2971 /// Process pending events from the ManyChannelMonitor.
2972 fn process_pending_monitor_events(&self) {
2973 let mut failed_channels = Vec::new();
2975 for monitor_event in self.monitor.get_and_clear_pending_monitor_events() {
2976 match monitor_event {
2977 MonitorEvent::HTLCEvent(htlc_update) => {
2978 if let Some(preimage) = htlc_update.payment_preimage {
2979 log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2980 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2982 log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2983 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() });
2986 MonitorEvent::CommitmentTxBroadcasted(funding_outpoint) => {
2987 let mut channel_lock = self.channel_state.lock().unwrap();
2988 let channel_state = &mut *channel_lock;
2989 let by_id = &mut channel_state.by_id;
2990 let short_to_id = &mut channel_state.short_to_id;
2991 let pending_msg_events = &mut channel_state.pending_msg_events;
2992 if let Some(mut chan) = by_id.remove(&funding_outpoint.to_channel_id()) {
2993 if let Some(short_id) = chan.get_short_channel_id() {
2994 short_to_id.remove(&short_id);
2996 failed_channels.push(chan.force_shutdown(false));
2997 if let Ok(update) = self.get_channel_update(&chan) {
2998 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3008 for failure in failed_channels.drain(..) {
3009 self.finish_force_close_channel(failure);
3014 impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> events::MessageSendEventsProvider for ChannelManager<ChanSigner, M, T, K, F, L>
3015 where M::Target: ManyChannelMonitor<Keys=ChanSigner>,
3016 T::Target: BroadcasterInterface,
3017 K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
3018 F::Target: FeeEstimator,
3021 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
3022 //TODO: This behavior should be documented. It's non-intuitive that we query
3023 // ChannelMonitors when clearing other events.
3024 self.process_pending_monitor_events();
3026 let mut ret = Vec::new();
3027 let mut channel_state = self.channel_state.lock().unwrap();
3028 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
3033 impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> events::EventsProvider for ChannelManager<ChanSigner, M, T, K, F, L>
3034 where M::Target: ManyChannelMonitor<Keys=ChanSigner>,
3035 T::Target: BroadcasterInterface,
3036 K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
3037 F::Target: FeeEstimator,
3040 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
3041 //TODO: This behavior should be documented. It's non-intuitive that we query
3042 // ChannelMonitors when clearing other events.
3043 self.process_pending_monitor_events();
3045 let mut ret = Vec::new();
3046 let mut pending_events = self.pending_events.lock().unwrap();
3047 mem::swap(&mut ret, &mut *pending_events);
3052 impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send>
3053 ChainListener for ChannelManager<ChanSigner, M, T, K, F, L>
3054 where M::Target: ManyChannelMonitor<Keys=ChanSigner>,
3055 T::Target: BroadcasterInterface,
3056 K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
3057 F::Target: FeeEstimator,
3060 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[usize]) {
3061 let header_hash = header.bitcoin_hash();
3062 log_trace!(self.logger, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
3063 let _ = self.total_consistency_lock.read().unwrap();
3064 let mut failed_channels = Vec::new();
3065 let mut timed_out_htlcs = Vec::new();
3067 let mut channel_lock = self.channel_state.lock().unwrap();
3068 let channel_state = &mut *channel_lock;
3069 let short_to_id = &mut channel_state.short_to_id;
3070 let pending_msg_events = &mut channel_state.pending_msg_events;
3071 channel_state.by_id.retain(|_, channel| {
3072 let res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
3073 if let Ok((chan_res, mut timed_out_pending_htlcs)) = res {
3074 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
3075 let chan_update = self.get_channel_update(&channel).map(|u| u.encode_with_len()).unwrap(); // Cannot add/recv HTLCs before we have a short_id so unwrap is safe
3076 timed_out_htlcs.push((source, payment_hash, HTLCFailReason::Reason {
3077 failure_code: 0x1000 | 14, // expiry_too_soon, or at least it is now
3081 if let Some(funding_locked) = chan_res {
3082 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
3083 node_id: channel.get_their_node_id(),
3084 msg: funding_locked,
3086 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
3087 log_trace!(self.logger, "Sending funding_locked and announcement_signatures for {}", log_bytes!(channel.channel_id()));
3088 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
3089 node_id: channel.get_their_node_id(),
3090 msg: announcement_sigs,
3093 log_trace!(self.logger, "Sending funding_locked WITHOUT announcement_signatures for {}", log_bytes!(channel.channel_id()));
3095 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
3097 } else if let Err(e) = res {
3098 pending_msg_events.push(events::MessageSendEvent::HandleError {
3099 node_id: channel.get_their_node_id(),
3100 action: msgs::ErrorAction::SendErrorMessage { msg: e },
3104 if let Some(funding_txo) = channel.get_funding_txo() {
3105 for tx in txn_matched {
3106 for inp in tx.input.iter() {
3107 if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
3108 log_trace!(self.logger, "Detected channel-closing tx {} spending {}:{}, closing channel {}", tx.txid(), inp.previous_output.txid, inp.previous_output.vout, log_bytes!(channel.channel_id()));
3109 if let Some(short_id) = channel.get_short_channel_id() {
3110 short_to_id.remove(&short_id);
3112 // It looks like our counterparty went on-chain. We go ahead and
3113 // broadcast our latest local state as well here, just in case its
3114 // some kind of SPV attack, though we expect these to be dropped.
3115 failed_channels.push(channel.force_shutdown(true));
3116 if let Ok(update) = self.get_channel_update(&channel) {
3117 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3129 channel_state.claimable_htlcs.retain(|&(ref payment_hash, _), htlcs| {
3130 htlcs.retain(|htlc| {
3131 // If height is approaching the number of blocks we think it takes us to get
3132 // our commitment transaction confirmed before the HTLC expires, plus the
3133 // number of blocks we generally consider it to take to do a commitment update,
3134 // just give up on it and fail the HTLC.
3135 if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
3136 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
3137 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(height));
3138 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(), HTLCFailReason::Reason {
3139 failure_code: 0x4000 | 15,
3140 data: htlc_msat_height_data
3145 !htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
3148 for failure in failed_channels.drain(..) {
3149 self.finish_force_close_channel(failure);
3152 for (source, payment_hash, reason) in timed_out_htlcs.drain(..) {
3153 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, reason);
3155 self.latest_block_height.store(height as usize, Ordering::Release);
3156 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
3158 // Update last_node_announcement_serial to be the max of its current value and the
3159 // block timestamp. This should keep us close to the current time without relying on
3160 // having an explicit local time source.
3161 // Just in case we end up in a race, we loop until we either successfully update
3162 // last_node_announcement_serial or decide we don't need to.
3163 let old_serial = self.last_node_announcement_serial.load(Ordering::Acquire);
3164 if old_serial >= header.time as usize { break; }
3165 if self.last_node_announcement_serial.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
3171 /// We force-close the channel without letting our counterparty participate in the shutdown
3172 fn block_disconnected(&self, header: &BlockHeader, _: u32) {
3173 let _ = self.total_consistency_lock.read().unwrap();
3174 let mut failed_channels = Vec::new();
3176 let mut channel_lock = self.channel_state.lock().unwrap();
3177 let channel_state = &mut *channel_lock;
3178 let short_to_id = &mut channel_state.short_to_id;
3179 let pending_msg_events = &mut channel_state.pending_msg_events;
3180 channel_state.by_id.retain(|_, v| {
3181 if v.block_disconnected(header) {
3182 if let Some(short_id) = v.get_short_channel_id() {
3183 short_to_id.remove(&short_id);
3185 failed_channels.push(v.force_shutdown(true));
3186 if let Ok(update) = self.get_channel_update(&v) {
3187 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3197 for failure in failed_channels.drain(..) {
3198 self.finish_force_close_channel(failure);
3200 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
3201 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
3205 impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send>
3206 ChannelMessageHandler for ChannelManager<ChanSigner, M, T, K, F, L>
3207 where M::Target: ManyChannelMonitor<Keys=ChanSigner>,
3208 T::Target: BroadcasterInterface,
3209 K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
3210 F::Target: FeeEstimator,
3213 fn handle_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) {
3214 let _ = self.total_consistency_lock.read().unwrap();
3215 let _ = handle_error!(self, self.internal_open_channel(their_node_id, their_features, msg), *their_node_id);
3218 fn handle_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) {
3219 let _ = self.total_consistency_lock.read().unwrap();
3220 let _ = handle_error!(self, self.internal_accept_channel(their_node_id, their_features, msg), *their_node_id);
3223 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
3224 let _ = self.total_consistency_lock.read().unwrap();
3225 let _ = handle_error!(self, self.internal_funding_created(their_node_id, msg), *their_node_id);
3228 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
3229 let _ = self.total_consistency_lock.read().unwrap();
3230 let _ = handle_error!(self, self.internal_funding_signed(their_node_id, msg), *their_node_id);
3233 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) {
3234 let _ = self.total_consistency_lock.read().unwrap();
3235 let _ = handle_error!(self, self.internal_funding_locked(their_node_id, msg), *their_node_id);
3238 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) {
3239 let _ = self.total_consistency_lock.read().unwrap();
3240 let _ = handle_error!(self, self.internal_shutdown(their_node_id, msg), *their_node_id);
3243 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
3244 let _ = self.total_consistency_lock.read().unwrap();
3245 let _ = handle_error!(self, self.internal_closing_signed(their_node_id, msg), *their_node_id);
3248 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
3249 let _ = self.total_consistency_lock.read().unwrap();
3250 let _ = handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), *their_node_id);
3253 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
3254 let _ = self.total_consistency_lock.read().unwrap();
3255 let _ = handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), *their_node_id);
3258 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
3259 let _ = self.total_consistency_lock.read().unwrap();
3260 let _ = handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), *their_node_id);
3263 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
3264 let _ = self.total_consistency_lock.read().unwrap();
3265 let _ = handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), *their_node_id);
3268 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
3269 let _ = self.total_consistency_lock.read().unwrap();
3270 let _ = handle_error!(self, self.internal_commitment_signed(their_node_id, msg), *their_node_id);
3273 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
3274 let _ = self.total_consistency_lock.read().unwrap();
3275 let _ = handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), *their_node_id);
3278 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
3279 let _ = self.total_consistency_lock.read().unwrap();
3280 let _ = handle_error!(self, self.internal_update_fee(their_node_id, msg), *their_node_id);
3283 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
3284 let _ = self.total_consistency_lock.read().unwrap();
3285 let _ = handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), *their_node_id);
3288 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
3289 let _ = self.total_consistency_lock.read().unwrap();
3290 let _ = handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), *their_node_id);
3293 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
3294 let _ = self.total_consistency_lock.read().unwrap();
3295 let mut failed_channels = Vec::new();
3296 let mut failed_payments = Vec::new();
3297 let mut no_channels_remain = true;
3299 let mut channel_state_lock = self.channel_state.lock().unwrap();
3300 let channel_state = &mut *channel_state_lock;
3301 let short_to_id = &mut channel_state.short_to_id;
3302 let pending_msg_events = &mut channel_state.pending_msg_events;
3303 if no_connection_possible {
3304 log_debug!(self.logger, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
3305 channel_state.by_id.retain(|_, chan| {
3306 if chan.get_their_node_id() == *their_node_id {
3307 if let Some(short_id) = chan.get_short_channel_id() {
3308 short_to_id.remove(&short_id);
3310 failed_channels.push(chan.force_shutdown(true));
3311 if let Ok(update) = self.get_channel_update(&chan) {
3312 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3322 log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
3323 channel_state.by_id.retain(|_, chan| {
3324 if chan.get_their_node_id() == *their_node_id {
3325 // Note that currently on channel reestablish we assert that there are no
3326 // holding cell add-HTLCs, so if in the future we stop removing uncommitted HTLCs
3327 // on peer disconnect here, there will need to be corresponding changes in
3328 // reestablish logic.
3329 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger);
3330 chan.to_disabled_marked();
3331 if !failed_adds.is_empty() {
3332 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
3333 failed_payments.push((chan_update, failed_adds));
3335 if chan.is_shutdown() {
3336 if let Some(short_id) = chan.get_short_channel_id() {
3337 short_to_id.remove(&short_id);
3341 no_channels_remain = false;
3347 pending_msg_events.retain(|msg| {
3349 &events::MessageSendEvent::SendAcceptChannel { ref node_id, .. } => node_id != their_node_id,
3350 &events::MessageSendEvent::SendOpenChannel { ref node_id, .. } => node_id != their_node_id,
3351 &events::MessageSendEvent::SendFundingCreated { ref node_id, .. } => node_id != their_node_id,
3352 &events::MessageSendEvent::SendFundingSigned { ref node_id, .. } => node_id != their_node_id,
3353 &events::MessageSendEvent::SendFundingLocked { ref node_id, .. } => node_id != their_node_id,
3354 &events::MessageSendEvent::SendAnnouncementSignatures { ref node_id, .. } => node_id != their_node_id,
3355 &events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => node_id != their_node_id,
3356 &events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => node_id != their_node_id,
3357 &events::MessageSendEvent::SendClosingSigned { ref node_id, .. } => node_id != their_node_id,
3358 &events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != their_node_id,
3359 &events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != their_node_id,
3360 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
3361 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
3362 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
3363 &events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != their_node_id,
3364 &events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
3368 if no_channels_remain {
3369 self.per_peer_state.write().unwrap().remove(their_node_id);
3372 for failure in failed_channels.drain(..) {
3373 self.finish_force_close_channel(failure);
3375 for (chan_update, mut htlc_sources) in failed_payments {
3376 for (htlc_source, payment_hash) in htlc_sources.drain(..) {
3377 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
3382 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init) {
3383 log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
3385 let _ = self.total_consistency_lock.read().unwrap();
3388 let mut peer_state_lock = self.per_peer_state.write().unwrap();
3389 match peer_state_lock.entry(their_node_id.clone()) {
3390 hash_map::Entry::Vacant(e) => {
3391 e.insert(Mutex::new(PeerState {
3392 latest_features: init_msg.features.clone(),
3395 hash_map::Entry::Occupied(e) => {
3396 e.get().lock().unwrap().latest_features = init_msg.features.clone();
3401 let mut channel_state_lock = self.channel_state.lock().unwrap();
3402 let channel_state = &mut *channel_state_lock;
3403 let pending_msg_events = &mut channel_state.pending_msg_events;
3404 channel_state.by_id.retain(|_, chan| {
3405 if chan.get_their_node_id() == *their_node_id {
3406 if !chan.have_received_message() {
3407 // If we created this (outbound) channel while we were disconnected from the
3408 // peer we probably failed to send the open_channel message, which is now
3409 // lost. We can't have had anything pending related to this channel, so we just
3413 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
3414 node_id: chan.get_their_node_id(),
3415 msg: chan.get_channel_reestablish(&self.logger),
3421 //TODO: Also re-broadcast announcement_signatures
3424 fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
3425 let _ = self.total_consistency_lock.read().unwrap();
3427 if msg.channel_id == [0; 32] {
3428 for chan in self.list_channels() {
3429 if chan.remote_network_id == *their_node_id {
3430 self.force_close_channel(&chan.channel_id);
3434 self.force_close_channel(&msg.channel_id);
3439 const SERIALIZATION_VERSION: u8 = 1;
3440 const MIN_SERIALIZATION_VERSION: u8 = 1;
3442 impl Writeable for PendingHTLCInfo {
3443 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3444 match &self.routing {
3445 &PendingHTLCRouting::Forward { ref onion_packet, ref short_channel_id } => {
3447 onion_packet.write(writer)?;
3448 short_channel_id.write(writer)?;
3450 &PendingHTLCRouting::Receive { ref payment_data, ref incoming_cltv_expiry } => {
3452 payment_data.write(writer)?;
3453 incoming_cltv_expiry.write(writer)?;
3456 self.incoming_shared_secret.write(writer)?;
3457 self.payment_hash.write(writer)?;
3458 self.amt_to_forward.write(writer)?;
3459 self.outgoing_cltv_value.write(writer)?;
3464 impl Readable for PendingHTLCInfo {
3465 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<PendingHTLCInfo, DecodeError> {
3466 Ok(PendingHTLCInfo {
3467 routing: match Readable::read(reader)? {
3468 0u8 => PendingHTLCRouting::Forward {
3469 onion_packet: Readable::read(reader)?,
3470 short_channel_id: Readable::read(reader)?,
3472 1u8 => PendingHTLCRouting::Receive {
3473 payment_data: Readable::read(reader)?,
3474 incoming_cltv_expiry: Readable::read(reader)?,
3476 _ => return Err(DecodeError::InvalidValue),
3478 incoming_shared_secret: Readable::read(reader)?,
3479 payment_hash: Readable::read(reader)?,
3480 amt_to_forward: Readable::read(reader)?,
3481 outgoing_cltv_value: Readable::read(reader)?,
3486 impl Writeable for HTLCFailureMsg {
3487 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3489 &HTLCFailureMsg::Relay(ref fail_msg) => {
3491 fail_msg.write(writer)?;
3493 &HTLCFailureMsg::Malformed(ref fail_msg) => {
3495 fail_msg.write(writer)?;
3502 impl Readable for HTLCFailureMsg {
3503 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3504 match <u8 as Readable>::read(reader)? {
3505 0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3506 1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3507 _ => Err(DecodeError::InvalidValue),
3512 impl Writeable for PendingHTLCStatus {
3513 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3515 &PendingHTLCStatus::Forward(ref forward_info) => {
3517 forward_info.write(writer)?;
3519 &PendingHTLCStatus::Fail(ref fail_msg) => {
3521 fail_msg.write(writer)?;
3528 impl Readable for PendingHTLCStatus {
3529 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3530 match <u8 as Readable>::read(reader)? {
3531 0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3532 1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3533 _ => Err(DecodeError::InvalidValue),
3538 impl_writeable!(HTLCPreviousHopData, 0, {
3541 incoming_packet_shared_secret
3544 impl_writeable!(ClaimableHTLC, 0, {
3551 impl Writeable for HTLCSource {
3552 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3554 &HTLCSource::PreviousHopData(ref hop_data) => {
3556 hop_data.write(writer)?;
3558 &HTLCSource::OutboundRoute { ref path, ref session_priv, ref first_hop_htlc_msat } => {
3560 path.write(writer)?;
3561 session_priv.write(writer)?;
3562 first_hop_htlc_msat.write(writer)?;
3569 impl Readable for HTLCSource {
3570 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3571 match <u8 as Readable>::read(reader)? {
3572 0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3573 1 => Ok(HTLCSource::OutboundRoute {
3574 path: Readable::read(reader)?,
3575 session_priv: Readable::read(reader)?,
3576 first_hop_htlc_msat: Readable::read(reader)?,
3578 _ => Err(DecodeError::InvalidValue),
3583 impl Writeable for HTLCFailReason {
3584 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3586 &HTLCFailReason::LightningError { ref err } => {
3590 &HTLCFailReason::Reason { ref failure_code, ref data } => {
3592 failure_code.write(writer)?;
3593 data.write(writer)?;
3600 impl Readable for HTLCFailReason {
3601 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3602 match <u8 as Readable>::read(reader)? {
3603 0 => Ok(HTLCFailReason::LightningError { err: Readable::read(reader)? }),
3604 1 => Ok(HTLCFailReason::Reason {
3605 failure_code: Readable::read(reader)?,
3606 data: Readable::read(reader)?,
3608 _ => Err(DecodeError::InvalidValue),
3613 impl Writeable for HTLCForwardInfo {
3614 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3616 &HTLCForwardInfo::AddHTLC { ref prev_short_channel_id, ref prev_htlc_id, ref forward_info } => {
3618 prev_short_channel_id.write(writer)?;
3619 prev_htlc_id.write(writer)?;
3620 forward_info.write(writer)?;
3622 &HTLCForwardInfo::FailHTLC { ref htlc_id, ref err_packet } => {
3624 htlc_id.write(writer)?;
3625 err_packet.write(writer)?;
3632 impl Readable for HTLCForwardInfo {
3633 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCForwardInfo, DecodeError> {
3634 match <u8 as Readable>::read(reader)? {
3635 0 => Ok(HTLCForwardInfo::AddHTLC {
3636 prev_short_channel_id: Readable::read(reader)?,
3637 prev_htlc_id: Readable::read(reader)?,
3638 forward_info: Readable::read(reader)?,
3640 1 => Ok(HTLCForwardInfo::FailHTLC {
3641 htlc_id: Readable::read(reader)?,
3642 err_packet: Readable::read(reader)?,
3644 _ => Err(DecodeError::InvalidValue),
3649 impl<ChanSigner: ChannelKeys + Writeable, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable for ChannelManager<ChanSigner, M, T, K, F, L>
3650 where M::Target: ManyChannelMonitor<Keys=ChanSigner>,
3651 T::Target: BroadcasterInterface,
3652 K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
3653 F::Target: FeeEstimator,
3656 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3657 let _ = self.total_consistency_lock.write().unwrap();
3659 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3660 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3662 self.genesis_hash.write(writer)?;
3663 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3664 self.last_block_hash.lock().unwrap().write(writer)?;
3666 let channel_state = self.channel_state.lock().unwrap();
3667 let mut unfunded_channels = 0;
3668 for (_, channel) in channel_state.by_id.iter() {
3669 if !channel.is_funding_initiated() {
3670 unfunded_channels += 1;
3673 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3674 for (_, channel) in channel_state.by_id.iter() {
3675 if channel.is_funding_initiated() {
3676 channel.write(writer)?;
3680 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3681 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3682 short_channel_id.write(writer)?;
3683 (pending_forwards.len() as u64).write(writer)?;
3684 for forward in pending_forwards {
3685 forward.write(writer)?;
3689 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3690 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3691 payment_hash.write(writer)?;
3692 (previous_hops.len() as u64).write(writer)?;
3693 for htlc in previous_hops.iter() {
3694 htlc.write(writer)?;
3698 let per_peer_state = self.per_peer_state.write().unwrap();
3699 (per_peer_state.len() as u64).write(writer)?;
3700 for (peer_pubkey, peer_state_mutex) in per_peer_state.iter() {
3701 peer_pubkey.write(writer)?;
3702 let peer_state = peer_state_mutex.lock().unwrap();
3703 peer_state.latest_features.write(writer)?;
3706 let events = self.pending_events.lock().unwrap();
3707 (events.len() as u64).write(writer)?;
3708 for event in events.iter() {
3709 event.write(writer)?;
3712 (self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
3718 /// Arguments for the creation of a ChannelManager that are not deserialized.
3720 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3722 /// 1) Deserialize all stored ChannelMonitors.
3723 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3724 /// ChannelManager)>::read(reader, args).
3725 /// This may result in closing some Channels if the ChannelMonitor is newer than the stored
3726 /// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3727 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3728 /// ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3729 /// 4) Reconnect blocks on your ChannelMonitors.
3730 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3731 /// 6) Disconnect/connect blocks on the ChannelManager.
3732 /// 7) Register the new ChannelManager with your ChainWatchInterface.
3733 pub struct ChannelManagerReadArgs<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
3734 where M::Target: ManyChannelMonitor<Keys=ChanSigner>,
3735 T::Target: BroadcasterInterface,
3736 K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
3737 F::Target: FeeEstimator,
3741 /// The keys provider which will give us relevant keys. Some keys will be loaded during
3742 /// deserialization.
3743 pub keys_manager: K,
3745 /// The fee_estimator for use in the ChannelManager in the future.
3747 /// No calls to the FeeEstimator will be made during deserialization.
3748 pub fee_estimator: F,
3749 /// The ManyChannelMonitor for use in the ChannelManager in the future.
3751 /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3752 /// you have deserialized ChannelMonitors separately and will add them to your
3753 /// ManyChannelMonitor after deserializing this ChannelManager.
3756 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3757 /// used to broadcast the latest local commitment transactions of channels which must be
3758 /// force-closed during deserialization.
3759 pub tx_broadcaster: T,
3760 /// The Logger for use in the ChannelManager and which may be used to log information during
3761 /// deserialization.
3763 /// Default settings used for new channels. Any existing channels will continue to use the
3764 /// runtime settings which were stored when the ChannelManager was serialized.
3765 pub default_config: UserConfig,
3767 /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3768 /// value.get_funding_txo() should be the key).
3770 /// If a monitor is inconsistent with the channel state during deserialization the channel will
3771 /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
3772 /// is true for missing channels as well. If there is a monitor missing for which we find
3773 /// channel data Err(DecodeError::InvalidValue) will be returned.
3775 /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3777 pub channel_monitors: &'a mut HashMap<OutPoint, &'a mut ChannelMonitor<ChanSigner>>,
3780 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
3781 // SipmleArcChannelManager type:
3782 impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
3783 ReadableArgs<ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>> for (BlockHash, Arc<ChannelManager<ChanSigner, M, T, K, F, L>>)
3784 where M::Target: ManyChannelMonitor<Keys=ChanSigner>,
3785 T::Target: BroadcasterInterface,
3786 K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
3787 F::Target: FeeEstimator,
3790 fn read<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>) -> Result<Self, DecodeError> {
3791 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<ChanSigner, M, T, K, F, L>)>::read(reader, args)?;
3792 Ok((blockhash, Arc::new(chan_manager)))
3796 impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
3797 ReadableArgs<ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>> for (BlockHash, ChannelManager<ChanSigner, M, T, K, F, L>)
3798 where M::Target: ManyChannelMonitor<Keys=ChanSigner>,
3799 T::Target: BroadcasterInterface,
3800 K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
3801 F::Target: FeeEstimator,
3804 fn read<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>) -> Result<Self, DecodeError> {
3805 let _ver: u8 = Readable::read(reader)?;
3806 let min_ver: u8 = Readable::read(reader)?;
3807 if min_ver > SERIALIZATION_VERSION {
3808 return Err(DecodeError::UnknownVersion);
3811 let genesis_hash: BlockHash = Readable::read(reader)?;
3812 let latest_block_height: u32 = Readable::read(reader)?;
3813 let last_block_hash: BlockHash = Readable::read(reader)?;
3815 let mut failed_htlcs = Vec::new();
3817 let channel_count: u64 = Readable::read(reader)?;
3818 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3819 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3820 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3821 for _ in 0..channel_count {
3822 let mut channel: Channel<ChanSigner> = Readable::read(reader)?;
3823 if channel.last_block_connected != Default::default() && channel.last_block_connected != last_block_hash {
3824 return Err(DecodeError::InvalidValue);
3827 let funding_txo = channel.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3828 funding_txo_set.insert(funding_txo.clone());
3829 if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
3830 if channel.get_cur_local_commitment_transaction_number() < monitor.get_cur_local_commitment_number() ||
3831 channel.get_revoked_remote_commitment_transaction_number() < monitor.get_min_seen_secret() ||
3832 channel.get_cur_remote_commitment_transaction_number() < monitor.get_cur_remote_commitment_number() ||
3833 channel.get_latest_monitor_update_id() > monitor.get_latest_update_id() {
3834 // If the channel is ahead of the monitor, return InvalidValue:
3835 return Err(DecodeError::InvalidValue);
3836 } else if channel.get_cur_local_commitment_transaction_number() > monitor.get_cur_local_commitment_number() ||
3837 channel.get_revoked_remote_commitment_transaction_number() > monitor.get_min_seen_secret() ||
3838 channel.get_cur_remote_commitment_transaction_number() > monitor.get_cur_remote_commitment_number() ||
3839 channel.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
3840 // But if the channel is behind of the monitor, close the channel:
3841 let (_, _, mut new_failed_htlcs) = channel.force_shutdown(true);
3842 failed_htlcs.append(&mut new_failed_htlcs);
3843 monitor.broadcast_latest_local_commitment_txn(&args.tx_broadcaster, &args.logger);
3845 if let Some(short_channel_id) = channel.get_short_channel_id() {
3846 short_to_id.insert(short_channel_id, channel.channel_id());
3848 by_id.insert(channel.channel_id(), channel);
3851 return Err(DecodeError::InvalidValue);
3855 for (ref funding_txo, ref mut monitor) in args.channel_monitors.iter_mut() {
3856 if !funding_txo_set.contains(funding_txo) {
3857 monitor.broadcast_latest_local_commitment_txn(&args.tx_broadcaster, &args.logger);
3861 const MAX_ALLOC_SIZE: usize = 1024 * 64;
3862 let forward_htlcs_count: u64 = Readable::read(reader)?;
3863 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3864 for _ in 0..forward_htlcs_count {
3865 let short_channel_id = Readable::read(reader)?;
3866 let pending_forwards_count: u64 = Readable::read(reader)?;
3867 let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
3868 for _ in 0..pending_forwards_count {
3869 pending_forwards.push(Readable::read(reader)?);
3871 forward_htlcs.insert(short_channel_id, pending_forwards);
3874 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3875 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3876 for _ in 0..claimable_htlcs_count {
3877 let payment_hash = Readable::read(reader)?;
3878 let previous_hops_len: u64 = Readable::read(reader)?;
3879 let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
3880 for _ in 0..previous_hops_len {
3881 previous_hops.push(Readable::read(reader)?);
3883 claimable_htlcs.insert(payment_hash, previous_hops);
3886 let peer_count: u64 = Readable::read(reader)?;
3887 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState>)>()));
3888 for _ in 0..peer_count {
3889 let peer_pubkey = Readable::read(reader)?;
3890 let peer_state = PeerState {
3891 latest_features: Readable::read(reader)?,
3893 per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
3896 let event_count: u64 = Readable::read(reader)?;
3897 let mut pending_events_read: Vec<events::Event> = Vec::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<events::Event>()));
3898 for _ in 0..event_count {
3899 match MaybeReadable::read(reader)? {
3900 Some(event) => pending_events_read.push(event),
3905 let last_node_announcement_serial: u32 = Readable::read(reader)?;
3907 let channel_manager = ChannelManager {
3909 fee_estimator: args.fee_estimator,
3910 monitor: args.monitor,
3911 tx_broadcaster: args.tx_broadcaster,
3913 latest_block_height: AtomicUsize::new(latest_block_height as usize),
3914 last_block_hash: Mutex::new(last_block_hash),
3915 secp_ctx: Secp256k1::new(),
3917 channel_state: Mutex::new(ChannelHolder {
3922 pending_msg_events: Vec::new(),
3924 our_network_key: args.keys_manager.get_node_secret(),
3926 last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
3928 per_peer_state: RwLock::new(per_peer_state),
3930 pending_events: Mutex::new(pending_events_read),
3931 total_consistency_lock: RwLock::new(()),
3932 keys_manager: args.keys_manager,
3933 logger: args.logger,
3934 default_configuration: args.default_config,
3937 for htlc_source in failed_htlcs.drain(..) {
3938 channel_manager.fail_htlc_backwards_internal(channel_manager.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
3941 //TODO: Broadcast channel update for closed channels, but only after we've made a
3942 //connection or two.
3944 Ok((last_block_hash.clone(), channel_manager))