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).
21 use bitcoin::blockdata::block::{Block, BlockHeader};
22 use bitcoin::blockdata::constants::genesis_block;
23 use bitcoin::network::constants::Network;
25 use bitcoin::hashes::{Hash, HashEngine};
26 use bitcoin::hashes::hmac::{Hmac, HmacEngine};
27 use bitcoin::hashes::sha256::Hash as Sha256;
28 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
29 use bitcoin::hashes::cmp::fixed_time_eq;
30 use bitcoin::hash_types::BlockHash;
32 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
33 use bitcoin::secp256k1::Secp256k1;
34 use bitcoin::secp256k1::ecdh::SharedSecret;
35 use bitcoin::secp256k1;
39 use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
40 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, ChannelMonitorUpdateErr, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent, CLOSED_CHANNEL_UPDATE_ID};
41 use chain::transaction::{OutPoint, TransactionData};
42 // Since this struct is returned in `list_channels` methods, expose it here in case users want to
43 // construct one themselves.
44 pub use ln::channel::CounterpartyForwardingInfo;
45 use ln::channel::{Channel, ChannelError};
46 use ln::features::{InitFeatures, NodeFeatures};
47 use routing::router::{Route, RouteHop};
49 use ln::msgs::NetAddress;
51 use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, OptionalField};
52 use chain::keysinterface::{Sign, KeysInterface, KeysManager, InMemorySigner};
53 use util::config::UserConfig;
54 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
55 use util::{byte_utils, events};
56 use util::ser::{Readable, ReadableArgs, MaybeReadable, Writeable, Writer};
57 use util::chacha20::{ChaCha20, ChaChaReader};
58 use util::logger::Logger;
59 use util::errors::APIError;
62 use std::collections::{HashMap, hash_map, HashSet};
63 use std::io::{Cursor, Read};
64 use std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard};
65 use std::sync::atomic::{AtomicUsize, Ordering};
66 use std::time::Duration;
67 #[cfg(any(test, feature = "allow_wallclock_use"))]
68 use std::time::Instant;
69 use std::marker::{Sync, Send};
71 use bitcoin::hashes::hex::ToHex;
73 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
75 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
76 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
77 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
79 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
80 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
81 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
82 // before we forward it.
84 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
85 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
86 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
87 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
88 // our payment, which we can use to decode errors or inform the user that the payment was sent.
90 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
91 enum PendingHTLCRouting {
93 onion_packet: msgs::OnionPacket,
94 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
97 payment_data: Option<msgs::FinalOnionHopData>,
98 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
102 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
103 pub(super) struct PendingHTLCInfo {
104 routing: PendingHTLCRouting,
105 incoming_shared_secret: [u8; 32],
106 payment_hash: PaymentHash,
107 pub(super) amt_to_forward: u64,
108 pub(super) outgoing_cltv_value: u32,
111 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
112 pub(super) enum HTLCFailureMsg {
113 Relay(msgs::UpdateFailHTLC),
114 Malformed(msgs::UpdateFailMalformedHTLC),
117 /// Stores whether we can't forward an HTLC or relevant forwarding info
118 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
119 pub(super) enum PendingHTLCStatus {
120 Forward(PendingHTLCInfo),
121 Fail(HTLCFailureMsg),
124 pub(super) enum HTLCForwardInfo {
126 forward_info: PendingHTLCInfo,
128 // These fields are produced in `forward_htlcs()` and consumed in
129 // `process_pending_htlc_forwards()` for constructing the
130 // `HTLCSource::PreviousHopData` for failed and forwarded
132 prev_short_channel_id: u64,
134 prev_funding_outpoint: OutPoint,
138 err_packet: msgs::OnionErrorPacket,
142 /// Tracks the inbound corresponding to an outbound HTLC
143 #[derive(Clone, PartialEq)]
144 pub(crate) struct HTLCPreviousHopData {
145 short_channel_id: u64,
147 incoming_packet_shared_secret: [u8; 32],
149 // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
150 // channel with a preimage provided by the forward channel.
154 struct ClaimableHTLC {
155 prev_hop: HTLCPreviousHopData,
157 /// Filled in when the HTLC was received with a payment_secret packet, which contains a
158 /// total_msat (which may differ from value if this is a Multi-Path Payment) and a
159 /// payment_secret which prevents path-probing attacks and can associate different HTLCs which
160 /// are part of the same payment.
161 payment_data: Option<msgs::FinalOnionHopData>,
165 /// Tracks the inbound corresponding to an outbound HTLC
166 #[derive(Clone, PartialEq)]
167 pub(crate) enum HTLCSource {
168 PreviousHopData(HTLCPreviousHopData),
171 session_priv: SecretKey,
172 /// Technically we can recalculate this from the route, but we cache it here to avoid
173 /// doing a double-pass on route when we get a failure back
174 first_hop_htlc_msat: u64,
179 pub fn dummy() -> Self {
180 HTLCSource::OutboundRoute {
182 session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
183 first_hop_htlc_msat: 0,
188 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
189 pub(super) enum HTLCFailReason {
191 err: msgs::OnionErrorPacket,
199 /// payment_hash type, use to cross-lock hop
200 /// (C-not exported) as we just use [u8; 32] directly
201 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
202 pub struct PaymentHash(pub [u8;32]);
203 /// payment_preimage type, use to route payment between hop
204 /// (C-not exported) as we just use [u8; 32] directly
205 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
206 pub struct PaymentPreimage(pub [u8;32]);
207 /// payment_secret type, use to authenticate sender to the receiver and tie MPP HTLCs together
208 /// (C-not exported) as we just use [u8; 32] directly
209 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
210 pub struct PaymentSecret(pub [u8;32]);
212 type ShutdownResult = (Option<(OutPoint, ChannelMonitorUpdate)>, Vec<(HTLCSource, PaymentHash)>);
214 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
215 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
216 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
217 /// channel_state lock. We then return the set of things that need to be done outside the lock in
218 /// this struct and call handle_error!() on it.
220 struct MsgHandleErrInternal {
221 err: msgs::LightningError,
222 shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
224 impl MsgHandleErrInternal {
226 fn send_err_msg_no_close(err: String, channel_id: [u8; 32]) -> Self {
228 err: LightningError {
230 action: msgs::ErrorAction::SendErrorMessage {
231 msg: msgs::ErrorMessage {
237 shutdown_finish: None,
241 fn ignore_no_close(err: String) -> Self {
243 err: LightningError {
245 action: msgs::ErrorAction::IgnoreError,
247 shutdown_finish: None,
251 fn from_no_close(err: msgs::LightningError) -> Self {
252 Self { err, shutdown_finish: None }
255 fn from_finish_shutdown(err: String, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
257 err: LightningError {
259 action: msgs::ErrorAction::SendErrorMessage {
260 msg: msgs::ErrorMessage {
266 shutdown_finish: Some((shutdown_res, channel_update)),
270 fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
273 ChannelError::Ignore(msg) => LightningError {
275 action: msgs::ErrorAction::IgnoreError,
277 ChannelError::Close(msg) => LightningError {
279 action: msgs::ErrorAction::SendErrorMessage {
280 msg: msgs::ErrorMessage {
286 ChannelError::CloseDelayBroadcast(msg) => LightningError {
288 action: msgs::ErrorAction::SendErrorMessage {
289 msg: msgs::ErrorMessage {
296 shutdown_finish: None,
301 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
302 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
303 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
304 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
305 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
307 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
308 /// be sent in the order they appear in the return value, however sometimes the order needs to be
309 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
310 /// they were originally sent). In those cases, this enum is also returned.
311 #[derive(Clone, PartialEq)]
312 pub(super) enum RAACommitmentOrder {
313 /// Send the CommitmentUpdate messages first
315 /// Send the RevokeAndACK message first
319 // Note this is only exposed in cfg(test):
320 pub(super) struct ChannelHolder<Signer: Sign> {
321 pub(super) by_id: HashMap<[u8; 32], Channel<Signer>>,
322 pub(super) short_to_id: HashMap<u64, [u8; 32]>,
323 /// short channel id -> forward infos. Key of 0 means payments received
324 /// Note that while this is held in the same mutex as the channels themselves, no consistency
325 /// guarantees are made about the existence of a channel with the short id here, nor the short
326 /// ids in the PendingHTLCInfo!
327 pub(super) forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
328 /// (payment_hash, payment_secret) -> Vec<HTLCs> for tracking HTLCs that
329 /// were to us and can be failed/claimed by the user
330 /// Note that while this is held in the same mutex as the channels themselves, no consistency
331 /// guarantees are made about the channels given here actually existing anymore by the time you
333 claimable_htlcs: HashMap<(PaymentHash, Option<PaymentSecret>), Vec<ClaimableHTLC>>,
334 /// Messages to send to peers - pushed to in the same lock that they are generated in (except
335 /// for broadcast messages, where ordering isn't as strict).
336 pub(super) pending_msg_events: Vec<MessageSendEvent>,
339 /// Events which we process internally but cannot be procsesed immediately at the generation site
340 /// for some reason. They are handled in timer_chan_freshness_every_min, so may be processed with
341 /// quite some time lag.
342 enum BackgroundEvent {
343 /// Handle a ChannelMonitorUpdate that closes a channel, broadcasting its current latest holder
344 /// commitment transaction.
345 ClosingMonitorUpdate((OutPoint, ChannelMonitorUpdate)),
348 /// State we hold per-peer. In the future we should put channels in here, but for now we only hold
349 /// the latest Init features we heard from the peer.
351 latest_features: InitFeatures,
354 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
355 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
357 /// SimpleArcChannelManager is useful when you need a ChannelManager with a static lifetime, e.g.
358 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
359 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
360 /// SimpleRefChannelManager is the more appropriate type. Defining these type aliases prevents
361 /// issues such as overly long function definitions. Note that the ChannelManager can take any
362 /// type that implements KeysInterface for its keys manager, but this type alias chooses the
363 /// concrete type of the KeysManager.
364 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<InMemorySigner, Arc<M>, Arc<T>, Arc<KeysManager>, Arc<F>, Arc<L>>;
366 /// SimpleRefChannelManager is a type alias for a ChannelManager reference, and is the reference
367 /// counterpart to the SimpleArcChannelManager type alias. Use this type by default when you don't
368 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
369 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
370 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
371 /// helps with issues such as long function definitions. Note that the ChannelManager can take any
372 /// type that implements KeysInterface for its keys manager, but this type alias chooses the
373 /// concrete type of the KeysManager.
374 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManager<InMemorySigner, &'a M, &'b T, &'c KeysManager, &'d F, &'e L>;
376 /// Manager which keeps track of a number of channels and sends messages to the appropriate
377 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
379 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
380 /// to individual Channels.
382 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
383 /// all peers during write/read (though does not modify this instance, only the instance being
384 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
385 /// called funding_transaction_generated for outbound channels).
387 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
388 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
389 /// returning from chain::Watch::watch_/update_channel, with ChannelManagers, writing updates
390 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
391 /// the serialization process). If the deserialized version is out-of-date compared to the
392 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
393 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
395 /// Note that the deserializer is only implemented for (BlockHash, ChannelManager), which
396 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
397 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
398 /// block_connected() to step towards your best block) upon deserialization before using the
401 /// Note that ChannelManager is responsible for tracking liveness of its channels and generating
402 /// ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid
403 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
404 /// offline for a full minute. In order to track this, you must call
405 /// timer_chan_freshness_every_min roughly once per minute, though it doesn't have to be perfect.
407 /// Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager
408 /// a SimpleRefChannelManager, for conciseness. See their documentation for more details, but
409 /// essentially you should default to using a SimpleRefChannelManager, and use a
410 /// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
411 /// you're using lightning-net-tokio.
412 pub struct ChannelManager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
413 where M::Target: chain::Watch<Signer>,
414 T::Target: BroadcasterInterface,
415 K::Target: KeysInterface<Signer = Signer>,
416 F::Target: FeeEstimator,
419 default_configuration: UserConfig,
420 genesis_hash: BlockHash,
426 pub(super) latest_block_height: AtomicUsize,
428 latest_block_height: AtomicUsize,
429 last_block_hash: RwLock<BlockHash>,
430 secp_ctx: Secp256k1<secp256k1::All>,
432 #[cfg(any(test, feature = "_test_utils"))]
433 pub(super) channel_state: Mutex<ChannelHolder<Signer>>,
434 #[cfg(not(any(test, feature = "_test_utils")))]
435 channel_state: Mutex<ChannelHolder<Signer>>,
436 our_network_key: SecretKey,
438 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
439 /// value increases strictly since we don't assume access to a time source.
440 last_node_announcement_serial: AtomicUsize,
442 /// The bulk of our storage will eventually be here (channels and message queues and the like).
443 /// If we are connected to a peer we always at least have an entry here, even if no channels
444 /// are currently open with that peer.
445 /// Because adding or removing an entry is rare, we usually take an outer read lock and then
446 /// operate on the inner value freely. Sadly, this prevents parallel operation when opening a
448 per_peer_state: RwLock<HashMap<PublicKey, Mutex<PeerState>>>,
450 pending_events: Mutex<Vec<events::Event>>,
451 pending_background_events: Mutex<Vec<BackgroundEvent>>,
452 /// Used when we have to take a BIG lock to make sure everything is self-consistent.
453 /// Essentially just when we're serializing ourselves out.
454 /// Taken first everywhere where we are making changes before any other locks.
455 /// When acquiring this lock in read mode, rather than acquiring it directly, call
456 /// `PersistenceNotifierGuard::new(..)` and pass the lock to it, to ensure the PersistenceNotifier
457 /// the lock contains sends out a notification when the lock is released.
458 total_consistency_lock: RwLock<()>,
460 persistence_notifier: PersistenceNotifier,
467 /// Chain-related parameters used to construct a new `ChannelManager`.
469 /// Typically, the block-specific parameters are derived from the best block hash for the network,
470 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
471 /// are not needed when deserializing a previously constructed `ChannelManager`.
472 pub struct ChainParameters {
473 /// The network for determining the `chain_hash` in Lightning messages.
474 pub network: Network,
476 /// The hash of the latest block successfully connected.
477 pub latest_hash: BlockHash,
479 /// The height of the latest block successfully connected.
481 /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
482 pub latest_height: usize,
485 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
486 /// desirable to notify any listeners on `await_persistable_update_timeout`/
487 /// `await_persistable_update` that new updates are available for persistence. Therefore, this
488 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
489 /// sending the aforementioned notification (since the lock being released indicates that the
490 /// updates are ready for persistence).
491 struct PersistenceNotifierGuard<'a> {
492 persistence_notifier: &'a PersistenceNotifier,
493 // We hold onto this result so the lock doesn't get released immediately.
494 _read_guard: RwLockReadGuard<'a, ()>,
497 impl<'a> PersistenceNotifierGuard<'a> {
498 fn new(lock: &'a RwLock<()>, notifier: &'a PersistenceNotifier) -> Self {
499 let read_guard = lock.read().unwrap();
502 persistence_notifier: notifier,
503 _read_guard: read_guard,
508 impl<'a> Drop for PersistenceNotifierGuard<'a> {
510 self.persistence_notifier.notify();
514 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
515 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
517 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
519 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
520 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
521 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
522 /// the maximum required amount in lnd as of March 2021.
523 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
525 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
526 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
527 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
528 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
529 /// CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
530 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
531 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
533 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
534 // ie that if the next-hop peer fails the HTLC within
535 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
536 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
537 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
538 // LATENCY_GRACE_PERIOD_BLOCKS.
541 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;
543 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
544 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
547 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
549 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
551 pub struct ChannelDetails {
552 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
553 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
554 /// Note that this means this value is *not* persistent - it can change once during the
555 /// lifetime of the channel.
556 pub channel_id: [u8; 32],
557 /// The position of the funding transaction in the chain. None if the funding transaction has
558 /// not yet been confirmed and the channel fully opened.
559 pub short_channel_id: Option<u64>,
560 /// The node_id of our counterparty
561 pub remote_network_id: PublicKey,
562 /// The Features the channel counterparty provided upon last connection.
563 /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
564 /// many routing-relevant features are present in the init context.
565 pub counterparty_features: InitFeatures,
566 /// The value, in satoshis, of this channel as appears in the funding output
567 pub channel_value_satoshis: u64,
568 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
570 /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
571 /// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
572 /// available for inclusion in new outbound HTLCs). This further does not include any pending
573 /// outgoing HTLCs which are awaiting some other resolution to be sent.
574 pub outbound_capacity_msat: u64,
575 /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
576 /// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
577 /// available for inclusion in new inbound HTLCs).
578 /// Note that there are some corner cases not fully handled here, so the actual available
579 /// inbound capacity may be slightly higher than this.
580 pub inbound_capacity_msat: u64,
581 /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
582 /// the peer is connected, and (c) no monitor update failure is pending resolution.
585 /// Information on the fees and requirements that the counterparty requires when forwarding
586 /// payments to us through this channel.
587 pub counterparty_forwarding_info: Option<CounterpartyForwardingInfo>,
590 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
591 /// Err() type describing which state the payment is in, see the description of individual enum
593 #[derive(Clone, Debug)]
594 pub enum PaymentSendFailure {
595 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
596 /// send the payment at all. No channel state has been changed or messages sent to peers, and
597 /// once you've changed the parameter at error, you can freely retry the payment in full.
598 ParameterError(APIError),
599 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
600 /// from attempting to send the payment at all. No channel state has been changed or messages
601 /// sent to peers, and once you've changed the parameter at error, you can freely retry the
604 /// The results here are ordered the same as the paths in the route object which was passed to
606 PathParameterError(Vec<Result<(), APIError>>),
607 /// All paths which were attempted failed to send, with no channel state change taking place.
608 /// You can freely retry the payment in full (though you probably want to do so over different
609 /// paths than the ones selected).
610 AllFailedRetrySafe(Vec<APIError>),
611 /// Some paths which were attempted failed to send, though possibly not all. At least some
612 /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
613 /// in over-/re-payment.
615 /// The results here are ordered the same as the paths in the route object which was passed to
616 /// send_payment, and any Errs which are not APIError::MonitorUpdateFailed can be safely
617 /// retried (though there is currently no API with which to do so).
619 /// Any entries which contain Err(APIError::MonitorUpdateFailed) or Ok(()) MUST NOT be retried
620 /// as they will result in over-/re-payment. These HTLCs all either successfully sent (in the
621 /// case of Ok(())) or will send once channel_monitor_updated is called on the next-hop channel
622 /// with the latest update_id.
623 PartialFailure(Vec<Result<(), APIError>>),
626 macro_rules! handle_error {
627 ($self: ident, $internal: expr, $counterparty_node_id: expr) => {
630 Err(MsgHandleErrInternal { err, shutdown_finish }) => {
631 #[cfg(debug_assertions)]
633 // In testing, ensure there are no deadlocks where the lock is already held upon
634 // entering the macro.
635 assert!($self.channel_state.try_lock().is_ok());
638 let mut msg_events = Vec::with_capacity(2);
640 if let Some((shutdown_res, update_option)) = shutdown_finish {
641 $self.finish_force_close_channel(shutdown_res);
642 if let Some(update) = update_option {
643 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
649 log_error!($self.logger, "{}", err.err);
650 if let msgs::ErrorAction::IgnoreError = err.action {
652 msg_events.push(events::MessageSendEvent::HandleError {
653 node_id: $counterparty_node_id,
654 action: err.action.clone()
658 if !msg_events.is_empty() {
659 $self.channel_state.lock().unwrap().pending_msg_events.append(&mut msg_events);
662 // Return error in case higher-API need one
669 macro_rules! break_chan_entry {
670 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
673 Err(ChannelError::Ignore(msg)) => {
674 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
676 Err(ChannelError::Close(msg)) => {
677 log_trace!($self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
678 let (channel_id, mut chan) = $entry.remove_entry();
679 if let Some(short_id) = chan.get_short_channel_id() {
680 $channel_state.short_to_id.remove(&short_id);
682 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()))
684 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"); }
689 macro_rules! try_chan_entry {
690 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
693 Err(ChannelError::Ignore(msg)) => {
694 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
696 Err(ChannelError::Close(msg)) => {
697 log_trace!($self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
698 let (channel_id, mut chan) = $entry.remove_entry();
699 if let Some(short_id) = chan.get_short_channel_id() {
700 $channel_state.short_to_id.remove(&short_id);
702 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()))
704 Err(ChannelError::CloseDelayBroadcast(msg)) => {
705 log_error!($self.logger, "Channel {} need to be shutdown but closing transactions not broadcast due to {}", log_bytes!($entry.key()[..]), msg);
706 let (channel_id, mut chan) = $entry.remove_entry();
707 if let Some(short_id) = chan.get_short_channel_id() {
708 $channel_state.short_to_id.remove(&short_id);
710 let shutdown_res = chan.force_shutdown(false);
711 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, shutdown_res, $self.get_channel_update(&chan).ok()))
717 macro_rules! handle_monitor_err {
718 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
719 handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, Vec::new(), Vec::new())
721 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
723 ChannelMonitorUpdateErr::PermanentFailure => {
724 log_error!($self.logger, "Closing channel {} due to monitor update PermanentFailure", log_bytes!($entry.key()[..]));
725 let (channel_id, mut chan) = $entry.remove_entry();
726 if let Some(short_id) = chan.get_short_channel_id() {
727 $channel_state.short_to_id.remove(&short_id);
729 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
730 // chain in a confused state! We need to move them into the ChannelMonitor which
731 // will be responsible for failing backwards once things confirm on-chain.
732 // It's ok that we drop $failed_forwards here - at this point we'd rather they
733 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
734 // us bother trying to claim it just to forward on to another peer. If we're
735 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
736 // given up the preimage yet, so might as well just wait until the payment is
737 // retried, avoiding the on-chain fees.
738 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()));
741 ChannelMonitorUpdateErr::TemporaryFailure => {
742 log_info!($self.logger, "Disabling channel {} due to monitor update TemporaryFailure. On restore will send {} and process {} forwards and {} fails",
743 log_bytes!($entry.key()[..]),
744 if $resend_commitment && $resend_raa {
746 RAACommitmentOrder::CommitmentFirst => { "commitment then RAA" },
747 RAACommitmentOrder::RevokeAndACKFirst => { "RAA then commitment" },
749 } else if $resend_commitment { "commitment" }
750 else if $resend_raa { "RAA" }
752 (&$failed_forwards as &Vec<(PendingHTLCInfo, u64)>).len(),
753 (&$failed_fails as &Vec<(HTLCSource, PaymentHash, HTLCFailReason)>).len());
754 if !$resend_commitment {
755 debug_assert!($action_type == RAACommitmentOrder::RevokeAndACKFirst || !$resend_raa);
758 debug_assert!($action_type == RAACommitmentOrder::CommitmentFirst || !$resend_commitment);
760 $entry.get_mut().monitor_update_failed($resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
761 Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor".to_owned()), *$entry.key()))
767 macro_rules! return_monitor_err {
768 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
769 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment);
771 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
772 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
776 // Does not break in case of TemporaryFailure!
777 macro_rules! maybe_break_monitor_err {
778 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
779 match (handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment), $err) {
780 (e, ChannelMonitorUpdateErr::PermanentFailure) => {
783 (_, ChannelMonitorUpdateErr::TemporaryFailure) => { },
788 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
789 where M::Target: chain::Watch<Signer>,
790 T::Target: BroadcasterInterface,
791 K::Target: KeysInterface<Signer = Signer>,
792 F::Target: FeeEstimator,
795 /// Constructs a new ChannelManager to hold several channels and route between them.
797 /// This is the main "logic hub" for all channel-related actions, and implements
798 /// ChannelMessageHandler.
800 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
802 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
804 /// Users need to notify the new ChannelManager when a new block is connected or
805 /// disconnected using its `block_connected` and `block_disconnected` methods, starting
806 /// from after `params.latest_hash`.
807 pub fn new(fee_est: F, chain_monitor: M, tx_broadcaster: T, logger: L, keys_manager: K, config: UserConfig, params: ChainParameters) -> Self {
808 let mut secp_ctx = Secp256k1::new();
809 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
812 default_configuration: config.clone(),
813 genesis_hash: genesis_block(params.network).header.block_hash(),
814 fee_estimator: fee_est,
818 latest_block_height: AtomicUsize::new(params.latest_height),
819 last_block_hash: RwLock::new(params.latest_hash),
822 channel_state: Mutex::new(ChannelHolder{
823 by_id: HashMap::new(),
824 short_to_id: HashMap::new(),
825 forward_htlcs: HashMap::new(),
826 claimable_htlcs: HashMap::new(),
827 pending_msg_events: Vec::new(),
829 our_network_key: keys_manager.get_node_secret(),
831 last_node_announcement_serial: AtomicUsize::new(0),
833 per_peer_state: RwLock::new(HashMap::new()),
835 pending_events: Mutex::new(Vec::new()),
836 pending_background_events: Mutex::new(Vec::new()),
837 total_consistency_lock: RwLock::new(()),
838 persistence_notifier: PersistenceNotifier::new(),
846 /// Creates a new outbound channel to the given remote node and with the given value.
848 /// user_id will be provided back as user_channel_id in FundingGenerationReady and
849 /// FundingBroadcastSafe events to allow tracking of which events correspond with which
850 /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
851 /// may wish to avoid using 0 for user_id here.
853 /// If successful, will generate a SendOpenChannel message event, so you should probably poll
854 /// PeerManager::process_events afterwards.
856 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
857 /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
858 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> {
859 if channel_value_satoshis < 1000 {
860 return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
863 let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
864 let channel = Channel::new_outbound(&self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, config)?;
865 let res = channel.get_open_channel(self.genesis_hash.clone());
867 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
868 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
869 debug_assert!(&self.total_consistency_lock.try_write().is_err());
871 let mut channel_state = self.channel_state.lock().unwrap();
872 match channel_state.by_id.entry(channel.channel_id()) {
873 hash_map::Entry::Occupied(_) => {
874 if cfg!(feature = "fuzztarget") {
875 return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
877 panic!("RNG is bad???");
880 hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
882 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
883 node_id: their_network_key,
889 fn list_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<Signer>)) -> bool>(&self, f: Fn) -> Vec<ChannelDetails> {
890 let mut res = Vec::new();
892 let channel_state = self.channel_state.lock().unwrap();
893 res.reserve(channel_state.by_id.len());
894 for (channel_id, channel) in channel_state.by_id.iter().filter(f) {
895 let (inbound_capacity_msat, outbound_capacity_msat) = channel.get_inbound_outbound_available_balance_msat();
896 res.push(ChannelDetails {
897 channel_id: (*channel_id).clone(),
898 short_channel_id: channel.get_short_channel_id(),
899 remote_network_id: channel.get_counterparty_node_id(),
900 counterparty_features: InitFeatures::empty(),
901 channel_value_satoshis: channel.get_value_satoshis(),
902 inbound_capacity_msat,
903 outbound_capacity_msat,
904 user_id: channel.get_user_id(),
905 is_live: channel.is_live(),
906 counterparty_forwarding_info: channel.counterparty_forwarding_info(),
910 let per_peer_state = self.per_peer_state.read().unwrap();
911 for chan in res.iter_mut() {
912 if let Some(peer_state) = per_peer_state.get(&chan.remote_network_id) {
913 chan.counterparty_features = peer_state.lock().unwrap().latest_features.clone();
919 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
920 /// more information.
921 pub fn list_channels(&self) -> Vec<ChannelDetails> {
922 self.list_channels_with_filter(|_| true)
925 /// Gets the list of usable channels, in random order. Useful as an argument to
926 /// get_route to ensure non-announced channels are used.
928 /// These are guaranteed to have their is_live value set to true, see the documentation for
929 /// ChannelDetails::is_live for more info on exactly what the criteria are.
930 pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
931 // Note we use is_live here instead of usable which leads to somewhat confused
932 // internal/external nomenclature, but that's ok cause that's probably what the user
933 // really wanted anyway.
934 self.list_channels_with_filter(|&(_, ref channel)| channel.is_live())
937 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
938 /// will be accepted on the given channel, and after additional timeout/the closing of all
939 /// pending HTLCs, the channel will be closed on chain.
941 /// May generate a SendShutdown message event on success, which should be relayed.
942 pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
943 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
945 let (mut failed_htlcs, chan_option) = {
946 let mut channel_state_lock = self.channel_state.lock().unwrap();
947 let channel_state = &mut *channel_state_lock;
948 match channel_state.by_id.entry(channel_id.clone()) {
949 hash_map::Entry::Occupied(mut chan_entry) => {
950 let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
951 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
952 node_id: chan_entry.get().get_counterparty_node_id(),
955 if chan_entry.get().is_shutdown() {
956 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
957 channel_state.short_to_id.remove(&short_id);
959 (failed_htlcs, Some(chan_entry.remove_entry().1))
960 } else { (failed_htlcs, None) }
962 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()})
965 for htlc_source in failed_htlcs.drain(..) {
966 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() });
968 let chan_update = if let Some(chan) = chan_option {
969 if let Ok(update) = self.get_channel_update(&chan) {
974 if let Some(update) = chan_update {
975 let mut channel_state = self.channel_state.lock().unwrap();
976 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
985 fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
986 let (monitor_update_option, mut failed_htlcs) = shutdown_res;
987 log_trace!(self.logger, "Finishing force-closure of channel {} HTLCs to fail", failed_htlcs.len());
988 for htlc_source in failed_htlcs.drain(..) {
989 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() });
991 if let Some((funding_txo, monitor_update)) = monitor_update_option {
992 // There isn't anything we can do if we get an update failure - we're already
993 // force-closing. The monitor update on the required in-memory copy should broadcast
994 // the latest local state, which is the best we can do anyway. Thus, it is safe to
995 // ignore the result here.
996 let _ = self.chain_monitor.update_channel(funding_txo, monitor_update);
1000 fn force_close_channel_with_peer(&self, channel_id: &[u8; 32], peer_node_id: Option<&PublicKey>) -> Result<(), APIError> {
1002 let mut channel_state_lock = self.channel_state.lock().unwrap();
1003 let channel_state = &mut *channel_state_lock;
1004 if let hash_map::Entry::Occupied(chan) = channel_state.by_id.entry(channel_id.clone()) {
1005 if let Some(node_id) = peer_node_id {
1006 if chan.get().get_counterparty_node_id() != *node_id {
1007 // Error or Ok here doesn't matter - the result is only exposed publicly
1008 // when peer_node_id is None anyway.
1012 if let Some(short_id) = chan.get().get_short_channel_id() {
1013 channel_state.short_to_id.remove(&short_id);
1015 chan.remove_entry().1
1017 return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()});
1020 log_trace!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
1021 self.finish_force_close_channel(chan.force_shutdown(true));
1022 if let Ok(update) = self.get_channel_update(&chan) {
1023 let mut channel_state = self.channel_state.lock().unwrap();
1024 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1032 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
1033 /// the chain and rejecting new HTLCs on the given channel. Fails if channel_id is unknown to the manager.
1034 pub fn force_close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
1035 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1036 self.force_close_channel_with_peer(channel_id, None)
1039 /// Force close all channels, immediately broadcasting the latest local commitment transaction
1040 /// for each to the chain and rejecting new HTLCs on each.
1041 pub fn force_close_all_channels(&self) {
1042 for chan in self.list_channels() {
1043 let _ = self.force_close_channel(&chan.channel_id);
1047 fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder<Signer>>) {
1048 macro_rules! return_malformed_err {
1049 ($msg: expr, $err_code: expr) => {
1051 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
1052 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
1053 channel_id: msg.channel_id,
1054 htlc_id: msg.htlc_id,
1055 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
1056 failure_code: $err_code,
1057 })), self.channel_state.lock().unwrap());
1062 if let Err(_) = msg.onion_routing_packet.public_key {
1063 return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
1066 let shared_secret = {
1067 let mut arr = [0; 32];
1068 arr.copy_from_slice(&SharedSecret::new(&msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
1071 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(&shared_secret);
1073 if msg.onion_routing_packet.version != 0 {
1074 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1075 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1076 //the hash doesn't really serve any purpose - in the case of hashing all data, the
1077 //receiving node would have to brute force to figure out which version was put in the
1078 //packet by the node that send us the message, in the case of hashing the hop_data, the
1079 //node knows the HMAC matched, so they already know what is there...
1080 return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
1083 let mut hmac = HmacEngine::<Sha256>::new(&mu);
1084 hmac.input(&msg.onion_routing_packet.hop_data);
1085 hmac.input(&msg.payment_hash.0[..]);
1086 if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
1087 return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
1090 let mut channel_state = None;
1091 macro_rules! return_err {
1092 ($msg: expr, $err_code: expr, $data: expr) => {
1094 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
1095 if channel_state.is_none() {
1096 channel_state = Some(self.channel_state.lock().unwrap());
1098 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1099 channel_id: msg.channel_id,
1100 htlc_id: msg.htlc_id,
1101 reason: onion_utils::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1102 })), channel_state.unwrap());
1107 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1108 let mut chacha_stream = ChaChaReader { chacha: &mut chacha, read: Cursor::new(&msg.onion_routing_packet.hop_data[..]) };
1109 let (next_hop_data, next_hop_hmac) = {
1110 match msgs::OnionHopData::read(&mut chacha_stream) {
1112 let error_code = match err {
1113 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1114 msgs::DecodeError::UnknownRequiredFeature|
1115 msgs::DecodeError::InvalidValue|
1116 msgs::DecodeError::ShortRead => 0x4000 | 22, // invalid_onion_payload
1117 _ => 0x2000 | 2, // Should never happen
1119 return_err!("Unable to decode our hop data", error_code, &[0;0]);
1122 let mut hmac = [0; 32];
1123 if let Err(_) = chacha_stream.read_exact(&mut hmac[..]) {
1124 return_err!("Unable to decode hop data", 0x4000 | 22, &[0;0]);
1131 let pending_forward_info = if next_hop_hmac == [0; 32] {
1134 // In tests, make sure that the initial onion pcket data is, at least, non-0.
1135 // We could do some fancy randomness test here, but, ehh, whatever.
1136 // This checks for the issue where you can calculate the path length given the
1137 // onion data as all the path entries that the originator sent will be here
1138 // as-is (and were originally 0s).
1139 // Of course reverse path calculation is still pretty easy given naive routing
1140 // algorithms, but this fixes the most-obvious case.
1141 let mut next_bytes = [0; 32];
1142 chacha_stream.read_exact(&mut next_bytes).unwrap();
1143 assert_ne!(next_bytes[..], [0; 32][..]);
1144 chacha_stream.read_exact(&mut next_bytes).unwrap();
1145 assert_ne!(next_bytes[..], [0; 32][..]);
1149 // final_expiry_too_soon
1150 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure we have at least
1151 // HTLC_FAIL_BACK_BUFFER blocks to go.
1152 // Also, ensure that, in the case of an unknown payment hash, our payment logic has enough time to fail the HTLC backward
1153 // before our onchain logic triggers a channel closure (see HTLC_FAIL_BACK_BUFFER rational).
1154 if (msg.cltv_expiry as u64) <= self.latest_block_height.load(Ordering::Acquire) as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1 {
1155 return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1157 // final_incorrect_htlc_amount
1158 if next_hop_data.amt_to_forward > msg.amount_msat {
1159 return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1161 // final_incorrect_cltv_expiry
1162 if next_hop_data.outgoing_cltv_value != msg.cltv_expiry {
1163 return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1166 let payment_data = match next_hop_data.format {
1167 msgs::OnionHopDataFormat::Legacy { .. } => None,
1168 msgs::OnionHopDataFormat::NonFinalNode { .. } => return_err!("Got non final data with an HMAC of 0", 0x4000 | 22, &[0;0]),
1169 msgs::OnionHopDataFormat::FinalNode { payment_data } => payment_data,
1172 // Note that we could obviously respond immediately with an update_fulfill_htlc
1173 // message, however that would leak that we are the recipient of this payment, so
1174 // instead we stay symmetric with the forwarding case, only responding (after a
1175 // delay) once they've send us a commitment_signed!
1177 PendingHTLCStatus::Forward(PendingHTLCInfo {
1178 routing: PendingHTLCRouting::Receive {
1180 incoming_cltv_expiry: msg.cltv_expiry,
1182 payment_hash: msg.payment_hash.clone(),
1183 incoming_shared_secret: shared_secret,
1184 amt_to_forward: next_hop_data.amt_to_forward,
1185 outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1188 let mut new_packet_data = [0; 20*65];
1189 let read_pos = chacha_stream.read(&mut new_packet_data).unwrap();
1190 #[cfg(debug_assertions)]
1192 // Check two things:
1193 // a) that the behavior of our stream here will return Ok(0) even if the TLV
1194 // read above emptied out our buffer and the unwrap() wont needlessly panic
1195 // b) that we didn't somehow magically end up with extra data.
1197 debug_assert!(chacha_stream.read(&mut t).unwrap() == 0);
1199 // Once we've emptied the set of bytes our peer gave us, encrypt 0 bytes until we
1200 // fill the onion hop data we'll forward to our next-hop peer.
1201 chacha_stream.chacha.process_in_place(&mut new_packet_data[read_pos..]);
1203 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1205 let blinding_factor = {
1206 let mut sha = Sha256::engine();
1207 sha.input(&new_pubkey.serialize()[..]);
1208 sha.input(&shared_secret);
1209 Sha256::from_engine(sha).into_inner()
1212 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor[..]) {
1214 } else { Ok(new_pubkey) };
1216 let outgoing_packet = msgs::OnionPacket {
1219 hop_data: new_packet_data,
1220 hmac: next_hop_hmac.clone(),
1223 let short_channel_id = match next_hop_data.format {
1224 msgs::OnionHopDataFormat::Legacy { short_channel_id } => short_channel_id,
1225 msgs::OnionHopDataFormat::NonFinalNode { short_channel_id } => short_channel_id,
1226 msgs::OnionHopDataFormat::FinalNode { .. } => {
1227 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0;0]);
1231 PendingHTLCStatus::Forward(PendingHTLCInfo {
1232 routing: PendingHTLCRouting::Forward {
1233 onion_packet: outgoing_packet,
1236 payment_hash: msg.payment_hash.clone(),
1237 incoming_shared_secret: shared_secret,
1238 amt_to_forward: next_hop_data.amt_to_forward,
1239 outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1243 channel_state = Some(self.channel_state.lock().unwrap());
1244 if let &PendingHTLCStatus::Forward(PendingHTLCInfo { ref routing, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1245 // If short_channel_id is 0 here, we'll reject the HTLC as there cannot be a channel
1246 // with a short_channel_id of 0. This is important as various things later assume
1247 // short_channel_id is non-0 in any ::Forward.
1248 if let &PendingHTLCRouting::Forward { ref short_channel_id, .. } = routing {
1249 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1250 let forwarding_id = match id_option {
1251 None => { // unknown_next_peer
1252 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1254 Some(id) => id.clone(),
1256 if let Some((err, code, chan_update)) = loop {
1257 let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1259 // Note that we could technically not return an error yet here and just hope
1260 // that the connection is reestablished or monitor updated by the time we get
1261 // around to doing the actual forward, but better to fail early if we can and
1262 // hopefully an attacker trying to path-trace payments cannot make this occur
1263 // on a small/per-node/per-channel scale.
1264 if !chan.is_live() { // channel_disabled
1265 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1267 if *amt_to_forward < chan.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
1268 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1270 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_holder_fee_base_msat(&self.fee_estimator) as u64) });
1271 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1272 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())));
1274 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1275 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())));
1277 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1278 // Theoretically, channel counterparty shouldn't send us a HTLC expiring now, but we want to be robust wrt to counterparty
1279 // packet sanitization (see HTLC_FAIL_BACK_BUFFER rational)
1280 if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
1281 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1283 if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1284 break Some(("CLTV expiry is too far in the future", 21, None));
1286 // In theory, we would be safe against unitentional channel-closure, if we only required a margin of LATENCY_GRACE_PERIOD_BLOCKS.
1287 // But, to be safe against policy reception, we use a longuer delay.
1288 if (*outgoing_cltv_value) as u64 <= (cur_height + HTLC_FAIL_BACK_BUFFER) as u64 {
1289 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1295 let mut res = Vec::with_capacity(8 + 128);
1296 if let Some(chan_update) = chan_update {
1297 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1298 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1300 else if code == 0x1000 | 13 {
1301 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1303 else if code == 0x1000 | 20 {
1304 // TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
1305 res.extend_from_slice(&byte_utils::be16_to_array(0));
1307 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1309 return_err!(err, code, &res[..]);
1314 (pending_forward_info, channel_state.unwrap())
1317 /// only fails if the channel does not yet have an assigned short_id
1318 /// May be called with channel_state already locked!
1319 fn get_channel_update(&self, chan: &Channel<Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
1320 let short_channel_id = match chan.get_short_channel_id() {
1321 None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
1325 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_counterparty_node_id().serialize()[..];
1327 let unsigned = msgs::UnsignedChannelUpdate {
1328 chain_hash: self.genesis_hash,
1330 timestamp: chan.get_update_time_counter(),
1331 flags: (!were_node_one) as u8 | ((!chan.is_live() as u8) << 1),
1332 cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1333 htlc_minimum_msat: chan.get_counterparty_htlc_minimum_msat(),
1334 htlc_maximum_msat: OptionalField::Present(chan.get_announced_htlc_max_msat()),
1335 fee_base_msat: chan.get_holder_fee_base_msat(&self.fee_estimator),
1336 fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1337 excess_data: Vec::new(),
1340 let msg_hash = Sha256dHash::hash(&unsigned.encode()[..]);
1341 let sig = self.secp_ctx.sign(&hash_to_message!(&msg_hash[..]), &self.our_network_key);
1343 Ok(msgs::ChannelUpdate {
1349 // Only public for testing, this should otherwise never be called direcly
1350 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> {
1351 log_trace!(self.logger, "Attempting to send payment for path with next hop {}", path.first().unwrap().short_channel_id);
1352 let prng_seed = self.keys_manager.get_secure_random_bytes();
1353 let session_priv = SecretKey::from_slice(&self.keys_manager.get_secure_random_bytes()[..]).expect("RNG is busted");
1355 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
1356 .map_err(|_| APIError::RouteError{err: "Pubkey along hop was maliciously selected"})?;
1357 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, payment_secret, cur_height)?;
1358 if onion_utils::route_size_insane(&onion_payloads) {
1359 return Err(APIError::RouteError{err: "Route size too large considering onion data"});
1361 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash);
1363 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1365 let err: Result<(), _> = loop {
1366 let mut channel_lock = self.channel_state.lock().unwrap();
1367 let id = match channel_lock.short_to_id.get(&path.first().unwrap().short_channel_id) {
1368 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
1369 Some(id) => id.clone(),
1372 let channel_state = &mut *channel_lock;
1373 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1375 if chan.get().get_counterparty_node_id() != path.first().unwrap().pubkey {
1376 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1378 if !chan.get().is_live() {
1379 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!".to_owned()});
1381 break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1383 session_priv: session_priv.clone(),
1384 first_hop_htlc_msat: htlc_msat,
1385 }, onion_packet, &self.logger), channel_state, chan)
1387 Some((update_add, commitment_signed, monitor_update)) => {
1388 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
1389 maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true);
1390 // Note that MonitorUpdateFailed here indicates (per function docs)
1391 // that we will resend the commitment update once monitor updating
1392 // is restored. Therefore, we must return an error indicating that
1393 // it is unsafe to retry the payment wholesale, which we do in the
1394 // send_payment check for MonitorUpdateFailed, below.
1395 return Err(APIError::MonitorUpdateFailed);
1398 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1399 node_id: path.first().unwrap().pubkey,
1400 updates: msgs::CommitmentUpdate {
1401 update_add_htlcs: vec![update_add],
1402 update_fulfill_htlcs: Vec::new(),
1403 update_fail_htlcs: Vec::new(),
1404 update_fail_malformed_htlcs: Vec::new(),
1412 } else { unreachable!(); }
1416 match handle_error!(self, err, path.first().unwrap().pubkey) {
1417 Ok(_) => unreachable!(),
1419 Err(APIError::ChannelUnavailable { err: e.err })
1424 /// Sends a payment along a given route.
1426 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1427 /// fields for more info.
1429 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1430 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1431 /// next hop knows the preimage to payment_hash they can claim an additional amount as
1432 /// specified in the last hop in the route! Thus, you should probably do your own
1433 /// payment_preimage tracking (which you should already be doing as they represent "proof of
1434 /// payment") and prevent double-sends yourself.
1436 /// May generate SendHTLCs message(s) event on success, which should be relayed.
1438 /// Each path may have a different return value, and PaymentSendValue may return a Vec with
1439 /// each entry matching the corresponding-index entry in the route paths, see
1440 /// PaymentSendFailure for more info.
1442 /// In general, a path may raise:
1443 /// * APIError::RouteError when an invalid route or forwarding parameter (cltv_delta, fee,
1444 /// node public key) is specified.
1445 /// * APIError::ChannelUnavailable if the next-hop channel is not available for updates
1446 /// (including due to previous monitor update failure or new permanent monitor update
1448 /// * APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1449 /// relevant updates.
1451 /// Note that depending on the type of the PaymentSendFailure the HTLC may have been
1452 /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
1453 /// different route unless you intend to pay twice!
1455 /// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
1456 /// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
1457 /// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
1458 /// must not contain multiple paths as multi-path payments require a recipient-provided
1460 /// If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
1461 /// bit set (either as required or as available). If multiple paths are present in the Route,
1462 /// we assume the invoice had the basic_mpp feature set.
1463 pub fn send_payment(&self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>) -> Result<(), PaymentSendFailure> {
1464 if route.paths.len() < 1 {
1465 return Err(PaymentSendFailure::ParameterError(APIError::RouteError{err: "There must be at least one path to send over"}));
1467 if route.paths.len() > 10 {
1468 // This limit is completely arbitrary - there aren't any real fundamental path-count
1469 // limits. After we support retrying individual paths we should likely bump this, but
1470 // for now more than 10 paths likely carries too much one-path failure.
1471 return Err(PaymentSendFailure::ParameterError(APIError::RouteError{err: "Sending over more than 10 paths is not currently supported"}));
1473 let mut total_value = 0;
1474 let our_node_id = self.get_our_node_id();
1475 let mut path_errs = Vec::with_capacity(route.paths.len());
1476 'path_check: for path in route.paths.iter() {
1477 if path.len() < 1 || path.len() > 20 {
1478 path_errs.push(Err(APIError::RouteError{err: "Path didn't go anywhere/had bogus size"}));
1479 continue 'path_check;
1481 for (idx, hop) in path.iter().enumerate() {
1482 if idx != path.len() - 1 && hop.pubkey == our_node_id {
1483 path_errs.push(Err(APIError::RouteError{err: "Path went through us but wasn't a simple rebalance loop to us"}));
1484 continue 'path_check;
1487 total_value += path.last().unwrap().fee_msat;
1488 path_errs.push(Ok(()));
1490 if path_errs.iter().any(|e| e.is_err()) {
1491 return Err(PaymentSendFailure::PathParameterError(path_errs));
1494 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1495 let mut results = Vec::new();
1496 for path in route.paths.iter() {
1497 results.push(self.send_payment_along_path(&path, &payment_hash, payment_secret, total_value, cur_height));
1499 let mut has_ok = false;
1500 let mut has_err = false;
1501 for res in results.iter() {
1502 if res.is_ok() { has_ok = true; }
1503 if res.is_err() { has_err = true; }
1504 if let &Err(APIError::MonitorUpdateFailed) = res {
1505 // MonitorUpdateFailed is inherently unsafe to retry, so we call it a
1512 if has_err && has_ok {
1513 Err(PaymentSendFailure::PartialFailure(results))
1515 Err(PaymentSendFailure::AllFailedRetrySafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1521 /// Call this upon creation of a funding transaction for the given channel.
1523 /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1524 /// or your counterparty can steal your funds!
1526 /// Panics if a funding transaction has already been provided for this channel.
1528 /// May panic if the funding_txo is duplicative with some other channel (note that this should
1529 /// be trivially prevented by using unique funding transaction keys per-channel).
1530 pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1531 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1534 let (res, chan) = match self.channel_state.lock().unwrap().by_id.remove(temporary_channel_id) {
1536 (chan.get_outbound_funding_created(funding_txo, &self.logger)
1537 .map_err(|e| if let ChannelError::Close(msg) = e {
1538 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(true), None)
1539 } else { unreachable!(); })
1544 match handle_error!(self, res, chan.get_counterparty_node_id()) {
1545 Ok(funding_msg) => {
1548 Err(_) => { return; }
1552 let mut channel_state = self.channel_state.lock().unwrap();
1553 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1554 node_id: chan.get_counterparty_node_id(),
1557 match channel_state.by_id.entry(chan.channel_id()) {
1558 hash_map::Entry::Occupied(_) => {
1559 panic!("Generated duplicate funding txid?");
1561 hash_map::Entry::Vacant(e) => {
1567 fn get_announcement_sigs(&self, chan: &Channel<Signer>) -> Option<msgs::AnnouncementSignatures> {
1568 if !chan.should_announce() {
1569 log_trace!(self.logger, "Can't send announcement_signatures for private channel {}", log_bytes!(chan.channel_id()));
1573 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1575 Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1577 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1578 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1580 Some(msgs::AnnouncementSignatures {
1581 channel_id: chan.channel_id(),
1582 short_channel_id: chan.get_short_channel_id().unwrap(),
1583 node_signature: our_node_sig,
1584 bitcoin_signature: our_bitcoin_sig,
1589 // Messages of up to 64KB should never end up more than half full with addresses, as that would
1590 // be absurd. We ensure this by checking that at least 500 (our stated public contract on when
1591 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
1593 const HALF_MESSAGE_IS_ADDRS: u32 = ::std::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
1596 // ...by failing to compile if the number of addresses that would be half of a message is
1597 // smaller than 500:
1598 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 500;
1600 /// Generates a signed node_announcement from the given arguments and creates a
1601 /// BroadcastNodeAnnouncement event. Note that such messages will be ignored unless peers have
1602 /// seen a channel_announcement from us (ie unless we have public channels open).
1604 /// RGB is a node "color" and alias is a printable human-readable string to describe this node
1605 /// to humans. They carry no in-protocol meaning.
1607 /// addresses represent the set (possibly empty) of socket addresses on which this node accepts
1608 /// incoming connections. These will be broadcast to the network, publicly tying these
1609 /// addresses together. If you wish to preserve user privacy, addresses should likely contain
1610 /// only Tor Onion addresses.
1612 /// Panics if addresses is absurdly large (more than 500).
1613 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: Vec<NetAddress>) {
1614 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1616 if addresses.len() > 500 {
1617 panic!("More than half the message size was taken up by public addresses!");
1620 let announcement = msgs::UnsignedNodeAnnouncement {
1621 features: NodeFeatures::known(),
1622 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1623 node_id: self.get_our_node_id(),
1624 rgb, alias, addresses,
1625 excess_address_data: Vec::new(),
1626 excess_data: Vec::new(),
1628 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1630 let mut channel_state = self.channel_state.lock().unwrap();
1631 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
1632 msg: msgs::NodeAnnouncement {
1633 signature: self.secp_ctx.sign(&msghash, &self.our_network_key),
1634 contents: announcement
1639 /// Processes HTLCs which are pending waiting on random forward delay.
1641 /// Should only really ever be called in response to a PendingHTLCsForwardable event.
1642 /// Will likely generate further events.
1643 pub fn process_pending_htlc_forwards(&self) {
1644 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1646 let mut new_events = Vec::new();
1647 let mut failed_forwards = Vec::new();
1648 let mut handle_errors = Vec::new();
1650 let mut channel_state_lock = self.channel_state.lock().unwrap();
1651 let channel_state = &mut *channel_state_lock;
1653 for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1654 if short_chan_id != 0 {
1655 let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1656 Some(chan_id) => chan_id.clone(),
1658 failed_forwards.reserve(pending_forwards.len());
1659 for forward_info in pending_forwards.drain(..) {
1660 match forward_info {
1661 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info,
1662 prev_funding_outpoint } => {
1663 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1664 short_channel_id: prev_short_channel_id,
1665 outpoint: prev_funding_outpoint,
1666 htlc_id: prev_htlc_id,
1667 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1669 failed_forwards.push((htlc_source, forward_info.payment_hash,
1670 HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() }
1673 HTLCForwardInfo::FailHTLC { .. } => {
1674 // Channel went away before we could fail it. This implies
1675 // the channel is now on chain and our counterparty is
1676 // trying to broadcast the HTLC-Timeout, but that's their
1677 // problem, not ours.
1684 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(forward_chan_id) {
1685 let mut add_htlc_msgs = Vec::new();
1686 let mut fail_htlc_msgs = Vec::new();
1687 for forward_info in pending_forwards.drain(..) {
1688 match forward_info {
1689 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1690 routing: PendingHTLCRouting::Forward {
1692 }, incoming_shared_secret, payment_hash, amt_to_forward, outgoing_cltv_value },
1693 prev_funding_outpoint } => {
1694 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);
1695 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1696 short_channel_id: prev_short_channel_id,
1697 outpoint: prev_funding_outpoint,
1698 htlc_id: prev_htlc_id,
1699 incoming_packet_shared_secret: incoming_shared_secret,
1701 match chan.get_mut().send_htlc(amt_to_forward, payment_hash, outgoing_cltv_value, htlc_source.clone(), onion_packet) {
1703 if let ChannelError::Ignore(msg) = e {
1704 log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
1706 panic!("Stated return value requirements in send_htlc() were not met");
1708 let chan_update = self.get_channel_update(chan.get()).unwrap();
1709 failed_forwards.push((htlc_source, payment_hash,
1710 HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.encode_with_len() }
1716 Some(msg) => { add_htlc_msgs.push(msg); },
1718 // Nothing to do here...we're waiting on a remote
1719 // revoke_and_ack before we can add anymore HTLCs. The Channel
1720 // will automatically handle building the update_add_htlc and
1721 // commitment_signed messages when we can.
1722 // TODO: Do some kind of timer to set the channel as !is_live()
1723 // as we don't really want others relying on us relaying through
1724 // this channel currently :/.
1730 HTLCForwardInfo::AddHTLC { .. } => {
1731 panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
1733 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
1734 log_trace!(self.logger, "Failing HTLC back to channel with short id {} after delay", short_chan_id);
1735 match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet) {
1737 if let ChannelError::Ignore(msg) = e {
1738 log_trace!(self.logger, "Failed to fail backwards to short_id {}: {}", short_chan_id, msg);
1740 panic!("Stated return value requirements in get_update_fail_htlc() were not met");
1742 // fail-backs are best-effort, we probably already have one
1743 // pending, and if not that's OK, if not, the channel is on
1744 // the chain and sending the HTLC-Timeout is their problem.
1747 Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
1749 // Nothing to do here...we're waiting on a remote
1750 // revoke_and_ack before we can update the commitment
1751 // transaction. The Channel will automatically handle
1752 // building the update_fail_htlc and commitment_signed
1753 // messages when we can.
1754 // We don't need any kind of timer here as they should fail
1755 // the channel onto the chain if they can't get our
1756 // update_fail_htlc in time, it's not our problem.
1763 if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
1764 let (commitment_msg, monitor_update) = match chan.get_mut().send_commitment(&self.logger) {
1767 // We surely failed send_commitment due to bad keys, in that case
1768 // close channel and then send error message to peer.
1769 let counterparty_node_id = chan.get().get_counterparty_node_id();
1770 let err: Result<(), _> = match e {
1771 ChannelError::Ignore(_) => {
1772 panic!("Stated return value requirements in send_commitment() were not met");
1774 ChannelError::Close(msg) => {
1775 log_trace!(self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
1776 let (channel_id, mut channel) = chan.remove_entry();
1777 if let Some(short_id) = channel.get_short_channel_id() {
1778 channel_state.short_to_id.remove(&short_id);
1780 Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, channel.force_shutdown(true), self.get_channel_update(&channel).ok()))
1782 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"); }
1784 handle_errors.push((counterparty_node_id, err));
1788 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
1789 handle_errors.push((chan.get().get_counterparty_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
1792 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1793 node_id: chan.get().get_counterparty_node_id(),
1794 updates: msgs::CommitmentUpdate {
1795 update_add_htlcs: add_htlc_msgs,
1796 update_fulfill_htlcs: Vec::new(),
1797 update_fail_htlcs: fail_htlc_msgs,
1798 update_fail_malformed_htlcs: Vec::new(),
1800 commitment_signed: commitment_msg,
1808 for forward_info in pending_forwards.drain(..) {
1809 match forward_info {
1810 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1811 routing: PendingHTLCRouting::Receive { payment_data, incoming_cltv_expiry },
1812 incoming_shared_secret, payment_hash, amt_to_forward, .. },
1813 prev_funding_outpoint } => {
1814 let prev_hop = HTLCPreviousHopData {
1815 short_channel_id: prev_short_channel_id,
1816 outpoint: prev_funding_outpoint,
1817 htlc_id: prev_htlc_id,
1818 incoming_packet_shared_secret: incoming_shared_secret,
1821 let mut total_value = 0;
1822 let payment_secret_opt =
1823 if let &Some(ref data) = &payment_data { Some(data.payment_secret.clone()) } else { None };
1824 let htlcs = channel_state.claimable_htlcs.entry((payment_hash, payment_secret_opt))
1825 .or_insert(Vec::new());
1826 htlcs.push(ClaimableHTLC {
1828 value: amt_to_forward,
1829 payment_data: payment_data.clone(),
1830 cltv_expiry: incoming_cltv_expiry,
1832 if let &Some(ref data) = &payment_data {
1833 for htlc in htlcs.iter() {
1834 total_value += htlc.value;
1835 if htlc.payment_data.as_ref().unwrap().total_msat != data.total_msat {
1836 total_value = msgs::MAX_VALUE_MSAT;
1838 if total_value >= msgs::MAX_VALUE_MSAT { break; }
1840 if total_value >= msgs::MAX_VALUE_MSAT || total_value > data.total_msat {
1841 for htlc in htlcs.iter() {
1842 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
1843 htlc_msat_height_data.extend_from_slice(
1844 &byte_utils::be32_to_array(
1845 self.latest_block_height.load(Ordering::Acquire)
1849 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
1850 short_channel_id: htlc.prev_hop.short_channel_id,
1851 outpoint: prev_funding_outpoint,
1852 htlc_id: htlc.prev_hop.htlc_id,
1853 incoming_packet_shared_secret: htlc.prev_hop.incoming_packet_shared_secret,
1855 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data }
1858 } else if total_value == data.total_msat {
1859 new_events.push(events::Event::PaymentReceived {
1861 payment_secret: Some(data.payment_secret),
1866 new_events.push(events::Event::PaymentReceived {
1868 payment_secret: None,
1869 amt: amt_to_forward,
1873 HTLCForwardInfo::AddHTLC { .. } => {
1874 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
1876 HTLCForwardInfo::FailHTLC { .. } => {
1877 panic!("Got pending fail of our own HTLC");
1885 for (htlc_source, payment_hash, failure_reason) in failed_forwards.drain(..) {
1886 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, failure_reason);
1889 for (counterparty_node_id, err) in handle_errors.drain(..) {
1890 let _ = handle_error!(self, err, counterparty_node_id);
1893 if new_events.is_empty() { return }
1894 let mut events = self.pending_events.lock().unwrap();
1895 events.append(&mut new_events);
1898 /// Free the background events, generally called from timer_chan_freshness_every_min.
1900 /// Exposed for testing to allow us to process events quickly without generating accidental
1901 /// BroadcastChannelUpdate events in timer_chan_freshness_every_min.
1903 /// Expects the caller to have a total_consistency_lock read lock.
1904 fn process_background_events(&self) {
1905 let mut background_events = Vec::new();
1906 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
1907 for event in background_events.drain(..) {
1909 BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)) => {
1910 // The channel has already been closed, so no use bothering to care about the
1911 // monitor updating completing.
1912 let _ = self.chain_monitor.update_channel(funding_txo, update);
1918 #[cfg(any(test, feature = "_test_utils"))]
1919 pub(crate) fn test_process_background_events(&self) {
1920 self.process_background_events();
1923 /// If a peer is disconnected we mark any channels with that peer as 'disabled'.
1924 /// After some time, if channels are still disabled we need to broadcast a ChannelUpdate
1925 /// to inform the network about the uselessness of these channels.
1927 /// This method handles all the details, and must be called roughly once per minute.
1929 /// Note that in some rare cases this may generate a `chain::Watch::update_channel` call.
1930 pub fn timer_chan_freshness_every_min(&self) {
1931 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1932 self.process_background_events();
1934 let mut channel_state_lock = self.channel_state.lock().unwrap();
1935 let channel_state = &mut *channel_state_lock;
1936 for (_, chan) in channel_state.by_id.iter_mut() {
1937 if chan.is_disabled_staged() && !chan.is_live() {
1938 if let Ok(update) = self.get_channel_update(&chan) {
1939 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1944 } else if chan.is_disabled_staged() && chan.is_live() {
1946 } else if chan.is_disabled_marked() {
1947 chan.to_disabled_staged();
1952 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1953 /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
1954 /// along the path (including in our own channel on which we received it).
1955 /// Returns false if no payment was found to fail backwards, true if the process of failing the
1956 /// HTLC backwards has been started.
1957 pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, payment_secret: &Option<PaymentSecret>) -> bool {
1958 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1960 let mut channel_state = Some(self.channel_state.lock().unwrap());
1961 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(*payment_hash, *payment_secret));
1962 if let Some(mut sources) = removed_source {
1963 for htlc in sources.drain(..) {
1964 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1965 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
1966 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
1967 self.latest_block_height.load(Ordering::Acquire) as u32,
1969 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1970 HTLCSource::PreviousHopData(htlc.prev_hop), payment_hash,
1971 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data });
1977 // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
1978 // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
1979 // be surfaced to the user.
1980 fn fail_holding_cell_htlcs(&self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: [u8; 32]) {
1981 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
1983 HTLCSource::PreviousHopData(HTLCPreviousHopData { .. }) => {
1984 let (failure_code, onion_failure_data) =
1985 match self.channel_state.lock().unwrap().by_id.entry(channel_id) {
1986 hash_map::Entry::Occupied(chan_entry) => {
1987 if let Ok(upd) = self.get_channel_update(&chan_entry.get()) {
1988 (0x1000|7, upd.encode_with_len())
1990 (0x4000|10, Vec::new())
1993 hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
1995 let channel_state = self.channel_state.lock().unwrap();
1996 self.fail_htlc_backwards_internal(channel_state,
1997 htlc_src, &payment_hash, HTLCFailReason::Reason { failure_code, data: onion_failure_data});
1999 HTLCSource::OutboundRoute { .. } => {
2000 self.pending_events.lock().unwrap().push(
2001 events::Event::PaymentFailed {
2003 rejected_by_dest: false,
2015 /// Fails an HTLC backwards to the sender of it to us.
2016 /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
2017 /// There are several callsites that do stupid things like loop over a list of payment_hashes
2018 /// to fail and take the channel_state lock for each iteration (as we take ownership and may
2019 /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
2020 /// still-available channels.
2021 fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
2022 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
2023 //identify whether we sent it or not based on the (I presume) very different runtime
2024 //between the branches here. We should make this async and move it into the forward HTLCs
2027 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
2028 // from block_connected which may run during initialization prior to the chain_monitor
2029 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
2031 HTLCSource::OutboundRoute { ref path, .. } => {
2032 log_trace!(self.logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
2033 mem::drop(channel_state_lock);
2034 match &onion_error {
2035 &HTLCFailReason::LightningError { ref err } => {
2037 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());
2039 let (channel_update, payment_retryable, _, _) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
2040 // TODO: If we decided to blame ourselves (or one of our channels) in
2041 // process_onion_failure we should close that channel as it implies our
2042 // next-hop is needlessly blaming us!
2043 if let Some(update) = channel_update {
2044 self.channel_state.lock().unwrap().pending_msg_events.push(
2045 events::MessageSendEvent::PaymentFailureNetworkUpdate {
2050 self.pending_events.lock().unwrap().push(
2051 events::Event::PaymentFailed {
2052 payment_hash: payment_hash.clone(),
2053 rejected_by_dest: !payment_retryable,
2055 error_code: onion_error_code,
2057 error_data: onion_error_data
2061 &HTLCFailReason::Reason {
2067 // we get a fail_malformed_htlc from the first hop
2068 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
2069 // failures here, but that would be insufficient as get_route
2070 // generally ignores its view of our own channels as we provide them via
2072 // TODO: For non-temporary failures, we really should be closing the
2073 // channel here as we apparently can't relay through them anyway.
2074 self.pending_events.lock().unwrap().push(
2075 events::Event::PaymentFailed {
2076 payment_hash: payment_hash.clone(),
2077 rejected_by_dest: path.len() == 1,
2079 error_code: Some(*failure_code),
2081 error_data: Some(data.clone()),
2087 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret, .. }) => {
2088 let err_packet = match onion_error {
2089 HTLCFailReason::Reason { failure_code, data } => {
2090 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
2091 let packet = onion_utils::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
2092 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
2094 HTLCFailReason::LightningError { err } => {
2095 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards with pre-built LightningError", log_bytes!(payment_hash.0));
2096 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
2100 let mut forward_event = None;
2101 if channel_state_lock.forward_htlcs.is_empty() {
2102 forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
2104 match channel_state_lock.forward_htlcs.entry(short_channel_id) {
2105 hash_map::Entry::Occupied(mut entry) => {
2106 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id, err_packet });
2108 hash_map::Entry::Vacant(entry) => {
2109 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id, err_packet }));
2112 mem::drop(channel_state_lock);
2113 if let Some(time) = forward_event {
2114 let mut pending_events = self.pending_events.lock().unwrap();
2115 pending_events.push(events::Event::PendingHTLCsForwardable {
2116 time_forwardable: time
2123 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
2124 /// generating message events for the net layer to claim the payment, if possible. Thus, you
2125 /// should probably kick the net layer to go send messages if this returns true!
2127 /// You must specify the expected amounts for this HTLC, and we will only claim HTLCs
2128 /// available within a few percent of the expected amount. This is critical for several
2129 /// reasons : a) it avoids providing senders with `proof-of-payment` (in the form of the
2130 /// payment_preimage without having provided the full value and b) it avoids certain
2131 /// privacy-breaking recipient-probing attacks which may reveal payment activity to
2132 /// motivated attackers.
2134 /// Note that the privacy concerns in (b) are not relevant in payments with a payment_secret
2135 /// set. Thus, for such payments we will claim any payments which do not under-pay.
2137 /// May panic if called except in response to a PaymentReceived event.
2138 pub fn claim_funds(&self, payment_preimage: PaymentPreimage, payment_secret: &Option<PaymentSecret>, expected_amount: u64) -> bool {
2139 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
2141 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
2143 let mut channel_state = Some(self.channel_state.lock().unwrap());
2144 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(payment_hash, *payment_secret));
2145 if let Some(mut sources) = removed_source {
2146 assert!(!sources.is_empty());
2148 // If we are claiming an MPP payment, we have to take special care to ensure that each
2149 // channel exists before claiming all of the payments (inside one lock).
2150 // Note that channel existance is sufficient as we should always get a monitor update
2151 // which will take care of the real HTLC claim enforcement.
2153 // If we find an HTLC which we would need to claim but for which we do not have a
2154 // channel, we will fail all parts of the MPP payment. While we could wait and see if
2155 // the sender retries the already-failed path(s), it should be a pretty rare case where
2156 // we got all the HTLCs and then a channel closed while we were waiting for the user to
2157 // provide the preimage, so worrying too much about the optimal handling isn't worth
2160 let (is_mpp, mut valid_mpp) = if let &Some(ref data) = &sources[0].payment_data {
2161 assert!(payment_secret.is_some());
2162 (true, data.total_msat >= expected_amount)
2164 assert!(payment_secret.is_none());
2168 for htlc in sources.iter() {
2169 if !is_mpp || !valid_mpp { break; }
2170 if let None = channel_state.as_ref().unwrap().short_to_id.get(&htlc.prev_hop.short_channel_id) {
2175 let mut errs = Vec::new();
2176 let mut claimed_any_htlcs = false;
2177 for htlc in sources.drain(..) {
2178 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
2179 if (is_mpp && !valid_mpp) || (!is_mpp && (htlc.value < expected_amount || htlc.value > expected_amount * 2)) {
2180 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
2181 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
2182 self.latest_block_height.load(Ordering::Acquire) as u32,
2184 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
2185 HTLCSource::PreviousHopData(htlc.prev_hop), &payment_hash,
2186 HTLCFailReason::Reason { failure_code: 0x4000|15, data: htlc_msat_height_data });
2188 match self.claim_funds_from_hop(channel_state.as_mut().unwrap(), htlc.prev_hop, payment_preimage) {
2190 if let msgs::ErrorAction::IgnoreError = e.1.err.action {
2191 // We got a temporary failure updating monitor, but will claim the
2192 // HTLC when the monitor updating is restored (or on chain).
2193 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", e.1.err.err);
2194 claimed_any_htlcs = true;
2195 } else { errs.push(e); }
2197 Err(None) if is_mpp => unreachable!("We already checked for channel existence, we can't fail here!"),
2199 log_warn!(self.logger, "Channel we expected to claim an HTLC from was closed.");
2201 Ok(()) => claimed_any_htlcs = true,
2206 // Now that we've done the entire above loop in one lock, we can handle any errors
2207 // which were generated.
2208 channel_state.take();
2210 for (counterparty_node_id, err) in errs.drain(..) {
2211 let res: Result<(), _> = Err(err);
2212 let _ = handle_error!(self, res, counterparty_node_id);
2219 fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard<ChannelHolder<Signer>>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> Result<(), Option<(PublicKey, MsgHandleErrInternal)>> {
2220 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
2221 let channel_state = &mut **channel_state_lock;
2222 let chan_id = match channel_state.short_to_id.get(&prev_hop.short_channel_id) {
2223 Some(chan_id) => chan_id.clone(),
2229 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(chan_id) {
2230 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2231 match chan.get_mut().get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger) {
2232 Ok((msgs, monitor_option)) => {
2233 if let Some(monitor_update) = monitor_option {
2234 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2235 if was_frozen_for_monitor {
2236 assert!(msgs.is_none());
2238 return Err(Some((chan.get().get_counterparty_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, msgs.is_some()).unwrap_err())));
2242 if let Some((msg, commitment_signed)) = msgs {
2243 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2244 node_id: chan.get().get_counterparty_node_id(),
2245 updates: msgs::CommitmentUpdate {
2246 update_add_htlcs: Vec::new(),
2247 update_fulfill_htlcs: vec![msg],
2248 update_fail_htlcs: Vec::new(),
2249 update_fail_malformed_htlcs: Vec::new(),
2258 // TODO: Do something with e?
2259 // This should only occur if we are claiming an HTLC at the same time as the
2260 // HTLC is being failed (eg because a block is being connected and this caused
2261 // an HTLC to time out). This should, of course, only occur if the user is the
2262 // one doing the claiming (as it being a part of a peer claim would imply we're
2263 // about to lose funds) and only if the lock in claim_funds was dropped as a
2264 // previous HTLC was failed (thus not for an MPP payment).
2265 debug_assert!(false, "This shouldn't be reachable except in absurdly rare cases between monitor updates and HTLC timeouts: {:?}", e);
2269 } else { unreachable!(); }
2272 fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_preimage: PaymentPreimage) {
2274 HTLCSource::OutboundRoute { .. } => {
2275 mem::drop(channel_state_lock);
2276 let mut pending_events = self.pending_events.lock().unwrap();
2277 pending_events.push(events::Event::PaymentSent {
2281 HTLCSource::PreviousHopData(hop_data) => {
2282 let prev_outpoint = hop_data.outpoint;
2283 if let Err((counterparty_node_id, err)) = match self.claim_funds_from_hop(&mut channel_state_lock, hop_data, payment_preimage) {
2286 let preimage_update = ChannelMonitorUpdate {
2287 update_id: CLOSED_CHANNEL_UPDATE_ID,
2288 updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
2289 payment_preimage: payment_preimage.clone(),
2292 // We update the ChannelMonitor on the backward link, after
2293 // receiving an offchain preimage event from the forward link (the
2294 // event being update_fulfill_htlc).
2295 if let Err(e) = self.chain_monitor.update_channel(prev_outpoint, preimage_update) {
2296 log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
2297 payment_preimage, e);
2301 Err(Some(res)) => Err(res),
2303 mem::drop(channel_state_lock);
2304 let res: Result<(), _> = Err(err);
2305 let _ = handle_error!(self, res, counterparty_node_id);
2311 /// Gets the node_id held by this ChannelManager
2312 pub fn get_our_node_id(&self) -> PublicKey {
2313 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
2316 /// Restores a single, given channel to normal operation after a
2317 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
2320 /// All ChannelMonitor updates up to and including highest_applied_update_id must have been
2321 /// fully committed in every copy of the given channels' ChannelMonitors.
2323 /// Note that there is no effect to calling with a highest_applied_update_id other than the
2324 /// current latest ChannelMonitorUpdate and one call to this function after multiple
2325 /// ChannelMonitorUpdateErr::TemporaryFailures is fine. The highest_applied_update_id field
2326 /// exists largely only to prevent races between this and concurrent update_monitor calls.
2328 /// Thus, the anticipated use is, at a high level:
2329 /// 1) You register a chain::Watch with this ChannelManager,
2330 /// 2) it stores each update to disk, and begins updating any remote (eg watchtower) copies of
2331 /// said ChannelMonitors as it can, returning ChannelMonitorUpdateErr::TemporaryFailures
2332 /// any time it cannot do so instantly,
2333 /// 3) update(s) are applied to each remote copy of a ChannelMonitor,
2334 /// 4) once all remote copies are updated, you call this function with the update_id that
2335 /// completed, and once it is the latest the Channel will be re-enabled.
2336 pub fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64) {
2337 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
2339 let mut close_results = Vec::new();
2340 let mut htlc_forwards = Vec::new();
2341 let mut htlc_failures = Vec::new();
2342 let mut pending_events = Vec::new();
2345 let mut channel_lock = self.channel_state.lock().unwrap();
2346 let channel_state = &mut *channel_lock;
2347 let short_to_id = &mut channel_state.short_to_id;
2348 let pending_msg_events = &mut channel_state.pending_msg_events;
2349 let channel = match channel_state.by_id.get_mut(&funding_txo.to_channel_id()) {
2353 if !channel.is_awaiting_monitor_update() || channel.get_latest_monitor_update_id() != highest_applied_update_id {
2357 let (raa, commitment_update, order, pending_forwards, mut pending_failures, needs_broadcast_safe, funding_locked) = channel.monitor_updating_restored(&self.logger);
2358 if !pending_forwards.is_empty() {
2359 htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), funding_txo.clone(), pending_forwards));
2361 htlc_failures.append(&mut pending_failures);
2363 macro_rules! handle_cs { () => {
2364 if let Some(update) = commitment_update {
2365 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2366 node_id: channel.get_counterparty_node_id(),
2371 macro_rules! handle_raa { () => {
2372 if let Some(revoke_and_ack) = raa {
2373 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2374 node_id: channel.get_counterparty_node_id(),
2375 msg: revoke_and_ack,
2380 RAACommitmentOrder::CommitmentFirst => {
2384 RAACommitmentOrder::RevokeAndACKFirst => {
2389 if needs_broadcast_safe {
2390 pending_events.push(events::Event::FundingBroadcastSafe {
2391 funding_txo: channel.get_funding_txo().unwrap(),
2392 user_channel_id: channel.get_user_id(),
2395 if let Some(msg) = funding_locked {
2396 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2397 node_id: channel.get_counterparty_node_id(),
2400 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2401 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2402 node_id: channel.get_counterparty_node_id(),
2403 msg: announcement_sigs,
2406 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2410 self.pending_events.lock().unwrap().append(&mut pending_events);
2412 for failure in htlc_failures.drain(..) {
2413 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2415 self.forward_htlcs(&mut htlc_forwards[..]);
2417 for res in close_results.drain(..) {
2418 self.finish_force_close_channel(res);
2422 fn internal_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
2423 if msg.chain_hash != self.genesis_hash {
2424 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
2427 let channel = Channel::new_from_req(&self.fee_estimator, &self.keys_manager, counterparty_node_id.clone(), their_features, msg, 0, &self.default_configuration)
2428 .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
2429 let mut channel_state_lock = self.channel_state.lock().unwrap();
2430 let channel_state = &mut *channel_state_lock;
2431 match channel_state.by_id.entry(channel.channel_id()) {
2432 hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!".to_owned(), msg.temporary_channel_id.clone())),
2433 hash_map::Entry::Vacant(entry) => {
2434 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
2435 node_id: counterparty_node_id.clone(),
2436 msg: channel.get_accept_channel(),
2438 entry.insert(channel);
2444 fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
2445 let (value, output_script, user_id) = {
2446 let mut channel_lock = self.channel_state.lock().unwrap();
2447 let channel_state = &mut *channel_lock;
2448 match channel_state.by_id.entry(msg.temporary_channel_id) {
2449 hash_map::Entry::Occupied(mut chan) => {
2450 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2451 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
2453 try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration, their_features), channel_state, chan);
2454 (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
2456 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
2459 let mut pending_events = self.pending_events.lock().unwrap();
2460 pending_events.push(events::Event::FundingGenerationReady {
2461 temporary_channel_id: msg.temporary_channel_id,
2462 channel_value_satoshis: value,
2464 user_channel_id: user_id,
2469 fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
2470 let ((funding_msg, monitor), mut chan) = {
2471 let last_block_hash = *self.last_block_hash.read().unwrap();
2472 let mut channel_lock = self.channel_state.lock().unwrap();
2473 let channel_state = &mut *channel_lock;
2474 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
2475 hash_map::Entry::Occupied(mut chan) => {
2476 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2477 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
2479 (try_chan_entry!(self, chan.get_mut().funding_created(msg, last_block_hash, &self.logger), channel_state, chan), chan.remove())
2481 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
2484 // Because we have exclusive ownership of the channel here we can release the channel_state
2485 // lock before watch_channel
2486 if let Err(e) = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor) {
2488 ChannelMonitorUpdateErr::PermanentFailure => {
2489 // Note that we reply with the new channel_id in error messages if we gave up on the
2490 // channel, not the temporary_channel_id. This is compatible with ourselves, but the
2491 // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
2492 // any messages referencing a previously-closed channel anyway.
2493 // We do not do a force-close here as that would generate a monitor update for
2494 // a monitor that we didn't manage to store (and that we don't care about - we
2495 // don't respond with the funding_signed so the channel can never go on chain).
2496 let (_monitor_update, failed_htlcs) = chan.force_shutdown(true);
2497 assert!(failed_htlcs.is_empty());
2498 return Err(MsgHandleErrInternal::send_err_msg_no_close("ChannelMonitor storage failure".to_owned(), funding_msg.channel_id));
2500 ChannelMonitorUpdateErr::TemporaryFailure => {
2501 // There's no problem signing a counterparty's funding transaction if our monitor
2502 // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
2503 // accepted payment from yet. We do, however, need to wait to send our funding_locked
2504 // until we have persisted our monitor.
2505 chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
2509 let mut channel_state_lock = self.channel_state.lock().unwrap();
2510 let channel_state = &mut *channel_state_lock;
2511 match channel_state.by_id.entry(funding_msg.channel_id) {
2512 hash_map::Entry::Occupied(_) => {
2513 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
2515 hash_map::Entry::Vacant(e) => {
2516 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
2517 node_id: counterparty_node_id.clone(),
2526 fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
2527 let (funding_txo, user_id) = {
2528 let last_block_hash = *self.last_block_hash.read().unwrap();
2529 let mut channel_lock = self.channel_state.lock().unwrap();
2530 let channel_state = &mut *channel_lock;
2531 match channel_state.by_id.entry(msg.channel_id) {
2532 hash_map::Entry::Occupied(mut chan) => {
2533 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2534 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2536 let monitor = match chan.get_mut().funding_signed(&msg, last_block_hash, &self.logger) {
2537 Ok(update) => update,
2538 Err(e) => try_chan_entry!(self, Err(e), channel_state, chan),
2540 if let Err(e) = self.chain_monitor.watch_channel(chan.get().get_funding_txo().unwrap(), monitor) {
2541 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
2543 (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
2545 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2548 let mut pending_events = self.pending_events.lock().unwrap();
2549 pending_events.push(events::Event::FundingBroadcastSafe {
2551 user_channel_id: user_id,
2556 fn internal_funding_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
2557 let mut channel_state_lock = self.channel_state.lock().unwrap();
2558 let channel_state = &mut *channel_state_lock;
2559 match channel_state.by_id.entry(msg.channel_id) {
2560 hash_map::Entry::Occupied(mut chan) => {
2561 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2562 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2564 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
2565 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
2566 log_trace!(self.logger, "Sending announcement_signatures for {} in response to funding_locked", log_bytes!(chan.get().channel_id()));
2567 // If we see locking block before receiving remote funding_locked, we broadcast our
2568 // announcement_sigs at remote funding_locked reception. If we receive remote
2569 // funding_locked before seeing locking block, we broadcast our announcement_sigs at locking
2570 // block connection. We should guanrantee to broadcast announcement_sigs to our peer whatever
2571 // the order of the events but our peer may not receive it due to disconnection. The specs
2572 // lacking an acknowledgement for announcement_sigs we may have to re-send them at peer
2573 // connection in the future if simultaneous misses by both peers due to network/hardware
2574 // failures is an issue. Note, to achieve its goal, only one of the announcement_sigs needs
2575 // to be received, from then sigs are going to be flood to the whole network.
2576 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2577 node_id: counterparty_node_id.clone(),
2578 msg: announcement_sigs,
2583 hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2587 fn internal_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
2588 let (mut dropped_htlcs, chan_option) = {
2589 let mut channel_state_lock = self.channel_state.lock().unwrap();
2590 let channel_state = &mut *channel_state_lock;
2592 match channel_state.by_id.entry(msg.channel_id.clone()) {
2593 hash_map::Entry::Occupied(mut chan_entry) => {
2594 if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
2595 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2597 let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&self.fee_estimator, &their_features, &msg), channel_state, chan_entry);
2598 if let Some(msg) = shutdown {
2599 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2600 node_id: counterparty_node_id.clone(),
2604 if let Some(msg) = closing_signed {
2605 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2606 node_id: counterparty_node_id.clone(),
2610 if chan_entry.get().is_shutdown() {
2611 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2612 channel_state.short_to_id.remove(&short_id);
2614 (dropped_htlcs, Some(chan_entry.remove_entry().1))
2615 } else { (dropped_htlcs, None) }
2617 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2620 for htlc_source in dropped_htlcs.drain(..) {
2621 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() });
2623 if let Some(chan) = chan_option {
2624 if let Ok(update) = self.get_channel_update(&chan) {
2625 let mut channel_state = self.channel_state.lock().unwrap();
2626 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2634 fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
2635 let (tx, chan_option) = {
2636 let mut channel_state_lock = self.channel_state.lock().unwrap();
2637 let channel_state = &mut *channel_state_lock;
2638 match channel_state.by_id.entry(msg.channel_id.clone()) {
2639 hash_map::Entry::Occupied(mut chan_entry) => {
2640 if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
2641 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2643 let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&self.fee_estimator, &msg), channel_state, chan_entry);
2644 if let Some(msg) = closing_signed {
2645 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2646 node_id: counterparty_node_id.clone(),
2651 // We're done with this channel, we've got a signed closing transaction and
2652 // will send the closing_signed back to the remote peer upon return. This
2653 // also implies there are no pending HTLCs left on the channel, so we can
2654 // fully delete it from tracking (the channel monitor is still around to
2655 // watch for old state broadcasts)!
2656 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2657 channel_state.short_to_id.remove(&short_id);
2659 (tx, Some(chan_entry.remove_entry().1))
2660 } else { (tx, None) }
2662 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2665 if let Some(broadcast_tx) = tx {
2666 log_trace!(self.logger, "Broadcast onchain {}", log_tx!(broadcast_tx));
2667 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2669 if let Some(chan) = chan_option {
2670 if let Ok(update) = self.get_channel_update(&chan) {
2671 let mut channel_state = self.channel_state.lock().unwrap();
2672 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2680 fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2681 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2682 //determine the state of the payment based on our response/if we forward anything/the time
2683 //we take to respond. We should take care to avoid allowing such an attack.
2685 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2686 //us repeatedly garbled in different ways, and compare our error messages, which are
2687 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
2688 //but we should prevent it anyway.
2690 let (pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2691 let channel_state = &mut *channel_state_lock;
2693 match channel_state.by_id.entry(msg.channel_id) {
2694 hash_map::Entry::Occupied(mut chan) => {
2695 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2696 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2699 let create_pending_htlc_status = |chan: &Channel<Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
2700 // Ensure error_code has the UPDATE flag set, since by default we send a
2701 // channel update along as part of failing the HTLC.
2702 assert!((error_code & 0x1000) != 0);
2703 // If the update_add is completely bogus, the call will Err and we will close,
2704 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2705 // want to reject the new HTLC and fail it backwards instead of forwarding.
2706 match pending_forward_info {
2707 PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
2708 let reason = if let Ok(upd) = self.get_channel_update(chan) {
2709 onion_utils::build_first_hop_failure_packet(incoming_shared_secret, error_code, &{
2710 let mut res = Vec::with_capacity(8 + 128);
2711 // TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
2712 res.extend_from_slice(&byte_utils::be16_to_array(0));
2713 res.extend_from_slice(&upd.encode_with_len()[..]);
2717 // The only case where we'd be unable to
2718 // successfully get a channel update is if the
2719 // channel isn't in the fully-funded state yet,
2720 // implying our counterparty is trying to route
2721 // payments over the channel back to themselves
2722 // (cause no one else should know the short_id
2723 // is a lightning channel yet). We should have
2724 // no problem just calling this
2725 // unknown_next_peer (0x4000|10).
2726 onion_utils::build_first_hop_failure_packet(incoming_shared_secret, 0x4000|10, &[])
2728 let msg = msgs::UpdateFailHTLC {
2729 channel_id: msg.channel_id,
2730 htlc_id: msg.htlc_id,
2733 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
2735 _ => pending_forward_info
2738 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.logger), channel_state, chan);
2740 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2745 fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2746 let mut channel_lock = self.channel_state.lock().unwrap();
2748 let channel_state = &mut *channel_lock;
2749 match channel_state.by_id.entry(msg.channel_id) {
2750 hash_map::Entry::Occupied(mut chan) => {
2751 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2752 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2754 try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2756 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2759 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2763 fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2764 let mut channel_lock = self.channel_state.lock().unwrap();
2765 let channel_state = &mut *channel_lock;
2766 match channel_state.by_id.entry(msg.channel_id) {
2767 hash_map::Entry::Occupied(mut chan) => {
2768 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2769 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2771 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::LightningError { err: msg.reason.clone() }), channel_state, chan);
2773 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2778 fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2779 let mut channel_lock = self.channel_state.lock().unwrap();
2780 let channel_state = &mut *channel_lock;
2781 match channel_state.by_id.entry(msg.channel_id) {
2782 hash_map::Entry::Occupied(mut chan) => {
2783 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2784 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2786 if (msg.failure_code & 0x8000) == 0 {
2787 let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
2788 try_chan_entry!(self, Err(chan_err), channel_state, chan);
2790 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);
2793 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2797 fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2798 let mut channel_state_lock = self.channel_state.lock().unwrap();
2799 let channel_state = &mut *channel_state_lock;
2800 match channel_state.by_id.entry(msg.channel_id) {
2801 hash_map::Entry::Occupied(mut chan) => {
2802 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2803 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2805 let (revoke_and_ack, commitment_signed, closing_signed, monitor_update) =
2806 match chan.get_mut().commitment_signed(&msg, &self.fee_estimator, &self.logger) {
2807 Err((None, e)) => try_chan_entry!(self, Err(e), channel_state, chan),
2808 Err((Some(update), e)) => {
2809 assert!(chan.get().is_awaiting_monitor_update());
2810 let _ = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), update);
2811 try_chan_entry!(self, Err(e), channel_state, chan);
2816 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2817 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some());
2818 //TODO: Rebroadcast closing_signed if present on monitor update restoration
2820 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2821 node_id: counterparty_node_id.clone(),
2822 msg: revoke_and_ack,
2824 if let Some(msg) = commitment_signed {
2825 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2826 node_id: counterparty_node_id.clone(),
2827 updates: msgs::CommitmentUpdate {
2828 update_add_htlcs: Vec::new(),
2829 update_fulfill_htlcs: Vec::new(),
2830 update_fail_htlcs: Vec::new(),
2831 update_fail_malformed_htlcs: Vec::new(),
2833 commitment_signed: msg,
2837 if let Some(msg) = closing_signed {
2838 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2839 node_id: counterparty_node_id.clone(),
2845 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2850 fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, Vec<(PendingHTLCInfo, u64)>)]) {
2851 for &mut (prev_short_channel_id, prev_funding_outpoint, ref mut pending_forwards) in per_source_pending_forwards {
2852 let mut forward_event = None;
2853 if !pending_forwards.is_empty() {
2854 let mut channel_state = self.channel_state.lock().unwrap();
2855 if channel_state.forward_htlcs.is_empty() {
2856 forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS))
2858 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2859 match channel_state.forward_htlcs.entry(match forward_info.routing {
2860 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
2861 PendingHTLCRouting::Receive { .. } => 0,
2863 hash_map::Entry::Occupied(mut entry) => {
2864 entry.get_mut().push(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_funding_outpoint,
2865 prev_htlc_id, forward_info });
2867 hash_map::Entry::Vacant(entry) => {
2868 entry.insert(vec!(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_funding_outpoint,
2869 prev_htlc_id, forward_info }));
2874 match forward_event {
2876 let mut pending_events = self.pending_events.lock().unwrap();
2877 pending_events.push(events::Event::PendingHTLCsForwardable {
2878 time_forwardable: time
2886 fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2887 let mut htlcs_to_fail = Vec::new();
2889 let mut channel_state_lock = self.channel_state.lock().unwrap();
2890 let channel_state = &mut *channel_state_lock;
2891 match channel_state.by_id.entry(msg.channel_id) {
2892 hash_map::Entry::Occupied(mut chan) => {
2893 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2894 break Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2896 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2897 let (commitment_update, pending_forwards, pending_failures, closing_signed, monitor_update, htlcs_to_fail_in) =
2898 break_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &self.fee_estimator, &self.logger), channel_state, chan);
2899 htlcs_to_fail = htlcs_to_fail_in;
2900 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2901 if was_frozen_for_monitor {
2902 assert!(commitment_update.is_none() && closing_signed.is_none() && pending_forwards.is_empty() && pending_failures.is_empty());
2903 break Err(MsgHandleErrInternal::ignore_no_close("Previous monitor update failure prevented responses to RAA".to_owned()));
2905 if let Err(e) = handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, commitment_update.is_some(), pending_forwards, pending_failures) {
2907 } else { unreachable!(); }
2910 if let Some(updates) = commitment_update {
2911 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2912 node_id: counterparty_node_id.clone(),
2916 if let Some(msg) = closing_signed {
2917 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2918 node_id: counterparty_node_id.clone(),
2922 break Ok((pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"), chan.get().get_funding_txo().unwrap()))
2924 hash_map::Entry::Vacant(_) => break Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2927 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id);
2929 Ok((pending_forwards, mut pending_failures, short_channel_id, channel_outpoint)) => {
2930 for failure in pending_failures.drain(..) {
2931 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2933 self.forward_htlcs(&mut [(short_channel_id, channel_outpoint, pending_forwards)]);
2940 fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2941 let mut channel_lock = self.channel_state.lock().unwrap();
2942 let channel_state = &mut *channel_lock;
2943 match channel_state.by_id.entry(msg.channel_id) {
2944 hash_map::Entry::Occupied(mut chan) => {
2945 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2946 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2948 try_chan_entry!(self, chan.get_mut().update_fee(&self.fee_estimator, &msg), channel_state, chan);
2950 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2955 fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2956 let mut channel_state_lock = self.channel_state.lock().unwrap();
2957 let channel_state = &mut *channel_state_lock;
2959 match channel_state.by_id.entry(msg.channel_id) {
2960 hash_map::Entry::Occupied(mut chan) => {
2961 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2962 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2964 if !chan.get().is_usable() {
2965 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
2968 let our_node_id = self.get_our_node_id();
2969 let (announcement, our_bitcoin_sig) =
2970 try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2972 let were_node_one = announcement.node_id_1 == our_node_id;
2973 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
2975 let their_node_key = if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 };
2976 let their_bitcoin_key = if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 };
2977 match (self.secp_ctx.verify(&msghash, &msg.node_signature, their_node_key),
2978 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, their_bitcoin_key)) {
2980 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));
2981 try_chan_entry!(self, Err(chan_err), channel_state, chan);
2984 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));
2985 try_chan_entry!(self, Err(chan_err), channel_state, chan);
2991 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2993 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2994 msg: msgs::ChannelAnnouncement {
2995 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2996 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2997 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2998 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2999 contents: announcement,
3001 update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
3004 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3009 fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<(), MsgHandleErrInternal> {
3010 let mut channel_state_lock = self.channel_state.lock().unwrap();
3011 let channel_state = &mut *channel_state_lock;
3012 let chan_id = match channel_state.short_to_id.get(&msg.contents.short_channel_id) {
3013 Some(chan_id) => chan_id.clone(),
3015 // It's not a local channel
3019 match channel_state.by_id.entry(chan_id) {
3020 hash_map::Entry::Occupied(mut chan) => {
3021 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3022 // TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
3023 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), chan_id));
3025 try_chan_entry!(self, chan.get_mut().channel_update(&msg), channel_state, chan);
3027 hash_map::Entry::Vacant(_) => unreachable!()
3032 fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
3033 let mut channel_state_lock = self.channel_state.lock().unwrap();
3034 let channel_state = &mut *channel_state_lock;
3036 match channel_state.by_id.entry(msg.channel_id) {
3037 hash_map::Entry::Occupied(mut chan) => {
3038 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3039 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
3041 // Currently, we expect all holding cell update_adds to be dropped on peer
3042 // disconnect, so Channel's reestablish will never hand us any holding cell
3043 // freed HTLCs to fail backwards. If in the future we no longer drop pending
3044 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
3045 let (funding_locked, revoke_and_ack, commitment_update, monitor_update_opt, mut order, shutdown) =
3046 try_chan_entry!(self, chan.get_mut().channel_reestablish(msg, &self.logger), channel_state, chan);
3047 if let Some(monitor_update) = monitor_update_opt {
3048 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3049 // channel_reestablish doesn't guarantee the order it returns is sensical
3050 // for the messages it returns, but if we're setting what messages to
3051 // re-transmit on monitor update success, we need to make sure it is sane.
3052 if revoke_and_ack.is_none() {
3053 order = RAACommitmentOrder::CommitmentFirst;
3055 if commitment_update.is_none() {
3056 order = RAACommitmentOrder::RevokeAndACKFirst;
3058 return_monitor_err!(self, e, channel_state, chan, order, revoke_and_ack.is_some(), commitment_update.is_some());
3059 //TODO: Resend the funding_locked if needed once we get the monitor running again
3062 if let Some(msg) = funding_locked {
3063 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
3064 node_id: counterparty_node_id.clone(),
3068 macro_rules! send_raa { () => {
3069 if let Some(msg) = revoke_and_ack {
3070 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
3071 node_id: counterparty_node_id.clone(),
3076 macro_rules! send_cu { () => {
3077 if let Some(updates) = commitment_update {
3078 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3079 node_id: counterparty_node_id.clone(),
3085 RAACommitmentOrder::RevokeAndACKFirst => {
3089 RAACommitmentOrder::CommitmentFirst => {
3094 if let Some(msg) = shutdown {
3095 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
3096 node_id: counterparty_node_id.clone(),
3102 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3106 /// Begin Update fee process. Allowed only on an outbound channel.
3107 /// If successful, will generate a UpdateHTLCs event, so you should probably poll
3108 /// PeerManager::process_events afterwards.
3109 /// Note: This API is likely to change!
3110 /// (C-not exported) Cause its doc(hidden) anyway
3112 pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u32) -> Result<(), APIError> {
3113 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3114 let counterparty_node_id;
3115 let err: Result<(), _> = loop {
3116 let mut channel_state_lock = self.channel_state.lock().unwrap();
3117 let channel_state = &mut *channel_state_lock;
3119 match channel_state.by_id.entry(channel_id) {
3120 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: format!("Failed to find corresponding channel for id {}", channel_id.to_hex())}),
3121 hash_map::Entry::Occupied(mut chan) => {
3122 if !chan.get().is_outbound() {
3123 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel".to_owned()});
3125 if chan.get().is_awaiting_monitor_update() {
3126 return Err(APIError::MonitorUpdateFailed);
3128 if !chan.get().is_live() {
3129 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected".to_owned()});
3131 counterparty_node_id = chan.get().get_counterparty_node_id();
3132 if let Some((update_fee, commitment_signed, monitor_update)) =
3133 break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw, &self.logger), channel_state, chan)
3135 if let Err(_e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3138 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3139 node_id: chan.get().get_counterparty_node_id(),
3140 updates: msgs::CommitmentUpdate {
3141 update_add_htlcs: Vec::new(),
3142 update_fulfill_htlcs: Vec::new(),
3143 update_fail_htlcs: Vec::new(),
3144 update_fail_malformed_htlcs: Vec::new(),
3145 update_fee: Some(update_fee),
3155 match handle_error!(self, err, counterparty_node_id) {
3156 Ok(_) => unreachable!(),
3157 Err(e) => { Err(APIError::APIMisuseError { err: e.err })}
3161 /// Process pending events from the `chain::Watch`.
3162 fn process_pending_monitor_events(&self) {
3163 let mut failed_channels = Vec::new();
3165 for monitor_event in self.chain_monitor.release_pending_monitor_events() {
3166 match monitor_event {
3167 MonitorEvent::HTLCEvent(htlc_update) => {
3168 if let Some(preimage) = htlc_update.payment_preimage {
3169 log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
3170 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
3172 log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
3173 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() });
3176 MonitorEvent::CommitmentTxBroadcasted(funding_outpoint) => {
3177 let mut channel_lock = self.channel_state.lock().unwrap();
3178 let channel_state = &mut *channel_lock;
3179 let by_id = &mut channel_state.by_id;
3180 let short_to_id = &mut channel_state.short_to_id;
3181 let pending_msg_events = &mut channel_state.pending_msg_events;
3182 if let Some(mut chan) = by_id.remove(&funding_outpoint.to_channel_id()) {
3183 if let Some(short_id) = chan.get_short_channel_id() {
3184 short_to_id.remove(&short_id);
3186 failed_channels.push(chan.force_shutdown(false));
3187 if let Ok(update) = self.get_channel_update(&chan) {
3188 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3198 for failure in failed_channels.drain(..) {
3199 self.finish_force_close_channel(failure);
3203 /// Handle a list of channel failures during a block_connected or block_disconnected call,
3204 /// pushing the channel monitor update (if any) to the background events queue and removing the
3206 fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
3207 for mut failure in failed_channels.drain(..) {
3208 // Either a commitment transactions has been confirmed on-chain or
3209 // Channel::block_disconnected detected that the funding transaction has been
3210 // reorganized out of the main chain.
3211 // We cannot broadcast our latest local state via monitor update (as
3212 // Channel::force_shutdown tries to make us do) as we may still be in initialization,
3213 // so we track the update internally and handle it when the user next calls
3214 // timer_chan_freshness_every_min, guaranteeing we're running normally.
3215 if let Some((funding_txo, update)) = failure.0.take() {
3216 assert_eq!(update.updates.len(), 1);
3217 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
3218 assert!(should_broadcast);
3219 } else { unreachable!(); }
3220 self.pending_background_events.lock().unwrap().push(BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)));
3222 self.finish_force_close_channel(failure);
3227 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> MessageSendEventsProvider for ChannelManager<Signer, M, T, K, F, L>
3228 where M::Target: chain::Watch<Signer>,
3229 T::Target: BroadcasterInterface,
3230 K::Target: KeysInterface<Signer = Signer>,
3231 F::Target: FeeEstimator,
3234 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
3235 //TODO: This behavior should be documented. It's non-intuitive that we query
3236 // ChannelMonitors when clearing other events.
3237 self.process_pending_monitor_events();
3239 let mut ret = Vec::new();
3240 let mut channel_state = self.channel_state.lock().unwrap();
3241 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
3246 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> EventsProvider for ChannelManager<Signer, M, T, K, F, L>
3247 where M::Target: chain::Watch<Signer>,
3248 T::Target: BroadcasterInterface,
3249 K::Target: KeysInterface<Signer = Signer>,
3250 F::Target: FeeEstimator,
3253 fn get_and_clear_pending_events(&self) -> Vec<Event> {
3254 //TODO: This behavior should be documented. It's non-intuitive that we query
3255 // ChannelMonitors when clearing other events.
3256 self.process_pending_monitor_events();
3258 let mut ret = Vec::new();
3259 let mut pending_events = self.pending_events.lock().unwrap();
3260 mem::swap(&mut ret, &mut *pending_events);
3265 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> chain::Listen for ChannelManager<Signer, M, T, K, F, L>
3267 M::Target: chain::Watch<Signer>,
3268 T::Target: BroadcasterInterface,
3269 K::Target: KeysInterface<Signer = Signer>,
3270 F::Target: FeeEstimator,
3273 fn block_connected(&self, block: &Block, height: u32) {
3274 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
3275 ChannelManager::block_connected(self, &block.header, &txdata, height);
3278 fn block_disconnected(&self, header: &BlockHeader, _height: u32) {
3279 ChannelManager::block_disconnected(self, header);
3283 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
3284 where M::Target: chain::Watch<Signer>,
3285 T::Target: BroadcasterInterface,
3286 K::Target: KeysInterface<Signer = Signer>,
3287 F::Target: FeeEstimator,
3290 /// Updates channel state based on transactions seen in a connected block.
3291 pub fn block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3292 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3293 // during initialization prior to the chain_monitor being fully configured in some cases.
3294 // See the docs for `ChannelManagerReadArgs` for more.
3295 let block_hash = header.block_hash();
3296 log_trace!(self.logger, "Block {} at height {} connected", block_hash, height);
3298 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3300 self.latest_block_height.store(height as usize, Ordering::Release);
3301 *self.last_block_hash.write().unwrap() = block_hash;
3303 let mut failed_channels = Vec::new();
3304 let mut timed_out_htlcs = Vec::new();
3306 let mut channel_lock = self.channel_state.lock().unwrap();
3307 let channel_state = &mut *channel_lock;
3308 let short_to_id = &mut channel_state.short_to_id;
3309 let pending_msg_events = &mut channel_state.pending_msg_events;
3310 channel_state.by_id.retain(|_, channel| {
3311 let res = channel.block_connected(header, txdata, height);
3312 if let Ok((chan_res, mut timed_out_pending_htlcs)) = res {
3313 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
3314 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
3315 timed_out_htlcs.push((source, payment_hash, HTLCFailReason::Reason {
3316 failure_code: 0x1000 | 14, // expiry_too_soon, or at least it is now
3320 if let Some(funding_locked) = chan_res {
3321 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
3322 node_id: channel.get_counterparty_node_id(),
3323 msg: funding_locked,
3325 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
3326 log_trace!(self.logger, "Sending funding_locked and announcement_signatures for {}", log_bytes!(channel.channel_id()));
3327 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
3328 node_id: channel.get_counterparty_node_id(),
3329 msg: announcement_sigs,
3332 log_trace!(self.logger, "Sending funding_locked WITHOUT announcement_signatures for {}", log_bytes!(channel.channel_id()));
3334 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
3336 } else if let Err(e) = res {
3337 pending_msg_events.push(events::MessageSendEvent::HandleError {
3338 node_id: channel.get_counterparty_node_id(),
3339 action: msgs::ErrorAction::SendErrorMessage { msg: e },
3343 if let Some(funding_txo) = channel.get_funding_txo() {
3344 for &(_, tx) in txdata.iter() {
3345 for inp in tx.input.iter() {
3346 if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
3347 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()));
3348 if let Some(short_id) = channel.get_short_channel_id() {
3349 short_to_id.remove(&short_id);
3351 // It looks like our counterparty went on-chain. Close the channel.
3352 failed_channels.push(channel.force_shutdown(true));
3353 if let Ok(update) = self.get_channel_update(&channel) {
3354 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3366 channel_state.claimable_htlcs.retain(|&(ref payment_hash, _), htlcs| {
3367 htlcs.retain(|htlc| {
3368 // If height is approaching the number of blocks we think it takes us to get
3369 // our commitment transaction confirmed before the HTLC expires, plus the
3370 // number of blocks we generally consider it to take to do a commitment update,
3371 // just give up on it and fail the HTLC.
3372 if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
3373 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
3374 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(height));
3375 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(), HTLCFailReason::Reason {
3376 failure_code: 0x4000 | 15,
3377 data: htlc_msat_height_data
3382 !htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
3386 self.handle_init_event_channel_failures(failed_channels);
3388 for (source, payment_hash, reason) in timed_out_htlcs.drain(..) {
3389 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, reason);
3393 // Update last_node_announcement_serial to be the max of its current value and the
3394 // block timestamp. This should keep us close to the current time without relying on
3395 // having an explicit local time source.
3396 // Just in case we end up in a race, we loop until we either successfully update
3397 // last_node_announcement_serial or decide we don't need to.
3398 let old_serial = self.last_node_announcement_serial.load(Ordering::Acquire);
3399 if old_serial >= header.time as usize { break; }
3400 if self.last_node_announcement_serial.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
3406 /// Updates channel state based on a disconnected block.
3408 /// If necessary, the channel may be force-closed without letting the counterparty participate
3409 /// in the shutdown.
3410 pub fn block_disconnected(&self, header: &BlockHeader) {
3411 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3412 // during initialization prior to the chain_monitor being fully configured in some cases.
3413 // See the docs for `ChannelManagerReadArgs` for more.
3414 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3416 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
3417 *self.last_block_hash.write().unwrap() = header.prev_blockhash;
3419 let mut failed_channels = Vec::new();
3421 let mut channel_lock = self.channel_state.lock().unwrap();
3422 let channel_state = &mut *channel_lock;
3423 let short_to_id = &mut channel_state.short_to_id;
3424 let pending_msg_events = &mut channel_state.pending_msg_events;
3425 channel_state.by_id.retain(|_, v| {
3426 if v.block_disconnected(header) {
3427 if let Some(short_id) = v.get_short_channel_id() {
3428 short_to_id.remove(&short_id);
3430 failed_channels.push(v.force_shutdown(true));
3431 if let Ok(update) = self.get_channel_update(&v) {
3432 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3443 self.handle_init_event_channel_failures(failed_channels);
3446 /// Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool
3447 /// indicating whether persistence is necessary. Only one listener on
3448 /// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
3450 /// Note that the feature `allow_wallclock_use` must be enabled to use this function.
3451 #[cfg(any(test, feature = "allow_wallclock_use"))]
3452 pub fn await_persistable_update_timeout(&self, max_wait: Duration) -> bool {
3453 self.persistence_notifier.wait_timeout(max_wait)
3456 /// Blocks until ChannelManager needs to be persisted. Only one listener on
3457 /// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
3459 pub fn await_persistable_update(&self) {
3460 self.persistence_notifier.wait()
3463 #[cfg(any(test, feature = "_test_utils"))]
3464 pub fn get_persistence_condvar_value(&self) -> bool {
3465 let mutcond = &self.persistence_notifier.persistence_lock;
3466 let &(ref mtx, _) = mutcond;
3467 let guard = mtx.lock().unwrap();
3472 impl<Signer: Sign, M: Deref + Sync + Send, T: Deref + Sync + Send, K: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send>
3473 ChannelMessageHandler for ChannelManager<Signer, M, T, K, F, L>
3474 where M::Target: chain::Watch<Signer>,
3475 T::Target: BroadcasterInterface,
3476 K::Target: KeysInterface<Signer = Signer>,
3477 F::Target: FeeEstimator,
3480 fn handle_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) {
3481 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3482 let _ = handle_error!(self, self.internal_open_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
3485 fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) {
3486 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3487 let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
3490 fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
3491 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3492 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
3495 fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
3496 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3497 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
3500 fn handle_funding_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingLocked) {
3501 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3502 let _ = handle_error!(self, self.internal_funding_locked(counterparty_node_id, msg), *counterparty_node_id);
3505 fn handle_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) {
3506 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3507 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, their_features, msg), *counterparty_node_id);
3510 fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
3511 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3512 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
3515 fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
3516 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3517 let _ = handle_error!(self, self.internal_update_add_htlc(counterparty_node_id, msg), *counterparty_node_id);
3520 fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
3521 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3522 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
3525 fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
3526 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3527 let _ = handle_error!(self, self.internal_update_fail_htlc(counterparty_node_id, msg), *counterparty_node_id);
3530 fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
3531 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3532 let _ = handle_error!(self, self.internal_update_fail_malformed_htlc(counterparty_node_id, msg), *counterparty_node_id);
3535 fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
3536 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3537 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
3540 fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
3541 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3542 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
3545 fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
3546 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3547 let _ = handle_error!(self, self.internal_update_fee(counterparty_node_id, msg), *counterparty_node_id);
3550 fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
3551 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3552 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
3555 fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
3556 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3557 let _ = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id);
3560 fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
3561 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3562 let _ = handle_error!(self, self.internal_channel_reestablish(counterparty_node_id, msg), *counterparty_node_id);
3565 fn peer_disconnected(&self, counterparty_node_id: &PublicKey, no_connection_possible: bool) {
3566 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3567 let mut failed_channels = Vec::new();
3568 let mut failed_payments = Vec::new();
3569 let mut no_channels_remain = true;
3571 let mut channel_state_lock = self.channel_state.lock().unwrap();
3572 let channel_state = &mut *channel_state_lock;
3573 let short_to_id = &mut channel_state.short_to_id;
3574 let pending_msg_events = &mut channel_state.pending_msg_events;
3575 if no_connection_possible {
3576 log_debug!(self.logger, "Failing all channels with {} due to no_connection_possible", log_pubkey!(counterparty_node_id));
3577 channel_state.by_id.retain(|_, chan| {
3578 if chan.get_counterparty_node_id() == *counterparty_node_id {
3579 if let Some(short_id) = chan.get_short_channel_id() {
3580 short_to_id.remove(&short_id);
3582 failed_channels.push(chan.force_shutdown(true));
3583 if let Ok(update) = self.get_channel_update(&chan) {
3584 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3594 log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(counterparty_node_id));
3595 channel_state.by_id.retain(|_, chan| {
3596 if chan.get_counterparty_node_id() == *counterparty_node_id {
3597 // Note that currently on channel reestablish we assert that there are no
3598 // holding cell add-HTLCs, so if in the future we stop removing uncommitted HTLCs
3599 // on peer disconnect here, there will need to be corresponding changes in
3600 // reestablish logic.
3601 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger);
3602 chan.to_disabled_marked();
3603 if !failed_adds.is_empty() {
3604 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
3605 failed_payments.push((chan_update, failed_adds));
3607 if chan.is_shutdown() {
3608 if let Some(short_id) = chan.get_short_channel_id() {
3609 short_to_id.remove(&short_id);
3613 no_channels_remain = false;
3619 pending_msg_events.retain(|msg| {
3621 &events::MessageSendEvent::SendAcceptChannel { ref node_id, .. } => node_id != counterparty_node_id,
3622 &events::MessageSendEvent::SendOpenChannel { ref node_id, .. } => node_id != counterparty_node_id,
3623 &events::MessageSendEvent::SendFundingCreated { ref node_id, .. } => node_id != counterparty_node_id,
3624 &events::MessageSendEvent::SendFundingSigned { ref node_id, .. } => node_id != counterparty_node_id,
3625 &events::MessageSendEvent::SendFundingLocked { ref node_id, .. } => node_id != counterparty_node_id,
3626 &events::MessageSendEvent::SendAnnouncementSignatures { ref node_id, .. } => node_id != counterparty_node_id,
3627 &events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => node_id != counterparty_node_id,
3628 &events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => node_id != counterparty_node_id,
3629 &events::MessageSendEvent::SendClosingSigned { ref node_id, .. } => node_id != counterparty_node_id,
3630 &events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != counterparty_node_id,
3631 &events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != counterparty_node_id,
3632 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
3633 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
3634 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
3635 &events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != counterparty_node_id,
3636 &events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
3637 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
3638 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
3639 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
3643 if no_channels_remain {
3644 self.per_peer_state.write().unwrap().remove(counterparty_node_id);
3647 for failure in failed_channels.drain(..) {
3648 self.finish_force_close_channel(failure);
3650 for (chan_update, mut htlc_sources) in failed_payments {
3651 for (htlc_source, payment_hash) in htlc_sources.drain(..) {
3652 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
3657 fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init) {
3658 log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
3660 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3663 let mut peer_state_lock = self.per_peer_state.write().unwrap();
3664 match peer_state_lock.entry(counterparty_node_id.clone()) {
3665 hash_map::Entry::Vacant(e) => {
3666 e.insert(Mutex::new(PeerState {
3667 latest_features: init_msg.features.clone(),
3670 hash_map::Entry::Occupied(e) => {
3671 e.get().lock().unwrap().latest_features = init_msg.features.clone();
3676 let mut channel_state_lock = self.channel_state.lock().unwrap();
3677 let channel_state = &mut *channel_state_lock;
3678 let pending_msg_events = &mut channel_state.pending_msg_events;
3679 channel_state.by_id.retain(|_, chan| {
3680 if chan.get_counterparty_node_id() == *counterparty_node_id {
3681 if !chan.have_received_message() {
3682 // If we created this (outbound) channel while we were disconnected from the
3683 // peer we probably failed to send the open_channel message, which is now
3684 // lost. We can't have had anything pending related to this channel, so we just
3688 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
3689 node_id: chan.get_counterparty_node_id(),
3690 msg: chan.get_channel_reestablish(&self.logger),
3696 //TODO: Also re-broadcast announcement_signatures
3699 fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
3700 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3702 if msg.channel_id == [0; 32] {
3703 for chan in self.list_channels() {
3704 if chan.remote_network_id == *counterparty_node_id {
3705 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
3706 let _ = self.force_close_channel_with_peer(&chan.channel_id, Some(counterparty_node_id));
3710 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
3711 let _ = self.force_close_channel_with_peer(&msg.channel_id, Some(counterparty_node_id));
3716 /// Used to signal to the ChannelManager persister that the manager needs to be re-persisted to
3717 /// disk/backups, through `await_persistable_update_timeout` and `await_persistable_update`.
3718 struct PersistenceNotifier {
3719 /// Users won't access the persistence_lock directly, but rather wait on its bool using
3720 /// `wait_timeout` and `wait`.
3721 persistence_lock: (Mutex<bool>, Condvar),
3724 impl PersistenceNotifier {
3727 persistence_lock: (Mutex::new(false), Condvar::new()),
3733 let &(ref mtx, ref cvar) = &self.persistence_lock;
3734 let mut guard = mtx.lock().unwrap();
3735 guard = cvar.wait(guard).unwrap();
3736 let result = *guard;
3744 #[cfg(any(test, feature = "allow_wallclock_use"))]
3745 fn wait_timeout(&self, max_wait: Duration) -> bool {
3746 let current_time = Instant::now();
3748 let &(ref mtx, ref cvar) = &self.persistence_lock;
3749 let mut guard = mtx.lock().unwrap();
3750 guard = cvar.wait_timeout(guard, max_wait).unwrap().0;
3751 // Due to spurious wakeups that can happen on `wait_timeout`, here we need to check if the
3752 // desired wait time has actually passed, and if not then restart the loop with a reduced wait
3753 // time. Note that this logic can be highly simplified through the use of
3754 // `Condvar::wait_while` and `Condvar::wait_timeout_while`, if and when our MSRV is raised to
3756 let elapsed = current_time.elapsed();
3757 let result = *guard;
3758 if result || elapsed >= max_wait {
3762 match max_wait.checked_sub(elapsed) {
3763 None => return result,
3769 // Signal to the ChannelManager persister that there are updates necessitating persisting to disk.
3771 let &(ref persist_mtx, ref cnd) = &self.persistence_lock;
3772 let mut persistence_lock = persist_mtx.lock().unwrap();
3773 *persistence_lock = true;
3774 mem::drop(persistence_lock);
3779 const SERIALIZATION_VERSION: u8 = 1;
3780 const MIN_SERIALIZATION_VERSION: u8 = 1;
3782 impl Writeable for PendingHTLCInfo {
3783 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3784 match &self.routing {
3785 &PendingHTLCRouting::Forward { ref onion_packet, ref short_channel_id } => {
3787 onion_packet.write(writer)?;
3788 short_channel_id.write(writer)?;
3790 &PendingHTLCRouting::Receive { ref payment_data, ref incoming_cltv_expiry } => {
3792 payment_data.write(writer)?;
3793 incoming_cltv_expiry.write(writer)?;
3796 self.incoming_shared_secret.write(writer)?;
3797 self.payment_hash.write(writer)?;
3798 self.amt_to_forward.write(writer)?;
3799 self.outgoing_cltv_value.write(writer)?;
3804 impl Readable for PendingHTLCInfo {
3805 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<PendingHTLCInfo, DecodeError> {
3806 Ok(PendingHTLCInfo {
3807 routing: match Readable::read(reader)? {
3808 0u8 => PendingHTLCRouting::Forward {
3809 onion_packet: Readable::read(reader)?,
3810 short_channel_id: Readable::read(reader)?,
3812 1u8 => PendingHTLCRouting::Receive {
3813 payment_data: Readable::read(reader)?,
3814 incoming_cltv_expiry: Readable::read(reader)?,
3816 _ => return Err(DecodeError::InvalidValue),
3818 incoming_shared_secret: Readable::read(reader)?,
3819 payment_hash: Readable::read(reader)?,
3820 amt_to_forward: Readable::read(reader)?,
3821 outgoing_cltv_value: Readable::read(reader)?,
3826 impl Writeable for HTLCFailureMsg {
3827 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3829 &HTLCFailureMsg::Relay(ref fail_msg) => {
3831 fail_msg.write(writer)?;
3833 &HTLCFailureMsg::Malformed(ref fail_msg) => {
3835 fail_msg.write(writer)?;
3842 impl Readable for HTLCFailureMsg {
3843 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3844 match <u8 as Readable>::read(reader)? {
3845 0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3846 1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3847 _ => Err(DecodeError::InvalidValue),
3852 impl Writeable for PendingHTLCStatus {
3853 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3855 &PendingHTLCStatus::Forward(ref forward_info) => {
3857 forward_info.write(writer)?;
3859 &PendingHTLCStatus::Fail(ref fail_msg) => {
3861 fail_msg.write(writer)?;
3868 impl Readable for PendingHTLCStatus {
3869 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3870 match <u8 as Readable>::read(reader)? {
3871 0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3872 1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3873 _ => Err(DecodeError::InvalidValue),
3878 impl_writeable!(HTLCPreviousHopData, 0, {
3882 incoming_packet_shared_secret
3885 impl_writeable!(ClaimableHTLC, 0, {
3892 impl Writeable for HTLCSource {
3893 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3895 &HTLCSource::PreviousHopData(ref hop_data) => {
3897 hop_data.write(writer)?;
3899 &HTLCSource::OutboundRoute { ref path, ref session_priv, ref first_hop_htlc_msat } => {
3901 path.write(writer)?;
3902 session_priv.write(writer)?;
3903 first_hop_htlc_msat.write(writer)?;
3910 impl Readable for HTLCSource {
3911 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3912 match <u8 as Readable>::read(reader)? {
3913 0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3914 1 => Ok(HTLCSource::OutboundRoute {
3915 path: Readable::read(reader)?,
3916 session_priv: Readable::read(reader)?,
3917 first_hop_htlc_msat: Readable::read(reader)?,
3919 _ => Err(DecodeError::InvalidValue),
3924 impl Writeable for HTLCFailReason {
3925 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3927 &HTLCFailReason::LightningError { ref err } => {
3931 &HTLCFailReason::Reason { ref failure_code, ref data } => {
3933 failure_code.write(writer)?;
3934 data.write(writer)?;
3941 impl Readable for HTLCFailReason {
3942 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3943 match <u8 as Readable>::read(reader)? {
3944 0 => Ok(HTLCFailReason::LightningError { err: Readable::read(reader)? }),
3945 1 => Ok(HTLCFailReason::Reason {
3946 failure_code: Readable::read(reader)?,
3947 data: Readable::read(reader)?,
3949 _ => Err(DecodeError::InvalidValue),
3954 impl Writeable for HTLCForwardInfo {
3955 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3957 &HTLCForwardInfo::AddHTLC { ref prev_short_channel_id, ref prev_funding_outpoint, ref prev_htlc_id, ref forward_info } => {
3959 prev_short_channel_id.write(writer)?;
3960 prev_funding_outpoint.write(writer)?;
3961 prev_htlc_id.write(writer)?;
3962 forward_info.write(writer)?;
3964 &HTLCForwardInfo::FailHTLC { ref htlc_id, ref err_packet } => {
3966 htlc_id.write(writer)?;
3967 err_packet.write(writer)?;
3974 impl Readable for HTLCForwardInfo {
3975 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCForwardInfo, DecodeError> {
3976 match <u8 as Readable>::read(reader)? {
3977 0 => Ok(HTLCForwardInfo::AddHTLC {
3978 prev_short_channel_id: Readable::read(reader)?,
3979 prev_funding_outpoint: Readable::read(reader)?,
3980 prev_htlc_id: Readable::read(reader)?,
3981 forward_info: Readable::read(reader)?,
3983 1 => Ok(HTLCForwardInfo::FailHTLC {
3984 htlc_id: Readable::read(reader)?,
3985 err_packet: Readable::read(reader)?,
3987 _ => Err(DecodeError::InvalidValue),
3992 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable for ChannelManager<Signer, M, T, K, F, L>
3993 where M::Target: chain::Watch<Signer>,
3994 T::Target: BroadcasterInterface,
3995 K::Target: KeysInterface<Signer = Signer>,
3996 F::Target: FeeEstimator,
3999 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
4000 let _consistency_lock = self.total_consistency_lock.write().unwrap();
4002 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
4003 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
4005 self.genesis_hash.write(writer)?;
4006 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
4007 self.last_block_hash.read().unwrap().write(writer)?;
4009 let channel_state = self.channel_state.lock().unwrap();
4010 let mut unfunded_channels = 0;
4011 for (_, channel) in channel_state.by_id.iter() {
4012 if !channel.is_funding_initiated() {
4013 unfunded_channels += 1;
4016 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
4017 for (_, channel) in channel_state.by_id.iter() {
4018 if channel.is_funding_initiated() {
4019 channel.write(writer)?;
4023 (channel_state.forward_htlcs.len() as u64).write(writer)?;
4024 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
4025 short_channel_id.write(writer)?;
4026 (pending_forwards.len() as u64).write(writer)?;
4027 for forward in pending_forwards {
4028 forward.write(writer)?;
4032 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
4033 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
4034 payment_hash.write(writer)?;
4035 (previous_hops.len() as u64).write(writer)?;
4036 for htlc in previous_hops.iter() {
4037 htlc.write(writer)?;
4041 let per_peer_state = self.per_peer_state.write().unwrap();
4042 (per_peer_state.len() as u64).write(writer)?;
4043 for (peer_pubkey, peer_state_mutex) in per_peer_state.iter() {
4044 peer_pubkey.write(writer)?;
4045 let peer_state = peer_state_mutex.lock().unwrap();
4046 peer_state.latest_features.write(writer)?;
4049 let events = self.pending_events.lock().unwrap();
4050 (events.len() as u64).write(writer)?;
4051 for event in events.iter() {
4052 event.write(writer)?;
4055 let background_events = self.pending_background_events.lock().unwrap();
4056 (background_events.len() as u64).write(writer)?;
4057 for event in background_events.iter() {
4059 BackgroundEvent::ClosingMonitorUpdate((funding_txo, monitor_update)) => {
4061 funding_txo.write(writer)?;
4062 monitor_update.write(writer)?;
4067 (self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
4073 /// Arguments for the creation of a ChannelManager that are not deserialized.
4075 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
4077 /// 1) Deserialize all stored ChannelMonitors.
4078 /// 2) Deserialize the ChannelManager by filling in this struct and calling:
4079 /// <(BlockHash, ChannelManager)>::read(reader, args)
4080 /// This may result in closing some Channels if the ChannelMonitor is newer than the stored
4081 /// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
4082 /// 3) If you are not fetching full blocks, register all relevant ChannelMonitor outpoints the same
4083 /// way you would handle a `chain::Filter` call using ChannelMonitor::get_outputs_to_watch() and
4084 /// ChannelMonitor::get_funding_txo().
4085 /// 4) Reconnect blocks on your ChannelMonitors.
4086 /// 5) Disconnect/connect blocks on the ChannelManager.
4087 /// 6) Move the ChannelMonitors into your local chain::Watch.
4089 /// Note that the ordering of #4-6 is not of importance, however all three must occur before you
4090 /// call any other methods on the newly-deserialized ChannelManager.
4092 /// Note that because some channels may be closed during deserialization, it is critical that you
4093 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
4094 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
4095 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
4096 /// not force-close the same channels but consider them live), you may end up revoking a state for
4097 /// which you've already broadcasted the transaction.
4098 pub struct ChannelManagerReadArgs<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4099 where M::Target: chain::Watch<Signer>,
4100 T::Target: BroadcasterInterface,
4101 K::Target: KeysInterface<Signer = Signer>,
4102 F::Target: FeeEstimator,
4105 /// The keys provider which will give us relevant keys. Some keys will be loaded during
4106 /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
4108 pub keys_manager: K,
4110 /// The fee_estimator for use in the ChannelManager in the future.
4112 /// No calls to the FeeEstimator will be made during deserialization.
4113 pub fee_estimator: F,
4114 /// The chain::Watch for use in the ChannelManager in the future.
4116 /// No calls to the chain::Watch will be made during deserialization. It is assumed that
4117 /// you have deserialized ChannelMonitors separately and will add them to your
4118 /// chain::Watch after deserializing this ChannelManager.
4119 pub chain_monitor: M,
4121 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
4122 /// used to broadcast the latest local commitment transactions of channels which must be
4123 /// force-closed during deserialization.
4124 pub tx_broadcaster: T,
4125 /// The Logger for use in the ChannelManager and which may be used to log information during
4126 /// deserialization.
4128 /// Default settings used for new channels. Any existing channels will continue to use the
4129 /// runtime settings which were stored when the ChannelManager was serialized.
4130 pub default_config: UserConfig,
4132 /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
4133 /// value.get_funding_txo() should be the key).
4135 /// If a monitor is inconsistent with the channel state during deserialization the channel will
4136 /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
4137 /// is true for missing channels as well. If there is a monitor missing for which we find
4138 /// channel data Err(DecodeError::InvalidValue) will be returned.
4140 /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
4143 /// (C-not exported) because we have no HashMap bindings
4144 pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<Signer>>,
4147 impl<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4148 ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>
4149 where M::Target: chain::Watch<Signer>,
4150 T::Target: BroadcasterInterface,
4151 K::Target: KeysInterface<Signer = Signer>,
4152 F::Target: FeeEstimator,
4155 /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
4156 /// HashMap for you. This is primarily useful for C bindings where it is not practical to
4157 /// populate a HashMap directly from C.
4158 pub fn new(keys_manager: K, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, logger: L, default_config: UserConfig,
4159 mut channel_monitors: Vec<&'a mut ChannelMonitor<Signer>>) -> Self {
4161 keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, default_config,
4162 channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
4167 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
4168 // SipmleArcChannelManager type:
4169 impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4170 ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, Arc<ChannelManager<Signer, M, T, K, F, L>>)
4171 where M::Target: chain::Watch<Signer>,
4172 T::Target: BroadcasterInterface,
4173 K::Target: KeysInterface<Signer = Signer>,
4174 F::Target: FeeEstimator,
4177 fn read<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
4178 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<Signer, M, T, K, F, L>)>::read(reader, args)?;
4179 Ok((blockhash, Arc::new(chan_manager)))
4183 impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4184 ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, ChannelManager<Signer, M, T, K, F, L>)
4185 where M::Target: chain::Watch<Signer>,
4186 T::Target: BroadcasterInterface,
4187 K::Target: KeysInterface<Signer = Signer>,
4188 F::Target: FeeEstimator,
4191 fn read<R: ::std::io::Read>(reader: &mut R, mut args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
4192 let _ver: u8 = Readable::read(reader)?;
4193 let min_ver: u8 = Readable::read(reader)?;
4194 if min_ver > SERIALIZATION_VERSION {
4195 return Err(DecodeError::UnknownVersion);
4198 let genesis_hash: BlockHash = Readable::read(reader)?;
4199 let latest_block_height: u32 = Readable::read(reader)?;
4200 let last_block_hash: BlockHash = Readable::read(reader)?;
4202 let mut failed_htlcs = Vec::new();
4204 let channel_count: u64 = Readable::read(reader)?;
4205 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
4206 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
4207 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
4208 for _ in 0..channel_count {
4209 let mut channel: Channel<Signer> = Channel::read(reader, &args.keys_manager)?;
4210 let funding_txo = channel.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
4211 funding_txo_set.insert(funding_txo.clone());
4212 if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
4213 if channel.get_cur_holder_commitment_transaction_number() < monitor.get_cur_holder_commitment_number() ||
4214 channel.get_revoked_counterparty_commitment_transaction_number() < monitor.get_min_seen_secret() ||
4215 channel.get_cur_counterparty_commitment_transaction_number() < monitor.get_cur_counterparty_commitment_number() ||
4216 channel.get_latest_monitor_update_id() > monitor.get_latest_update_id() {
4217 // If the channel is ahead of the monitor, return InvalidValue:
4218 return Err(DecodeError::InvalidValue);
4219 } else if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
4220 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
4221 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
4222 channel.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
4223 // But if the channel is behind of the monitor, close the channel:
4224 let (_, mut new_failed_htlcs) = channel.force_shutdown(true);
4225 failed_htlcs.append(&mut new_failed_htlcs);
4226 monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
4228 if let Some(short_channel_id) = channel.get_short_channel_id() {
4229 short_to_id.insert(short_channel_id, channel.channel_id());
4231 by_id.insert(channel.channel_id(), channel);
4234 return Err(DecodeError::InvalidValue);
4238 for (ref funding_txo, ref mut monitor) in args.channel_monitors.iter_mut() {
4239 if !funding_txo_set.contains(funding_txo) {
4240 monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
4244 const MAX_ALLOC_SIZE: usize = 1024 * 64;
4245 let forward_htlcs_count: u64 = Readable::read(reader)?;
4246 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
4247 for _ in 0..forward_htlcs_count {
4248 let short_channel_id = Readable::read(reader)?;
4249 let pending_forwards_count: u64 = Readable::read(reader)?;
4250 let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
4251 for _ in 0..pending_forwards_count {
4252 pending_forwards.push(Readable::read(reader)?);
4254 forward_htlcs.insert(short_channel_id, pending_forwards);
4257 let claimable_htlcs_count: u64 = Readable::read(reader)?;
4258 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
4259 for _ in 0..claimable_htlcs_count {
4260 let payment_hash = Readable::read(reader)?;
4261 let previous_hops_len: u64 = Readable::read(reader)?;
4262 let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
4263 for _ in 0..previous_hops_len {
4264 previous_hops.push(Readable::read(reader)?);
4266 claimable_htlcs.insert(payment_hash, previous_hops);
4269 let peer_count: u64 = Readable::read(reader)?;
4270 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState>)>()));
4271 for _ in 0..peer_count {
4272 let peer_pubkey = Readable::read(reader)?;
4273 let peer_state = PeerState {
4274 latest_features: Readable::read(reader)?,
4276 per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
4279 let event_count: u64 = Readable::read(reader)?;
4280 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>()));
4281 for _ in 0..event_count {
4282 match MaybeReadable::read(reader)? {
4283 Some(event) => pending_events_read.push(event),
4288 let background_event_count: u64 = Readable::read(reader)?;
4289 let mut pending_background_events_read: Vec<BackgroundEvent> = Vec::with_capacity(cmp::min(background_event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<BackgroundEvent>()));
4290 for _ in 0..background_event_count {
4291 match <u8 as Readable>::read(reader)? {
4292 0 => pending_background_events_read.push(BackgroundEvent::ClosingMonitorUpdate((Readable::read(reader)?, Readable::read(reader)?))),
4293 _ => return Err(DecodeError::InvalidValue),
4297 let last_node_announcement_serial: u32 = Readable::read(reader)?;
4299 let mut secp_ctx = Secp256k1::new();
4300 secp_ctx.seeded_randomize(&args.keys_manager.get_secure_random_bytes());
4302 let channel_manager = ChannelManager {
4304 fee_estimator: args.fee_estimator,
4305 chain_monitor: args.chain_monitor,
4306 tx_broadcaster: args.tx_broadcaster,
4308 latest_block_height: AtomicUsize::new(latest_block_height as usize),
4309 last_block_hash: RwLock::new(last_block_hash),
4312 channel_state: Mutex::new(ChannelHolder {
4317 pending_msg_events: Vec::new(),
4319 our_network_key: args.keys_manager.get_node_secret(),
4321 last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
4323 per_peer_state: RwLock::new(per_peer_state),
4325 pending_events: Mutex::new(pending_events_read),
4326 pending_background_events: Mutex::new(pending_background_events_read),
4327 total_consistency_lock: RwLock::new(()),
4328 persistence_notifier: PersistenceNotifier::new(),
4330 keys_manager: args.keys_manager,
4331 logger: args.logger,
4332 default_configuration: args.default_config,
4335 for htlc_source in failed_htlcs.drain(..) {
4336 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() });
4339 //TODO: Broadcast channel update for closed channels, but only after we've made a
4340 //connection or two.
4342 Ok((last_block_hash.clone(), channel_manager))
4348 use ln::channelmanager::PersistenceNotifier;
4350 use std::sync::atomic::{AtomicBool, Ordering};
4352 use std::time::Duration;
4355 fn test_wait_timeout() {
4356 let persistence_notifier = Arc::new(PersistenceNotifier::new());
4357 let thread_notifier = Arc::clone(&persistence_notifier);
4359 let exit_thread = Arc::new(AtomicBool::new(false));
4360 let exit_thread_clone = exit_thread.clone();
4361 thread::spawn(move || {
4363 let &(ref persist_mtx, ref cnd) = &thread_notifier.persistence_lock;
4364 let mut persistence_lock = persist_mtx.lock().unwrap();
4365 *persistence_lock = true;
4368 if exit_thread_clone.load(Ordering::SeqCst) {
4374 // Check that we can block indefinitely until updates are available.
4375 let _ = persistence_notifier.wait();
4377 // Check that the PersistenceNotifier will return after the given duration if updates are
4380 if persistence_notifier.wait_timeout(Duration::from_millis(100)) {
4385 exit_thread.store(true, Ordering::SeqCst);
4387 // Check that the PersistenceNotifier will return after the given duration even if no updates
4390 if !persistence_notifier.wait_timeout(Duration::from_millis(100)) {