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::transaction::Transaction;
23 use bitcoin::blockdata::constants::genesis_block;
24 use bitcoin::network::constants::Network;
26 use bitcoin::hashes::{Hash, HashEngine};
27 use bitcoin::hashes::hmac::{Hmac, HmacEngine};
28 use bitcoin::hashes::sha256::Hash as Sha256;
29 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
30 use bitcoin::hashes::cmp::fixed_time_eq;
31 use bitcoin::hash_types::{BlockHash, Txid};
33 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
34 use bitcoin::secp256k1::Secp256k1;
35 use bitcoin::secp256k1::ecdh::SharedSecret;
36 use bitcoin::secp256k1;
41 use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
42 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};
43 use chain::transaction::{OutPoint, TransactionData};
44 // Since this struct is returned in `list_channels` methods, expose it here in case users want to
45 // construct one themselves.
46 use ln::{PaymentHash, PaymentPreimage, PaymentSecret};
47 pub use ln::channel::CounterpartyForwardingInfo;
48 use ln::channel::{Channel, ChannelError, ChannelUpdateStatus};
49 use ln::features::{InitFeatures, NodeFeatures};
50 use routing::router::{Route, RouteHop};
52 use ln::msgs::NetAddress;
54 use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, OptionalField};
55 use chain::keysinterface::{Sign, KeysInterface, KeysManager, InMemorySigner};
56 use util::config::UserConfig;
57 use util::events::{EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
58 use util::{byte_utils, events};
59 use util::ser::{Readable, ReadableArgs, MaybeReadable, Writeable, Writer};
60 use util::chacha20::{ChaCha20, ChaChaReader};
61 use util::logger::Logger;
62 use util::errors::APIError;
66 use core::cell::RefCell;
67 use std::collections::{HashMap, hash_map, HashSet};
68 use std::io::{Cursor, Read};
69 use std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard};
70 use core::sync::atomic::{AtomicUsize, Ordering};
71 use core::time::Duration;
72 #[cfg(any(test, feature = "allow_wallclock_use"))]
73 use std::time::Instant;
75 use bitcoin::hashes::hex::ToHex;
77 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
79 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
80 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
81 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
83 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
84 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
85 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
86 // before we forward it.
88 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
89 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
90 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
91 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
92 // our payment, which we can use to decode errors or inform the user that the payment was sent.
94 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
95 enum PendingHTLCRouting {
97 onion_packet: msgs::OnionPacket,
98 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
101 payment_data: msgs::FinalOnionHopData,
102 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
106 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
107 pub(super) struct PendingHTLCInfo {
108 routing: PendingHTLCRouting,
109 incoming_shared_secret: [u8; 32],
110 payment_hash: PaymentHash,
111 pub(super) amt_to_forward: u64,
112 pub(super) outgoing_cltv_value: u32,
115 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
116 pub(super) enum HTLCFailureMsg {
117 Relay(msgs::UpdateFailHTLC),
118 Malformed(msgs::UpdateFailMalformedHTLC),
121 /// Stores whether we can't forward an HTLC or relevant forwarding info
122 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
123 pub(super) enum PendingHTLCStatus {
124 Forward(PendingHTLCInfo),
125 Fail(HTLCFailureMsg),
128 pub(super) enum HTLCForwardInfo {
130 forward_info: PendingHTLCInfo,
132 // These fields are produced in `forward_htlcs()` and consumed in
133 // `process_pending_htlc_forwards()` for constructing the
134 // `HTLCSource::PreviousHopData` for failed and forwarded
136 prev_short_channel_id: u64,
138 prev_funding_outpoint: OutPoint,
142 err_packet: msgs::OnionErrorPacket,
146 /// Tracks the inbound corresponding to an outbound HTLC
147 #[derive(Clone, PartialEq)]
148 pub(crate) struct HTLCPreviousHopData {
149 short_channel_id: u64,
151 incoming_packet_shared_secret: [u8; 32],
153 // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
154 // channel with a preimage provided by the forward channel.
158 struct ClaimableHTLC {
159 prev_hop: HTLCPreviousHopData,
161 /// Contains a total_msat (which may differ from value if this is a Multi-Path Payment) and a
162 /// payment_secret which prevents path-probing attacks and can associate different HTLCs which
163 /// are part of the same payment.
164 payment_data: msgs::FinalOnionHopData,
168 /// Tracks the inbound corresponding to an outbound HTLC
169 #[derive(Clone, PartialEq)]
170 pub(crate) enum HTLCSource {
171 PreviousHopData(HTLCPreviousHopData),
174 session_priv: SecretKey,
175 /// Technically we can recalculate this from the route, but we cache it here to avoid
176 /// doing a double-pass on route when we get a failure back
177 first_hop_htlc_msat: u64,
182 pub fn dummy() -> Self {
183 HTLCSource::OutboundRoute {
185 session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
186 first_hop_htlc_msat: 0,
191 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
192 pub(super) enum HTLCFailReason {
194 err: msgs::OnionErrorPacket,
202 type ShutdownResult = (Option<(OutPoint, ChannelMonitorUpdate)>, Vec<(HTLCSource, PaymentHash)>);
204 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
205 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
206 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
207 /// channel_state lock. We then return the set of things that need to be done outside the lock in
208 /// this struct and call handle_error!() on it.
210 struct MsgHandleErrInternal {
211 err: msgs::LightningError,
212 shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
214 impl MsgHandleErrInternal {
216 fn send_err_msg_no_close(err: String, channel_id: [u8; 32]) -> Self {
218 err: LightningError {
220 action: msgs::ErrorAction::SendErrorMessage {
221 msg: msgs::ErrorMessage {
227 shutdown_finish: None,
231 fn ignore_no_close(err: String) -> Self {
233 err: LightningError {
235 action: msgs::ErrorAction::IgnoreError,
237 shutdown_finish: None,
241 fn from_no_close(err: msgs::LightningError) -> Self {
242 Self { err, shutdown_finish: None }
245 fn from_finish_shutdown(err: String, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
247 err: LightningError {
249 action: msgs::ErrorAction::SendErrorMessage {
250 msg: msgs::ErrorMessage {
256 shutdown_finish: Some((shutdown_res, channel_update)),
260 fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
263 ChannelError::Ignore(msg) => LightningError {
265 action: msgs::ErrorAction::IgnoreError,
267 ChannelError::Close(msg) => LightningError {
269 action: msgs::ErrorAction::SendErrorMessage {
270 msg: msgs::ErrorMessage {
276 ChannelError::CloseDelayBroadcast(msg) => LightningError {
278 action: msgs::ErrorAction::SendErrorMessage {
279 msg: msgs::ErrorMessage {
286 shutdown_finish: None,
291 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
292 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
293 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
294 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
295 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
297 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
298 /// be sent in the order they appear in the return value, however sometimes the order needs to be
299 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
300 /// they were originally sent). In those cases, this enum is also returned.
301 #[derive(Clone, PartialEq)]
302 pub(super) enum RAACommitmentOrder {
303 /// Send the CommitmentUpdate messages first
305 /// Send the RevokeAndACK message first
309 // Note this is only exposed in cfg(test):
310 pub(super) struct ChannelHolder<Signer: Sign> {
311 pub(super) by_id: HashMap<[u8; 32], Channel<Signer>>,
312 pub(super) short_to_id: HashMap<u64, [u8; 32]>,
313 /// short channel id -> forward infos. Key of 0 means payments received
314 /// Note that while this is held in the same mutex as the channels themselves, no consistency
315 /// guarantees are made about the existence of a channel with the short id here, nor the short
316 /// ids in the PendingHTLCInfo!
317 pub(super) forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
318 /// Map from payment hash to any HTLCs which are to us and can be failed/claimed by the user.
319 /// Note that while this is held in the same mutex as the channels themselves, no consistency
320 /// guarantees are made about the channels given here actually existing anymore by the time you
322 claimable_htlcs: HashMap<PaymentHash, Vec<ClaimableHTLC>>,
323 /// Messages to send to peers - pushed to in the same lock that they are generated in (except
324 /// for broadcast messages, where ordering isn't as strict).
325 pub(super) pending_msg_events: Vec<MessageSendEvent>,
328 /// Events which we process internally but cannot be procsesed immediately at the generation site
329 /// for some reason. They are handled in timer_tick_occurred, so may be processed with
330 /// quite some time lag.
331 enum BackgroundEvent {
332 /// Handle a ChannelMonitorUpdate that closes a channel, broadcasting its current latest holder
333 /// commitment transaction.
334 ClosingMonitorUpdate((OutPoint, ChannelMonitorUpdate)),
337 /// State we hold per-peer. In the future we should put channels in here, but for now we only hold
338 /// the latest Init features we heard from the peer.
340 latest_features: InitFeatures,
343 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
344 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
346 /// For users who don't want to bother doing their own payment preimage storage, we also store that
348 struct PendingInboundPayment {
349 /// The payment secret that the sender must use for us to accept this payment
350 payment_secret: PaymentSecret,
351 /// Time at which this HTLC expires - blocks with a header time above this value will result in
352 /// this payment being removed.
354 /// Arbitrary identifier the user specifies (or not)
355 user_payment_id: u64,
356 // Other required attributes of the payment, optionally enforced:
357 payment_preimage: Option<PaymentPreimage>,
358 min_value_msat: Option<u64>,
361 /// SimpleArcChannelManager is useful when you need a ChannelManager with a static lifetime, e.g.
362 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
363 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
364 /// SimpleRefChannelManager is the more appropriate type. Defining these type aliases prevents
365 /// issues such as overly long function definitions. Note that the ChannelManager can take any
366 /// type that implements KeysInterface for its keys manager, but this type alias chooses the
367 /// concrete type of the KeysManager.
368 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<InMemorySigner, Arc<M>, Arc<T>, Arc<KeysManager>, Arc<F>, Arc<L>>;
370 /// SimpleRefChannelManager is a type alias for a ChannelManager reference, and is the reference
371 /// counterpart to the SimpleArcChannelManager type alias. Use this type by default when you don't
372 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
373 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
374 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
375 /// helps with issues such as long function definitions. Note that the ChannelManager can take any
376 /// type that implements KeysInterface for its keys manager, but this type alias chooses the
377 /// concrete type of the KeysManager.
378 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManager<InMemorySigner, &'a M, &'b T, &'c KeysManager, &'d F, &'e L>;
380 /// Manager which keeps track of a number of channels and sends messages to the appropriate
381 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
383 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
384 /// to individual Channels.
386 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
387 /// all peers during write/read (though does not modify this instance, only the instance being
388 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
389 /// called funding_transaction_generated for outbound channels).
391 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
392 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
393 /// returning from chain::Watch::watch_/update_channel, with ChannelManagers, writing updates
394 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
395 /// the serialization process). If the deserialized version is out-of-date compared to the
396 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
397 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
399 /// Note that the deserializer is only implemented for (BlockHash, ChannelManager), which
400 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
401 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
402 /// block_connected() to step towards your best block) upon deserialization before using the
405 /// Note that ChannelManager is responsible for tracking liveness of its channels and generating
406 /// ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid
407 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
408 /// offline for a full minute. In order to track this, you must call
409 /// timer_tick_occurred roughly once per minute, though it doesn't have to be perfect.
411 /// Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager
412 /// a SimpleRefChannelManager, for conciseness. See their documentation for more details, but
413 /// essentially you should default to using a SimpleRefChannelManager, and use a
414 /// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
415 /// you're using lightning-net-tokio.
416 pub struct ChannelManager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
417 where M::Target: chain::Watch<Signer>,
418 T::Target: BroadcasterInterface,
419 K::Target: KeysInterface<Signer = Signer>,
420 F::Target: FeeEstimator,
423 default_configuration: UserConfig,
424 genesis_hash: BlockHash,
430 pub(super) best_block: RwLock<BestBlock>,
432 best_block: RwLock<BestBlock>,
433 secp_ctx: Secp256k1<secp256k1::All>,
435 #[cfg(any(test, feature = "_test_utils"))]
436 pub(super) channel_state: Mutex<ChannelHolder<Signer>>,
437 #[cfg(not(any(test, feature = "_test_utils")))]
438 channel_state: Mutex<ChannelHolder<Signer>>,
440 /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
441 /// expose them to users via a PaymentReceived event. HTLCs which do not meet the requirements
442 /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
443 /// after we generate a PaymentReceived upon receipt of all MPP parts or when they time out.
444 /// Locked *after* channel_state.
445 pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
447 /// The session_priv bytes of outbound payments which are pending resolution.
448 /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
449 /// (if the channel has been force-closed), however we track them here to prevent duplicative
450 /// PaymentSent/PaymentFailed events. Specifically, in the case of a duplicative
451 /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
452 /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
453 /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
454 /// after reloading from disk while replaying blocks against ChannelMonitors.
456 /// Locked *after* channel_state.
457 pending_outbound_payments: Mutex<HashSet<[u8; 32]>>,
459 our_network_key: SecretKey,
460 our_network_pubkey: PublicKey,
462 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
463 /// value increases strictly since we don't assume access to a time source.
464 last_node_announcement_serial: AtomicUsize,
466 /// The highest block timestamp we've seen, which is usually a good guess at the current time.
467 /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
468 /// very far in the past, and can only ever be up to two hours in the future.
469 highest_seen_timestamp: AtomicUsize,
471 /// The bulk of our storage will eventually be here (channels and message queues and the like).
472 /// If we are connected to a peer we always at least have an entry here, even if no channels
473 /// are currently open with that peer.
474 /// Because adding or removing an entry is rare, we usually take an outer read lock and then
475 /// operate on the inner value freely. Sadly, this prevents parallel operation when opening a
477 per_peer_state: RwLock<HashMap<PublicKey, Mutex<PeerState>>>,
479 pending_events: Mutex<Vec<events::Event>>,
480 pending_background_events: Mutex<Vec<BackgroundEvent>>,
481 /// Used when we have to take a BIG lock to make sure everything is self-consistent.
482 /// Essentially just when we're serializing ourselves out.
483 /// Taken first everywhere where we are making changes before any other locks.
484 /// When acquiring this lock in read mode, rather than acquiring it directly, call
485 /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
486 /// PersistenceNotifier the lock contains sends out a notification when the lock is released.
487 total_consistency_lock: RwLock<()>,
489 persistence_notifier: PersistenceNotifier,
496 /// Chain-related parameters used to construct a new `ChannelManager`.
498 /// Typically, the block-specific parameters are derived from the best block hash for the network,
499 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
500 /// are not needed when deserializing a previously constructed `ChannelManager`.
501 pub struct ChainParameters {
502 /// The network for determining the `chain_hash` in Lightning messages.
503 pub network: Network,
505 /// The hash and height of the latest block successfully connected.
507 /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
508 pub best_block: BestBlock,
511 /// The best known block as identified by its hash and height.
512 #[derive(Clone, Copy)]
513 pub struct BestBlock {
514 block_hash: BlockHash,
519 /// Returns the best block from the genesis of the given network.
520 pub fn from_genesis(network: Network) -> Self {
522 block_hash: genesis_block(network).header.block_hash(),
527 /// Returns the best block as identified by the given block hash and height.
528 pub fn new(block_hash: BlockHash, height: u32) -> Self {
529 BestBlock { block_hash, height }
532 /// Returns the best block hash.
533 pub fn block_hash(&self) -> BlockHash { self.block_hash }
535 /// Returns the best block height.
536 pub fn height(&self) -> u32 { self.height }
539 #[derive(Copy, Clone, PartialEq)]
545 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
546 /// desirable to notify any listeners on `await_persistable_update_timeout`/
547 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
548 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
549 /// sending the aforementioned notification (since the lock being released indicates that the
550 /// updates are ready for persistence).
552 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
553 /// notify or not based on whether relevant changes have been made, providing a closure to
554 /// `optionally_notify` which returns a `NotifyOption`.
555 struct PersistenceNotifierGuard<'a, F: Fn() -> NotifyOption> {
556 persistence_notifier: &'a PersistenceNotifier,
558 // We hold onto this result so the lock doesn't get released immediately.
559 _read_guard: RwLockReadGuard<'a, ()>,
562 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
563 fn notify_on_drop(lock: &'a RwLock<()>, notifier: &'a PersistenceNotifier) -> PersistenceNotifierGuard<'a, impl Fn() -> NotifyOption> {
564 PersistenceNotifierGuard::optionally_notify(lock, notifier, || -> NotifyOption { NotifyOption::DoPersist })
567 fn optionally_notify<F: Fn() -> NotifyOption>(lock: &'a RwLock<()>, notifier: &'a PersistenceNotifier, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
568 let read_guard = lock.read().unwrap();
570 PersistenceNotifierGuard {
571 persistence_notifier: notifier,
572 should_persist: persist_check,
573 _read_guard: read_guard,
578 impl<'a, F: Fn() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
580 if (self.should_persist)() == NotifyOption::DoPersist {
581 self.persistence_notifier.notify();
586 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
587 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
589 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
591 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
592 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
593 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
594 /// the maximum required amount in lnd as of March 2021.
595 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
597 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
598 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
600 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
602 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
603 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
604 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
605 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
606 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
607 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
608 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
610 /// Minimum CLTV difference between the current block height and received inbound payments.
611 /// Invoices generated for payment to us must set their `min_final_cltv_expiry` field to at least
613 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
614 // any payments to succeed. Further, we don't want payments to fail if a block was found while
615 // a payment was being routed, so we add an extra block to be safe.
616 pub const MIN_FINAL_CLTV_EXPIRY: u32 = HTLC_FAIL_BACK_BUFFER + 3;
618 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
619 // ie that if the next-hop peer fails the HTLC within
620 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
621 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
622 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
623 // LATENCY_GRACE_PERIOD_BLOCKS.
626 const CHECK_CLTV_EXPIRY_SANITY: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - CLTV_CLAIM_BUFFER - ANTI_REORG_DELAY - LATENCY_GRACE_PERIOD_BLOCKS;
628 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
629 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
632 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
634 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
636 pub struct ChannelDetails {
637 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
638 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
639 /// Note that this means this value is *not* persistent - it can change once during the
640 /// lifetime of the channel.
641 pub channel_id: [u8; 32],
642 /// The Channel's funding transaction output, if we've negotiated the funding transaction with
643 /// our counterparty already.
645 /// Note that, if this has been set, `channel_id` will be equivalent to
646 /// `funding_txo.unwrap().to_channel_id()`.
647 pub funding_txo: Option<OutPoint>,
648 /// The position of the funding transaction in the chain. None if the funding transaction has
649 /// not yet been confirmed and the channel fully opened.
650 pub short_channel_id: Option<u64>,
651 /// The node_id of our counterparty
652 pub remote_network_id: PublicKey,
653 /// The Features the channel counterparty provided upon last connection.
654 /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
655 /// many routing-relevant features are present in the init context.
656 pub counterparty_features: InitFeatures,
657 /// The value, in satoshis, of this channel as appears in the funding output
658 pub channel_value_satoshis: u64,
659 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
661 /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
662 /// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
663 /// available for inclusion in new outbound HTLCs). This further does not include any pending
664 /// outgoing HTLCs which are awaiting some other resolution to be sent.
665 pub outbound_capacity_msat: u64,
666 /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
667 /// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
668 /// available for inclusion in new inbound HTLCs).
669 /// Note that there are some corner cases not fully handled here, so the actual available
670 /// inbound capacity may be slightly higher than this.
671 pub inbound_capacity_msat: u64,
672 /// True if the channel was initiated (and thus funded) by us.
673 pub is_outbound: bool,
674 /// True if the channel is confirmed, funding_locked messages have been exchanged, and the
675 /// channel is not currently being shut down. `funding_locked` message exchange implies the
676 /// required confirmation count has been reached (and we were connected to the peer at some
677 /// point after the funding transaction received enough confirmations).
678 pub is_funding_locked: bool,
679 /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
680 /// the peer is connected, (c) no monitor update failure is pending resolution, and (d) the
681 /// channel is not currently negotiating a shutdown.
683 /// This is a strict superset of `is_funding_locked`.
685 /// True if this channel is (or will be) publicly-announced.
687 /// Information on the fees and requirements that the counterparty requires when forwarding
688 /// payments to us through this channel.
689 pub counterparty_forwarding_info: Option<CounterpartyForwardingInfo>,
692 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
693 /// Err() type describing which state the payment is in, see the description of individual enum
695 #[derive(Clone, Debug)]
696 pub enum PaymentSendFailure {
697 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
698 /// send the payment at all. No channel state has been changed or messages sent to peers, and
699 /// once you've changed the parameter at error, you can freely retry the payment in full.
700 ParameterError(APIError),
701 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
702 /// from attempting to send the payment at all. No channel state has been changed or messages
703 /// sent to peers, and once you've changed the parameter at error, you can freely retry the
706 /// The results here are ordered the same as the paths in the route object which was passed to
708 PathParameterError(Vec<Result<(), APIError>>),
709 /// All paths which were attempted failed to send, with no channel state change taking place.
710 /// You can freely retry the payment in full (though you probably want to do so over different
711 /// paths than the ones selected).
712 AllFailedRetrySafe(Vec<APIError>),
713 /// Some paths which were attempted failed to send, though possibly not all. At least some
714 /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
715 /// in over-/re-payment.
717 /// The results here are ordered the same as the paths in the route object which was passed to
718 /// send_payment, and any Errs which are not APIError::MonitorUpdateFailed can be safely
719 /// retried (though there is currently no API with which to do so).
721 /// Any entries which contain Err(APIError::MonitorUpdateFailed) or Ok(()) MUST NOT be retried
722 /// as they will result in over-/re-payment. These HTLCs all either successfully sent (in the
723 /// case of Ok(())) or will send once channel_monitor_updated is called on the next-hop channel
724 /// with the latest update_id.
725 PartialFailure(Vec<Result<(), APIError>>),
728 macro_rules! handle_error {
729 ($self: ident, $internal: expr, $counterparty_node_id: expr) => {
732 Err(MsgHandleErrInternal { err, shutdown_finish }) => {
733 #[cfg(debug_assertions)]
735 // In testing, ensure there are no deadlocks where the lock is already held upon
736 // entering the macro.
737 assert!($self.channel_state.try_lock().is_ok());
740 let mut msg_events = Vec::with_capacity(2);
742 if let Some((shutdown_res, update_option)) = shutdown_finish {
743 $self.finish_force_close_channel(shutdown_res);
744 if let Some(update) = update_option {
745 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
751 log_error!($self.logger, "{}", err.err);
752 if let msgs::ErrorAction::IgnoreError = err.action {
754 msg_events.push(events::MessageSendEvent::HandleError {
755 node_id: $counterparty_node_id,
756 action: err.action.clone()
760 if !msg_events.is_empty() {
761 $self.channel_state.lock().unwrap().pending_msg_events.append(&mut msg_events);
764 // Return error in case higher-API need one
771 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
772 macro_rules! convert_chan_err {
773 ($self: ident, $err: expr, $short_to_id: expr, $channel: expr, $channel_id: expr) => {
775 ChannelError::Ignore(msg) => {
776 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $channel_id.clone()))
778 ChannelError::Close(msg) => {
779 log_trace!($self.logger, "Closing channel {} due to close-required error: {}", log_bytes!($channel_id[..]), msg);
780 if let Some(short_id) = $channel.get_short_channel_id() {
781 $short_to_id.remove(&short_id);
783 let shutdown_res = $channel.force_shutdown(true);
784 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, shutdown_res, $self.get_channel_update(&$channel).ok()))
786 ChannelError::CloseDelayBroadcast(msg) => {
787 log_error!($self.logger, "Channel {} need to be shutdown but closing transactions not broadcast due to {}", log_bytes!($channel_id[..]), msg);
788 if let Some(short_id) = $channel.get_short_channel_id() {
789 $short_to_id.remove(&short_id);
791 let shutdown_res = $channel.force_shutdown(false);
792 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, shutdown_res, $self.get_channel_update(&$channel).ok()))
798 macro_rules! break_chan_entry {
799 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
803 let (drop, res) = convert_chan_err!($self, e, $channel_state.short_to_id, $entry.get_mut(), $entry.key());
805 $entry.remove_entry();
813 macro_rules! try_chan_entry {
814 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
818 let (drop, res) = convert_chan_err!($self, e, $channel_state.short_to_id, $entry.get_mut(), $entry.key());
820 $entry.remove_entry();
828 macro_rules! handle_monitor_err {
829 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
830 handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, Vec::new(), Vec::new())
832 ($self: ident, $err: expr, $short_to_id: expr, $chan: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr, $chan_id: expr) => {
834 ChannelMonitorUpdateErr::PermanentFailure => {
835 log_error!($self.logger, "Closing channel {} due to monitor update ChannelMonitorUpdateErr::PermanentFailure", log_bytes!($chan_id[..]));
836 if let Some(short_id) = $chan.get_short_channel_id() {
837 $short_to_id.remove(&short_id);
839 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
840 // chain in a confused state! We need to move them into the ChannelMonitor which
841 // will be responsible for failing backwards once things confirm on-chain.
842 // It's ok that we drop $failed_forwards here - at this point we'd rather they
843 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
844 // us bother trying to claim it just to forward on to another peer. If we're
845 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
846 // given up the preimage yet, so might as well just wait until the payment is
847 // retried, avoiding the on-chain fees.
848 let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure".to_owned(), *$chan_id, $chan.force_shutdown(true), $self.get_channel_update(&$chan).ok()));
851 ChannelMonitorUpdateErr::TemporaryFailure => {
852 log_info!($self.logger, "Disabling channel {} due to monitor update TemporaryFailure. On restore will send {} and process {} forwards and {} fails",
853 log_bytes!($chan_id[..]),
854 if $resend_commitment && $resend_raa {
856 RAACommitmentOrder::CommitmentFirst => { "commitment then RAA" },
857 RAACommitmentOrder::RevokeAndACKFirst => { "RAA then commitment" },
859 } else if $resend_commitment { "commitment" }
860 else if $resend_raa { "RAA" }
862 (&$failed_forwards as &Vec<(PendingHTLCInfo, u64)>).len(),
863 (&$failed_fails as &Vec<(HTLCSource, PaymentHash, HTLCFailReason)>).len());
864 if !$resend_commitment {
865 debug_assert!($action_type == RAACommitmentOrder::RevokeAndACKFirst || !$resend_raa);
868 debug_assert!($action_type == RAACommitmentOrder::CommitmentFirst || !$resend_commitment);
870 $chan.monitor_update_failed($resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
871 (Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor".to_owned()), *$chan_id)), false)
875 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => { {
876 let (res, drop) = handle_monitor_err!($self, $err, $channel_state.short_to_id, $entry.get_mut(), $action_type, $resend_raa, $resend_commitment, $failed_forwards, $failed_fails, $entry.key());
878 $entry.remove_entry();
884 macro_rules! return_monitor_err {
885 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
886 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment);
888 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
889 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
893 // Does not break in case of TemporaryFailure!
894 macro_rules! maybe_break_monitor_err {
895 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
896 match (handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment), $err) {
897 (e, ChannelMonitorUpdateErr::PermanentFailure) => {
900 (_, ChannelMonitorUpdateErr::TemporaryFailure) => { },
905 macro_rules! handle_chan_restoration_locked {
906 ($self: ident, $channel_lock: expr, $channel_state: expr, $channel_entry: expr,
907 $raa: expr, $commitment_update: expr, $order: expr, $chanmon_update: expr,
908 $pending_forwards: expr, $funding_broadcastable: expr, $funding_locked: expr) => { {
909 let mut htlc_forwards = None;
910 let counterparty_node_id = $channel_entry.get().get_counterparty_node_id();
912 let chanmon_update: Option<ChannelMonitorUpdate> = $chanmon_update; // Force type-checking to resolve
913 let chanmon_update_is_none = chanmon_update.is_none();
915 let forwards: Vec<(PendingHTLCInfo, u64)> = $pending_forwards; // Force type-checking to resolve
916 if !forwards.is_empty() {
917 htlc_forwards = Some(($channel_entry.get().get_short_channel_id().expect("We can't have pending forwards before funding confirmation"),
918 $channel_entry.get().get_funding_txo().unwrap(), forwards));
921 if chanmon_update.is_some() {
922 // On reconnect, we, by definition, only resend a funding_locked if there have been
923 // no commitment updates, so the only channel monitor update which could also be
924 // associated with a funding_locked would be the funding_created/funding_signed
925 // monitor update. That monitor update failing implies that we won't send
926 // funding_locked until it's been updated, so we can't have a funding_locked and a
927 // monitor update here (so we don't bother to handle it correctly below).
928 assert!($funding_locked.is_none());
929 // A channel monitor update makes no sense without either a funding_locked or a
930 // commitment update to process after it. Since we can't have a funding_locked, we
931 // only bother to handle the monitor-update + commitment_update case below.
932 assert!($commitment_update.is_some());
935 if let Some(msg) = $funding_locked {
936 // Similar to the above, this implies that we're letting the funding_locked fly
937 // before it should be allowed to.
938 assert!(chanmon_update.is_none());
939 $channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
940 node_id: counterparty_node_id,
943 if let Some(announcement_sigs) = $self.get_announcement_sigs($channel_entry.get()) {
944 $channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
945 node_id: counterparty_node_id,
946 msg: announcement_sigs,
949 $channel_state.short_to_id.insert($channel_entry.get().get_short_channel_id().unwrap(), $channel_entry.get().channel_id());
952 let funding_broadcastable: Option<Transaction> = $funding_broadcastable; // Force type-checking to resolve
953 if let Some(monitor_update) = chanmon_update {
954 // We only ever broadcast a funding transaction in response to a funding_signed
955 // message and the resulting monitor update. Thus, on channel_reestablish
956 // message handling we can't have a funding transaction to broadcast. When
957 // processing a monitor update finishing resulting in a funding broadcast, we
958 // cannot have a second monitor update, thus this case would indicate a bug.
959 assert!(funding_broadcastable.is_none());
960 // Given we were just reconnected or finished updating a channel monitor, the
961 // only case where we can get a new ChannelMonitorUpdate would be if we also
962 // have some commitment updates to send as well.
963 assert!($commitment_update.is_some());
964 if let Err(e) = $self.chain_monitor.update_channel($channel_entry.get().get_funding_txo().unwrap(), monitor_update) {
965 // channel_reestablish doesn't guarantee the order it returns is sensical
966 // for the messages it returns, but if we're setting what messages to
967 // re-transmit on monitor update success, we need to make sure it is sane.
968 let mut order = $order;
970 order = RAACommitmentOrder::CommitmentFirst;
972 break handle_monitor_err!($self, e, $channel_state, $channel_entry, order, $raa.is_some(), true);
976 macro_rules! handle_cs { () => {
977 if let Some(update) = $commitment_update {
978 $channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
979 node_id: counterparty_node_id,
984 macro_rules! handle_raa { () => {
985 if let Some(revoke_and_ack) = $raa {
986 $channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
987 node_id: counterparty_node_id,
993 RAACommitmentOrder::CommitmentFirst => {
997 RAACommitmentOrder::RevokeAndACKFirst => {
1002 if let Some(tx) = funding_broadcastable {
1003 log_info!($self.logger, "Broadcasting funding transaction with txid {}", tx.txid());
1004 $self.tx_broadcaster.broadcast_transaction(&tx);
1009 if chanmon_update_is_none {
1010 // If there was no ChannelMonitorUpdate, we should never generate an Err in the res loop
1011 // above. Doing so would imply calling handle_err!() from channel_monitor_updated() which
1012 // should *never* end up calling back to `chain_monitor.update_channel()`.
1013 assert!(res.is_ok());
1016 (htlc_forwards, res, counterparty_node_id)
1020 macro_rules! post_handle_chan_restoration {
1021 ($self: ident, $locked_res: expr) => { {
1022 let (htlc_forwards, res, counterparty_node_id) = $locked_res;
1024 let _ = handle_error!($self, res, counterparty_node_id);
1026 if let Some(forwards) = htlc_forwards {
1027 $self.forward_htlcs(&mut [forwards][..]);
1032 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
1033 where M::Target: chain::Watch<Signer>,
1034 T::Target: BroadcasterInterface,
1035 K::Target: KeysInterface<Signer = Signer>,
1036 F::Target: FeeEstimator,
1039 /// Constructs a new ChannelManager to hold several channels and route between them.
1041 /// This is the main "logic hub" for all channel-related actions, and implements
1042 /// ChannelMessageHandler.
1044 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
1046 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
1048 /// Users need to notify the new ChannelManager when a new block is connected or
1049 /// disconnected using its `block_connected` and `block_disconnected` methods, starting
1050 /// from after `params.latest_hash`.
1051 pub fn new(fee_est: F, chain_monitor: M, tx_broadcaster: T, logger: L, keys_manager: K, config: UserConfig, params: ChainParameters) -> Self {
1052 let mut secp_ctx = Secp256k1::new();
1053 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
1056 default_configuration: config.clone(),
1057 genesis_hash: genesis_block(params.network).header.block_hash(),
1058 fee_estimator: fee_est,
1062 best_block: RwLock::new(params.best_block),
1064 channel_state: Mutex::new(ChannelHolder{
1065 by_id: HashMap::new(),
1066 short_to_id: HashMap::new(),
1067 forward_htlcs: HashMap::new(),
1068 claimable_htlcs: HashMap::new(),
1069 pending_msg_events: Vec::new(),
1071 pending_inbound_payments: Mutex::new(HashMap::new()),
1072 pending_outbound_payments: Mutex::new(HashSet::new()),
1074 our_network_key: keys_manager.get_node_secret(),
1075 our_network_pubkey: PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()),
1078 last_node_announcement_serial: AtomicUsize::new(0),
1079 highest_seen_timestamp: AtomicUsize::new(0),
1081 per_peer_state: RwLock::new(HashMap::new()),
1083 pending_events: Mutex::new(Vec::new()),
1084 pending_background_events: Mutex::new(Vec::new()),
1085 total_consistency_lock: RwLock::new(()),
1086 persistence_notifier: PersistenceNotifier::new(),
1094 /// Gets the current configuration applied to all new channels, as
1095 pub fn get_current_default_configuration(&self) -> &UserConfig {
1096 &self.default_configuration
1099 /// Creates a new outbound channel to the given remote node and with the given value.
1101 /// user_id will be provided back as user_channel_id in FundingGenerationReady events to allow
1102 /// tracking of which events correspond with which create_channel call. Note that the
1103 /// user_channel_id defaults to 0 for inbound channels, so you may wish to avoid using 0 for
1104 /// user_id here. user_id has no meaning inside of LDK, it is simply copied to events and
1105 /// otherwise ignored.
1107 /// If successful, will generate a SendOpenChannel message event, so you should probably poll
1108 /// PeerManager::process_events afterwards.
1110 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
1111 /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
1112 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> {
1113 if channel_value_satoshis < 1000 {
1114 return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
1117 let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
1118 let channel = Channel::new_outbound(&self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, config)?;
1119 let res = channel.get_open_channel(self.genesis_hash.clone());
1121 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
1122 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
1123 debug_assert!(&self.total_consistency_lock.try_write().is_err());
1125 let mut channel_state = self.channel_state.lock().unwrap();
1126 match channel_state.by_id.entry(channel.channel_id()) {
1127 hash_map::Entry::Occupied(_) => {
1128 if cfg!(feature = "fuzztarget") {
1129 return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
1131 panic!("RNG is bad???");
1134 hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
1136 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
1137 node_id: their_network_key,
1143 fn list_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<Signer>)) -> bool>(&self, f: Fn) -> Vec<ChannelDetails> {
1144 let mut res = Vec::new();
1146 let channel_state = self.channel_state.lock().unwrap();
1147 res.reserve(channel_state.by_id.len());
1148 for (channel_id, channel) in channel_state.by_id.iter().filter(f) {
1149 let (inbound_capacity_msat, outbound_capacity_msat) = channel.get_inbound_outbound_available_balance_msat();
1150 res.push(ChannelDetails {
1151 channel_id: (*channel_id).clone(),
1152 funding_txo: channel.get_funding_txo(),
1153 short_channel_id: channel.get_short_channel_id(),
1154 remote_network_id: channel.get_counterparty_node_id(),
1155 counterparty_features: InitFeatures::empty(),
1156 channel_value_satoshis: channel.get_value_satoshis(),
1157 inbound_capacity_msat,
1158 outbound_capacity_msat,
1159 user_id: channel.get_user_id(),
1160 is_outbound: channel.is_outbound(),
1161 is_funding_locked: channel.is_usable(),
1162 is_usable: channel.is_live(),
1163 is_public: channel.should_announce(),
1164 counterparty_forwarding_info: channel.counterparty_forwarding_info(),
1168 let per_peer_state = self.per_peer_state.read().unwrap();
1169 for chan in res.iter_mut() {
1170 if let Some(peer_state) = per_peer_state.get(&chan.remote_network_id) {
1171 chan.counterparty_features = peer_state.lock().unwrap().latest_features.clone();
1177 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
1178 /// more information.
1179 pub fn list_channels(&self) -> Vec<ChannelDetails> {
1180 self.list_channels_with_filter(|_| true)
1183 /// Gets the list of usable channels, in random order. Useful as an argument to
1184 /// get_route to ensure non-announced channels are used.
1186 /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
1187 /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
1189 pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
1190 // Note we use is_live here instead of usable which leads to somewhat confused
1191 // internal/external nomenclature, but that's ok cause that's probably what the user
1192 // really wanted anyway.
1193 self.list_channels_with_filter(|&(_, ref channel)| channel.is_live())
1196 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
1197 /// will be accepted on the given channel, and after additional timeout/the closing of all
1198 /// pending HTLCs, the channel will be closed on chain.
1200 /// May generate a SendShutdown message event on success, which should be relayed.
1201 pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
1202 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
1204 let (mut failed_htlcs, chan_option) = {
1205 let mut channel_state_lock = self.channel_state.lock().unwrap();
1206 let channel_state = &mut *channel_state_lock;
1207 match channel_state.by_id.entry(channel_id.clone()) {
1208 hash_map::Entry::Occupied(mut chan_entry) => {
1209 let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
1210 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1211 node_id: chan_entry.get().get_counterparty_node_id(),
1214 if chan_entry.get().is_shutdown() {
1215 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1216 channel_state.short_to_id.remove(&short_id);
1218 (failed_htlcs, Some(chan_entry.remove_entry().1))
1219 } else { (failed_htlcs, None) }
1221 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()})
1224 for htlc_source in failed_htlcs.drain(..) {
1225 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() });
1227 let chan_update = if let Some(chan) = chan_option {
1228 if let Ok(update) = self.get_channel_update(&chan) {
1233 if let Some(update) = chan_update {
1234 let mut channel_state = self.channel_state.lock().unwrap();
1235 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1244 fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
1245 let (monitor_update_option, mut failed_htlcs) = shutdown_res;
1246 log_trace!(self.logger, "Finishing force-closure of channel {} HTLCs to fail", failed_htlcs.len());
1247 for htlc_source in failed_htlcs.drain(..) {
1248 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() });
1250 if let Some((funding_txo, monitor_update)) = monitor_update_option {
1251 // There isn't anything we can do if we get an update failure - we're already
1252 // force-closing. The monitor update on the required in-memory copy should broadcast
1253 // the latest local state, which is the best we can do anyway. Thus, it is safe to
1254 // ignore the result here.
1255 let _ = self.chain_monitor.update_channel(funding_txo, monitor_update);
1259 fn force_close_channel_with_peer(&self, channel_id: &[u8; 32], peer_node_id: Option<&PublicKey>) -> Result<PublicKey, APIError> {
1261 let mut channel_state_lock = self.channel_state.lock().unwrap();
1262 let channel_state = &mut *channel_state_lock;
1263 if let hash_map::Entry::Occupied(chan) = channel_state.by_id.entry(channel_id.clone()) {
1264 if let Some(node_id) = peer_node_id {
1265 if chan.get().get_counterparty_node_id() != *node_id {
1266 return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()});
1269 if let Some(short_id) = chan.get().get_short_channel_id() {
1270 channel_state.short_to_id.remove(&short_id);
1272 chan.remove_entry().1
1274 return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()});
1277 log_trace!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
1278 self.finish_force_close_channel(chan.force_shutdown(true));
1279 if let Ok(update) = self.get_channel_update(&chan) {
1280 let mut channel_state = self.channel_state.lock().unwrap();
1281 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1286 Ok(chan.get_counterparty_node_id())
1289 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
1290 /// the chain and rejecting new HTLCs on the given channel. Fails if channel_id is unknown to the manager.
1291 pub fn force_close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
1292 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
1293 match self.force_close_channel_with_peer(channel_id, None) {
1294 Ok(counterparty_node_id) => {
1295 self.channel_state.lock().unwrap().pending_msg_events.push(
1296 events::MessageSendEvent::HandleError {
1297 node_id: counterparty_node_id,
1298 action: msgs::ErrorAction::SendErrorMessage {
1299 msg: msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() }
1309 /// Force close all channels, immediately broadcasting the latest local commitment transaction
1310 /// for each to the chain and rejecting new HTLCs on each.
1311 pub fn force_close_all_channels(&self) {
1312 for chan in self.list_channels() {
1313 let _ = self.force_close_channel(&chan.channel_id);
1317 fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder<Signer>>) {
1318 macro_rules! return_malformed_err {
1319 ($msg: expr, $err_code: expr) => {
1321 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
1322 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
1323 channel_id: msg.channel_id,
1324 htlc_id: msg.htlc_id,
1325 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
1326 failure_code: $err_code,
1327 })), self.channel_state.lock().unwrap());
1332 if let Err(_) = msg.onion_routing_packet.public_key {
1333 return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
1336 let shared_secret = {
1337 let mut arr = [0; 32];
1338 arr.copy_from_slice(&SharedSecret::new(&msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
1341 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(&shared_secret);
1343 if msg.onion_routing_packet.version != 0 {
1344 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1345 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1346 //the hash doesn't really serve any purpose - in the case of hashing all data, the
1347 //receiving node would have to brute force to figure out which version was put in the
1348 //packet by the node that send us the message, in the case of hashing the hop_data, the
1349 //node knows the HMAC matched, so they already know what is there...
1350 return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
1353 let mut hmac = HmacEngine::<Sha256>::new(&mu);
1354 hmac.input(&msg.onion_routing_packet.hop_data);
1355 hmac.input(&msg.payment_hash.0[..]);
1356 if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
1357 return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
1360 let mut channel_state = None;
1361 macro_rules! return_err {
1362 ($msg: expr, $err_code: expr, $data: expr) => {
1364 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
1365 if channel_state.is_none() {
1366 channel_state = Some(self.channel_state.lock().unwrap());
1368 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1369 channel_id: msg.channel_id,
1370 htlc_id: msg.htlc_id,
1371 reason: onion_utils::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1372 })), channel_state.unwrap());
1377 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1378 let mut chacha_stream = ChaChaReader { chacha: &mut chacha, read: Cursor::new(&msg.onion_routing_packet.hop_data[..]) };
1379 let (next_hop_data, next_hop_hmac) = {
1380 match msgs::OnionHopData::read(&mut chacha_stream) {
1382 let error_code = match err {
1383 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1384 msgs::DecodeError::UnknownRequiredFeature|
1385 msgs::DecodeError::InvalidValue|
1386 msgs::DecodeError::ShortRead => 0x4000 | 22, // invalid_onion_payload
1387 _ => 0x2000 | 2, // Should never happen
1389 return_err!("Unable to decode our hop data", error_code, &[0;0]);
1392 let mut hmac = [0; 32];
1393 if let Err(_) = chacha_stream.read_exact(&mut hmac[..]) {
1394 return_err!("Unable to decode hop data", 0x4000 | 22, &[0;0]);
1401 let pending_forward_info = if next_hop_hmac == [0; 32] {
1404 // In tests, make sure that the initial onion pcket data is, at least, non-0.
1405 // We could do some fancy randomness test here, but, ehh, whatever.
1406 // This checks for the issue where you can calculate the path length given the
1407 // onion data as all the path entries that the originator sent will be here
1408 // as-is (and were originally 0s).
1409 // Of course reverse path calculation is still pretty easy given naive routing
1410 // algorithms, but this fixes the most-obvious case.
1411 let mut next_bytes = [0; 32];
1412 chacha_stream.read_exact(&mut next_bytes).unwrap();
1413 assert_ne!(next_bytes[..], [0; 32][..]);
1414 chacha_stream.read_exact(&mut next_bytes).unwrap();
1415 assert_ne!(next_bytes[..], [0; 32][..]);
1419 // final_expiry_too_soon
1420 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure we have at least
1421 // HTLC_FAIL_BACK_BUFFER blocks to go.
1422 // Also, ensure that, in the case of an unknown payment hash, our payment logic has enough time to fail the HTLC backward
1423 // before our onchain logic triggers a channel closure (see HTLC_FAIL_BACK_BUFFER rational).
1424 if (msg.cltv_expiry as u64) <= self.best_block.read().unwrap().height() as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1 {
1425 return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1427 // final_incorrect_htlc_amount
1428 if next_hop_data.amt_to_forward > msg.amount_msat {
1429 return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1431 // final_incorrect_cltv_expiry
1432 if next_hop_data.outgoing_cltv_value != msg.cltv_expiry {
1433 return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1436 let payment_data = match next_hop_data.format {
1437 msgs::OnionHopDataFormat::Legacy { .. } => None,
1438 msgs::OnionHopDataFormat::NonFinalNode { .. } => return_err!("Got non final data with an HMAC of 0", 0x4000 | 22, &[0;0]),
1439 msgs::OnionHopDataFormat::FinalNode { payment_data } => payment_data,
1442 if payment_data.is_none() {
1443 return_err!("We require payment_secrets", 0x4000|0x2000|3, &[0;0]);
1446 // Note that we could obviously respond immediately with an update_fulfill_htlc
1447 // message, however that would leak that we are the recipient of this payment, so
1448 // instead we stay symmetric with the forwarding case, only responding (after a
1449 // delay) once they've send us a commitment_signed!
1451 PendingHTLCStatus::Forward(PendingHTLCInfo {
1452 routing: PendingHTLCRouting::Receive {
1453 payment_data: payment_data.unwrap(),
1454 incoming_cltv_expiry: msg.cltv_expiry,
1456 payment_hash: msg.payment_hash.clone(),
1457 incoming_shared_secret: shared_secret,
1458 amt_to_forward: next_hop_data.amt_to_forward,
1459 outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1462 let mut new_packet_data = [0; 20*65];
1463 let read_pos = chacha_stream.read(&mut new_packet_data).unwrap();
1464 #[cfg(debug_assertions)]
1466 // Check two things:
1467 // a) that the behavior of our stream here will return Ok(0) even if the TLV
1468 // read above emptied out our buffer and the unwrap() wont needlessly panic
1469 // b) that we didn't somehow magically end up with extra data.
1471 debug_assert!(chacha_stream.read(&mut t).unwrap() == 0);
1473 // Once we've emptied the set of bytes our peer gave us, encrypt 0 bytes until we
1474 // fill the onion hop data we'll forward to our next-hop peer.
1475 chacha_stream.chacha.process_in_place(&mut new_packet_data[read_pos..]);
1477 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1479 let blinding_factor = {
1480 let mut sha = Sha256::engine();
1481 sha.input(&new_pubkey.serialize()[..]);
1482 sha.input(&shared_secret);
1483 Sha256::from_engine(sha).into_inner()
1486 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor[..]) {
1488 } else { Ok(new_pubkey) };
1490 let outgoing_packet = msgs::OnionPacket {
1493 hop_data: new_packet_data,
1494 hmac: next_hop_hmac.clone(),
1497 let short_channel_id = match next_hop_data.format {
1498 msgs::OnionHopDataFormat::Legacy { short_channel_id } => short_channel_id,
1499 msgs::OnionHopDataFormat::NonFinalNode { short_channel_id } => short_channel_id,
1500 msgs::OnionHopDataFormat::FinalNode { .. } => {
1501 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0;0]);
1505 PendingHTLCStatus::Forward(PendingHTLCInfo {
1506 routing: PendingHTLCRouting::Forward {
1507 onion_packet: outgoing_packet,
1510 payment_hash: msg.payment_hash.clone(),
1511 incoming_shared_secret: shared_secret,
1512 amt_to_forward: next_hop_data.amt_to_forward,
1513 outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1517 channel_state = Some(self.channel_state.lock().unwrap());
1518 if let &PendingHTLCStatus::Forward(PendingHTLCInfo { ref routing, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1519 // If short_channel_id is 0 here, we'll reject the HTLC as there cannot be a channel
1520 // with a short_channel_id of 0. This is important as various things later assume
1521 // short_channel_id is non-0 in any ::Forward.
1522 if let &PendingHTLCRouting::Forward { ref short_channel_id, .. } = routing {
1523 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1524 let forwarding_id = match id_option {
1525 None => { // unknown_next_peer
1526 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1528 Some(id) => id.clone(),
1530 if let Some((err, code, chan_update)) = loop {
1531 let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1533 // Note that we could technically not return an error yet here and just hope
1534 // that the connection is reestablished or monitor updated by the time we get
1535 // around to doing the actual forward, but better to fail early if we can and
1536 // hopefully an attacker trying to path-trace payments cannot make this occur
1537 // on a small/per-node/per-channel scale.
1538 if !chan.is_live() { // channel_disabled
1539 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1541 if *amt_to_forward < chan.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
1542 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1544 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) });
1545 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1546 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())));
1548 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + chan.get_cltv_expiry_delta() as u64 { // incorrect_cltv_expiry
1549 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())));
1551 let cur_height = self.best_block.read().unwrap().height() + 1;
1552 // Theoretically, channel counterparty shouldn't send us a HTLC expiring now, but we want to be robust wrt to counterparty
1553 // packet sanitization (see HTLC_FAIL_BACK_BUFFER rational)
1554 if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
1555 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1557 if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1558 break Some(("CLTV expiry is too far in the future", 21, None));
1560 // In theory, we would be safe against unitentional channel-closure, if we only required a margin of LATENCY_GRACE_PERIOD_BLOCKS.
1561 // But, to be safe against policy reception, we use a longuer delay.
1562 if (*outgoing_cltv_value) as u64 <= (cur_height + HTLC_FAIL_BACK_BUFFER) as u64 {
1563 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1569 let mut res = Vec::with_capacity(8 + 128);
1570 if let Some(chan_update) = chan_update {
1571 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1572 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1574 else if code == 0x1000 | 13 {
1575 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1577 else if code == 0x1000 | 20 {
1578 // TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
1579 res.extend_from_slice(&byte_utils::be16_to_array(0));
1581 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1583 return_err!(err, code, &res[..]);
1588 (pending_forward_info, channel_state.unwrap())
1591 /// only fails if the channel does not yet have an assigned short_id
1592 /// May be called with channel_state already locked!
1593 fn get_channel_update(&self, chan: &Channel<Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
1594 let short_channel_id = match chan.get_short_channel_id() {
1595 None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
1599 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_counterparty_node_id().serialize()[..];
1601 let unsigned = msgs::UnsignedChannelUpdate {
1602 chain_hash: self.genesis_hash,
1604 timestamp: chan.get_update_time_counter(),
1605 flags: (!were_node_one) as u8 | ((!chan.is_live() as u8) << 1),
1606 cltv_expiry_delta: chan.get_cltv_expiry_delta(),
1607 htlc_minimum_msat: chan.get_counterparty_htlc_minimum_msat(),
1608 htlc_maximum_msat: OptionalField::Present(chan.get_announced_htlc_max_msat()),
1609 fee_base_msat: chan.get_holder_fee_base_msat(&self.fee_estimator),
1610 fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1611 excess_data: Vec::new(),
1614 let msg_hash = Sha256dHash::hash(&unsigned.encode()[..]);
1615 let sig = self.secp_ctx.sign(&hash_to_message!(&msg_hash[..]), &self.our_network_key);
1617 Ok(msgs::ChannelUpdate {
1623 // Only public for testing, this should otherwise never be called direcly
1624 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> {
1625 log_trace!(self.logger, "Attempting to send payment for path with next hop {}", path.first().unwrap().short_channel_id);
1626 let prng_seed = self.keys_manager.get_secure_random_bytes();
1627 let session_priv_bytes = self.keys_manager.get_secure_random_bytes();
1628 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
1630 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
1631 .map_err(|_| APIError::RouteError{err: "Pubkey along hop was maliciously selected"})?;
1632 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, payment_secret, cur_height)?;
1633 if onion_utils::route_size_insane(&onion_payloads) {
1634 return Err(APIError::RouteError{err: "Route size too large considering onion data"});
1636 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash);
1638 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
1639 assert!(self.pending_outbound_payments.lock().unwrap().insert(session_priv_bytes));
1641 let err: Result<(), _> = loop {
1642 let mut channel_lock = self.channel_state.lock().unwrap();
1643 let id = match channel_lock.short_to_id.get(&path.first().unwrap().short_channel_id) {
1644 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
1645 Some(id) => id.clone(),
1648 let channel_state = &mut *channel_lock;
1649 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1651 if chan.get().get_counterparty_node_id() != path.first().unwrap().pubkey {
1652 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1654 if !chan.get().is_live() {
1655 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!".to_owned()});
1657 break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1659 session_priv: session_priv.clone(),
1660 first_hop_htlc_msat: htlc_msat,
1661 }, onion_packet, &self.logger), channel_state, chan)
1663 Some((update_add, commitment_signed, monitor_update)) => {
1664 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
1665 maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true);
1666 // Note that MonitorUpdateFailed here indicates (per function docs)
1667 // that we will resend the commitment update once monitor updating
1668 // is restored. Therefore, we must return an error indicating that
1669 // it is unsafe to retry the payment wholesale, which we do in the
1670 // send_payment check for MonitorUpdateFailed, below.
1671 return Err(APIError::MonitorUpdateFailed);
1674 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1675 node_id: path.first().unwrap().pubkey,
1676 updates: msgs::CommitmentUpdate {
1677 update_add_htlcs: vec![update_add],
1678 update_fulfill_htlcs: Vec::new(),
1679 update_fail_htlcs: Vec::new(),
1680 update_fail_malformed_htlcs: Vec::new(),
1688 } else { unreachable!(); }
1692 match handle_error!(self, err, path.first().unwrap().pubkey) {
1693 Ok(_) => unreachable!(),
1695 Err(APIError::ChannelUnavailable { err: e.err })
1700 /// Sends a payment along a given route.
1702 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1703 /// fields for more info.
1705 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1706 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1707 /// next hop knows the preimage to payment_hash they can claim an additional amount as
1708 /// specified in the last hop in the route! Thus, you should probably do your own
1709 /// payment_preimage tracking (which you should already be doing as they represent "proof of
1710 /// payment") and prevent double-sends yourself.
1712 /// May generate SendHTLCs message(s) event on success, which should be relayed.
1714 /// Each path may have a different return value, and PaymentSendValue may return a Vec with
1715 /// each entry matching the corresponding-index entry in the route paths, see
1716 /// PaymentSendFailure for more info.
1718 /// In general, a path may raise:
1719 /// * APIError::RouteError when an invalid route or forwarding parameter (cltv_delta, fee,
1720 /// node public key) is specified.
1721 /// * APIError::ChannelUnavailable if the next-hop channel is not available for updates
1722 /// (including due to previous monitor update failure or new permanent monitor update
1724 /// * APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1725 /// relevant updates.
1727 /// Note that depending on the type of the PaymentSendFailure the HTLC may have been
1728 /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
1729 /// different route unless you intend to pay twice!
1731 /// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
1732 /// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
1733 /// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
1734 /// must not contain multiple paths as multi-path payments require a recipient-provided
1736 /// If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
1737 /// bit set (either as required or as available). If multiple paths are present in the Route,
1738 /// we assume the invoice had the basic_mpp feature set.
1739 pub fn send_payment(&self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>) -> Result<(), PaymentSendFailure> {
1740 if route.paths.len() < 1 {
1741 return Err(PaymentSendFailure::ParameterError(APIError::RouteError{err: "There must be at least one path to send over"}));
1743 if route.paths.len() > 10 {
1744 // This limit is completely arbitrary - there aren't any real fundamental path-count
1745 // limits. After we support retrying individual paths we should likely bump this, but
1746 // for now more than 10 paths likely carries too much one-path failure.
1747 return Err(PaymentSendFailure::ParameterError(APIError::RouteError{err: "Sending over more than 10 paths is not currently supported"}));
1749 let mut total_value = 0;
1750 let our_node_id = self.get_our_node_id();
1751 let mut path_errs = Vec::with_capacity(route.paths.len());
1752 'path_check: for path in route.paths.iter() {
1753 if path.len() < 1 || path.len() > 20 {
1754 path_errs.push(Err(APIError::RouteError{err: "Path didn't go anywhere/had bogus size"}));
1755 continue 'path_check;
1757 for (idx, hop) in path.iter().enumerate() {
1758 if idx != path.len() - 1 && hop.pubkey == our_node_id {
1759 path_errs.push(Err(APIError::RouteError{err: "Path went through us but wasn't a simple rebalance loop to us"}));
1760 continue 'path_check;
1763 total_value += path.last().unwrap().fee_msat;
1764 path_errs.push(Ok(()));
1766 if path_errs.iter().any(|e| e.is_err()) {
1767 return Err(PaymentSendFailure::PathParameterError(path_errs));
1770 let cur_height = self.best_block.read().unwrap().height() + 1;
1771 let mut results = Vec::new();
1772 for path in route.paths.iter() {
1773 results.push(self.send_payment_along_path(&path, &payment_hash, payment_secret, total_value, cur_height));
1775 let mut has_ok = false;
1776 let mut has_err = false;
1777 for res in results.iter() {
1778 if res.is_ok() { has_ok = true; }
1779 if res.is_err() { has_err = true; }
1780 if let &Err(APIError::MonitorUpdateFailed) = res {
1781 // MonitorUpdateFailed is inherently unsafe to retry, so we call it a
1788 if has_err && has_ok {
1789 Err(PaymentSendFailure::PartialFailure(results))
1791 Err(PaymentSendFailure::AllFailedRetrySafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1797 /// Handles the generation of a funding transaction, optionally (for tests) with a function
1798 /// which checks the correctness of the funding transaction given the associated channel.
1799 fn funding_transaction_generated_intern<FundingOutput: Fn(&Channel<Signer>, &Transaction) -> Result<OutPoint, APIError>>
1800 (&self, temporary_channel_id: &[u8; 32], funding_transaction: Transaction, find_funding_output: FundingOutput) -> Result<(), APIError> {
1802 let (res, chan) = match self.channel_state.lock().unwrap().by_id.remove(temporary_channel_id) {
1804 let funding_txo = find_funding_output(&chan, &funding_transaction)?;
1806 (chan.get_outbound_funding_created(funding_transaction, funding_txo, &self.logger)
1807 .map_err(|e| if let ChannelError::Close(msg) = e {
1808 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(true), None)
1809 } else { unreachable!(); })
1812 None => { return Err(APIError::ChannelUnavailable { err: "No such channel".to_owned() }) },
1814 match handle_error!(self, res, chan.get_counterparty_node_id()) {
1815 Ok(funding_msg) => {
1818 Err(_) => { return Err(APIError::ChannelUnavailable {
1819 err: "Error deriving keys or signing initial commitment transactions - either our RNG or our counterparty's RNG is broken or the Signer refused to sign".to_owned()
1824 let mut channel_state = self.channel_state.lock().unwrap();
1825 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1826 node_id: chan.get_counterparty_node_id(),
1829 match channel_state.by_id.entry(chan.channel_id()) {
1830 hash_map::Entry::Occupied(_) => {
1831 panic!("Generated duplicate funding txid?");
1833 hash_map::Entry::Vacant(e) => {
1841 pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: &[u8; 32], funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> {
1842 self.funding_transaction_generated_intern(temporary_channel_id, funding_transaction, |_, tx| {
1843 Ok(OutPoint { txid: tx.txid(), index: output_index })
1847 /// Call this upon creation of a funding transaction for the given channel.
1849 /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
1850 /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
1852 /// Panics if a funding transaction has already been provided for this channel.
1854 /// May panic if the output found in the funding transaction is duplicative with some other
1855 /// channel (note that this should be trivially prevented by using unique funding transaction
1856 /// keys per-channel).
1858 /// Do NOT broadcast the funding transaction yourself. When we have safely received our
1859 /// counterparty's signature the funding transaction will automatically be broadcast via the
1860 /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
1862 /// Note that this includes RBF or similar transaction replacement strategies - lightning does
1863 /// not currently support replacing a funding transaction on an existing channel. Instead,
1864 /// create a new channel with a conflicting funding transaction.
1866 /// [`Event::FundingGenerationReady`]: crate::util::events::Event::FundingGenerationReady
1867 pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_transaction: Transaction) -> Result<(), APIError> {
1868 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
1870 for inp in funding_transaction.input.iter() {
1871 if inp.witness.is_empty() {
1872 return Err(APIError::APIMisuseError {
1873 err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
1877 self.funding_transaction_generated_intern(temporary_channel_id, funding_transaction, |chan, tx| {
1878 let mut output_index = None;
1879 let expected_spk = chan.get_funding_redeemscript().to_v0_p2wsh();
1880 for (idx, outp) in tx.output.iter().enumerate() {
1881 if outp.script_pubkey == expected_spk && outp.value == chan.get_value_satoshis() {
1882 if output_index.is_some() {
1883 return Err(APIError::APIMisuseError {
1884 err: "Multiple outputs matched the expected script and value".to_owned()
1887 if idx > u16::max_value() as usize {
1888 return Err(APIError::APIMisuseError {
1889 err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
1892 output_index = Some(idx as u16);
1895 if output_index.is_none() {
1896 return Err(APIError::APIMisuseError {
1897 err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
1900 Ok(OutPoint { txid: tx.txid(), index: output_index.unwrap() })
1904 fn get_announcement_sigs(&self, chan: &Channel<Signer>) -> Option<msgs::AnnouncementSignatures> {
1905 if !chan.should_announce() {
1906 log_trace!(self.logger, "Can't send announcement_signatures for private channel {}", log_bytes!(chan.channel_id()));
1910 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1912 Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1914 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1915 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1917 Some(msgs::AnnouncementSignatures {
1918 channel_id: chan.channel_id(),
1919 short_channel_id: chan.get_short_channel_id().unwrap(),
1920 node_signature: our_node_sig,
1921 bitcoin_signature: our_bitcoin_sig,
1926 // Messages of up to 64KB should never end up more than half full with addresses, as that would
1927 // be absurd. We ensure this by checking that at least 500 (our stated public contract on when
1928 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
1930 const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
1933 // ...by failing to compile if the number of addresses that would be half of a message is
1934 // smaller than 500:
1935 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 500;
1937 /// Regenerates channel_announcements and generates a signed node_announcement from the given
1938 /// arguments, providing them in corresponding events via
1939 /// [`get_and_clear_pending_msg_events`], if at least one public channel has been confirmed
1940 /// on-chain. This effectively re-broadcasts all channel announcements and sends our node
1941 /// announcement to ensure that the lightning P2P network is aware of the channels we have and
1942 /// our network addresses.
1944 /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
1945 /// node to humans. They carry no in-protocol meaning.
1947 /// `addresses` represent the set (possibly empty) of socket addresses on which this node
1948 /// accepts incoming connections. These will be included in the node_announcement, publicly
1949 /// tying these addresses together and to this node. If you wish to preserve user privacy,
1950 /// addresses should likely contain only Tor Onion addresses.
1952 /// Panics if `addresses` is absurdly large (more than 500).
1954 /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
1955 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<NetAddress>) {
1956 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
1958 if addresses.len() > 500 {
1959 panic!("More than half the message size was taken up by public addresses!");
1962 // While all existing nodes handle unsorted addresses just fine, the spec requires that
1963 // addresses be sorted for future compatibility.
1964 addresses.sort_by_key(|addr| addr.get_id());
1966 let announcement = msgs::UnsignedNodeAnnouncement {
1967 features: NodeFeatures::known(),
1968 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1969 node_id: self.get_our_node_id(),
1970 rgb, alias, addresses,
1971 excess_address_data: Vec::new(),
1972 excess_data: Vec::new(),
1974 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1975 let node_announce_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1977 let mut channel_state_lock = self.channel_state.lock().unwrap();
1978 let channel_state = &mut *channel_state_lock;
1980 let mut announced_chans = false;
1981 for (_, chan) in channel_state.by_id.iter() {
1982 if let Some(msg) = chan.get_signed_channel_announcement(&self.our_network_key, self.get_our_node_id(), self.genesis_hash.clone()) {
1983 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
1985 update_msg: match self.get_channel_update(chan) {
1990 announced_chans = true;
1992 // If the channel is not public or has not yet reached funding_locked, check the
1993 // next channel. If we don't yet have any public channels, we'll skip the broadcast
1994 // below as peers may not accept it without channels on chain first.
1998 if announced_chans {
1999 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
2000 msg: msgs::NodeAnnouncement {
2001 signature: node_announce_sig,
2002 contents: announcement
2008 /// Processes HTLCs which are pending waiting on random forward delay.
2010 /// Should only really ever be called in response to a PendingHTLCsForwardable event.
2011 /// Will likely generate further events.
2012 pub fn process_pending_htlc_forwards(&self) {
2013 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2015 let mut new_events = Vec::new();
2016 let mut failed_forwards = Vec::new();
2017 let mut handle_errors = Vec::new();
2019 let mut channel_state_lock = self.channel_state.lock().unwrap();
2020 let channel_state = &mut *channel_state_lock;
2022 for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
2023 if short_chan_id != 0 {
2024 let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
2025 Some(chan_id) => chan_id.clone(),
2027 failed_forwards.reserve(pending_forwards.len());
2028 for forward_info in pending_forwards.drain(..) {
2029 match forward_info {
2030 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info,
2031 prev_funding_outpoint } => {
2032 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
2033 short_channel_id: prev_short_channel_id,
2034 outpoint: prev_funding_outpoint,
2035 htlc_id: prev_htlc_id,
2036 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
2038 failed_forwards.push((htlc_source, forward_info.payment_hash,
2039 HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() }
2042 HTLCForwardInfo::FailHTLC { .. } => {
2043 // Channel went away before we could fail it. This implies
2044 // the channel is now on chain and our counterparty is
2045 // trying to broadcast the HTLC-Timeout, but that's their
2046 // problem, not ours.
2053 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(forward_chan_id) {
2054 let mut add_htlc_msgs = Vec::new();
2055 let mut fail_htlc_msgs = Vec::new();
2056 for forward_info in pending_forwards.drain(..) {
2057 match forward_info {
2058 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
2059 routing: PendingHTLCRouting::Forward {
2061 }, incoming_shared_secret, payment_hash, amt_to_forward, outgoing_cltv_value },
2062 prev_funding_outpoint } => {
2063 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);
2064 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
2065 short_channel_id: prev_short_channel_id,
2066 outpoint: prev_funding_outpoint,
2067 htlc_id: prev_htlc_id,
2068 incoming_packet_shared_secret: incoming_shared_secret,
2070 match chan.get_mut().send_htlc(amt_to_forward, payment_hash, outgoing_cltv_value, htlc_source.clone(), onion_packet) {
2072 if let ChannelError::Ignore(msg) = e {
2073 log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
2075 panic!("Stated return value requirements in send_htlc() were not met");
2077 let chan_update = self.get_channel_update(chan.get()).unwrap();
2078 failed_forwards.push((htlc_source, payment_hash,
2079 HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.encode_with_len() }
2085 Some(msg) => { add_htlc_msgs.push(msg); },
2087 // Nothing to do here...we're waiting on a remote
2088 // revoke_and_ack before we can add anymore HTLCs. The Channel
2089 // will automatically handle building the update_add_htlc and
2090 // commitment_signed messages when we can.
2091 // TODO: Do some kind of timer to set the channel as !is_live()
2092 // as we don't really want others relying on us relaying through
2093 // this channel currently :/.
2099 HTLCForwardInfo::AddHTLC { .. } => {
2100 panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
2102 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
2103 log_trace!(self.logger, "Failing HTLC back to channel with short id {} after delay", short_chan_id);
2104 match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet, &self.logger) {
2106 if let ChannelError::Ignore(msg) = e {
2107 log_trace!(self.logger, "Failed to fail backwards to short_id {}: {}", short_chan_id, msg);
2109 panic!("Stated return value requirements in get_update_fail_htlc() were not met");
2111 // fail-backs are best-effort, we probably already have one
2112 // pending, and if not that's OK, if not, the channel is on
2113 // the chain and sending the HTLC-Timeout is their problem.
2116 Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
2118 // Nothing to do here...we're waiting on a remote
2119 // revoke_and_ack before we can update the commitment
2120 // transaction. The Channel will automatically handle
2121 // building the update_fail_htlc and commitment_signed
2122 // messages when we can.
2123 // We don't need any kind of timer here as they should fail
2124 // the channel onto the chain if they can't get our
2125 // update_fail_htlc in time, it's not our problem.
2132 if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
2133 let (commitment_msg, monitor_update) = match chan.get_mut().send_commitment(&self.logger) {
2136 // We surely failed send_commitment due to bad keys, in that case
2137 // close channel and then send error message to peer.
2138 let counterparty_node_id = chan.get().get_counterparty_node_id();
2139 let err: Result<(), _> = match e {
2140 ChannelError::Ignore(_) => {
2141 panic!("Stated return value requirements in send_commitment() were not met");
2143 ChannelError::Close(msg) => {
2144 log_trace!(self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
2145 let (channel_id, mut channel) = chan.remove_entry();
2146 if let Some(short_id) = channel.get_short_channel_id() {
2147 channel_state.short_to_id.remove(&short_id);
2149 Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, channel.force_shutdown(true), self.get_channel_update(&channel).ok()))
2151 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"); }
2153 handle_errors.push((counterparty_node_id, err));
2157 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2158 handle_errors.push((chan.get().get_counterparty_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
2161 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2162 node_id: chan.get().get_counterparty_node_id(),
2163 updates: msgs::CommitmentUpdate {
2164 update_add_htlcs: add_htlc_msgs,
2165 update_fulfill_htlcs: Vec::new(),
2166 update_fail_htlcs: fail_htlc_msgs,
2167 update_fail_malformed_htlcs: Vec::new(),
2169 commitment_signed: commitment_msg,
2177 for forward_info in pending_forwards.drain(..) {
2178 match forward_info {
2179 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
2180 routing: PendingHTLCRouting::Receive { payment_data, incoming_cltv_expiry },
2181 incoming_shared_secret, payment_hash, amt_to_forward, .. },
2182 prev_funding_outpoint } => {
2183 let claimable_htlc = ClaimableHTLC {
2184 prev_hop: HTLCPreviousHopData {
2185 short_channel_id: prev_short_channel_id,
2186 outpoint: prev_funding_outpoint,
2187 htlc_id: prev_htlc_id,
2188 incoming_packet_shared_secret: incoming_shared_secret,
2190 value: amt_to_forward,
2191 payment_data: payment_data.clone(),
2192 cltv_expiry: incoming_cltv_expiry,
2195 macro_rules! fail_htlc {
2197 let mut htlc_msat_height_data = byte_utils::be64_to_array($htlc.value).to_vec();
2198 htlc_msat_height_data.extend_from_slice(
2199 &byte_utils::be32_to_array(self.best_block.read().unwrap().height()),
2201 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
2202 short_channel_id: $htlc.prev_hop.short_channel_id,
2203 outpoint: prev_funding_outpoint,
2204 htlc_id: $htlc.prev_hop.htlc_id,
2205 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
2207 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data }
2212 // Check that the payment hash and secret are known. Note that we
2213 // MUST take care to handle the "unknown payment hash" and
2214 // "incorrect payment secret" cases here identically or we'd expose
2215 // that we are the ultimate recipient of the given payment hash.
2216 // Further, we must not expose whether we have any other HTLCs
2217 // associated with the same payment_hash pending or not.
2218 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
2219 match payment_secrets.entry(payment_hash) {
2220 hash_map::Entry::Vacant(_) => {
2221 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as we didn't have a corresponding inbound payment.", log_bytes!(payment_hash.0));
2222 fail_htlc!(claimable_htlc);
2224 hash_map::Entry::Occupied(inbound_payment) => {
2225 if inbound_payment.get().payment_secret != payment_data.payment_secret {
2226 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", log_bytes!(payment_hash.0));
2227 fail_htlc!(claimable_htlc);
2228 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
2229 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
2230 log_bytes!(payment_hash.0), payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
2231 fail_htlc!(claimable_htlc);
2233 let mut total_value = 0;
2234 let htlcs = channel_state.claimable_htlcs.entry(payment_hash)
2235 .or_insert(Vec::new());
2236 htlcs.push(claimable_htlc);
2237 for htlc in htlcs.iter() {
2238 total_value += htlc.value;
2239 if htlc.payment_data.total_msat != payment_data.total_msat {
2240 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
2241 log_bytes!(payment_hash.0), payment_data.total_msat, htlc.payment_data.total_msat);
2242 total_value = msgs::MAX_VALUE_MSAT;
2244 if total_value >= msgs::MAX_VALUE_MSAT { break; }
2246 if total_value >= msgs::MAX_VALUE_MSAT || total_value > payment_data.total_msat {
2247 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the total value {} ran over expected value {} (or HTLCs were inconsistent)",
2248 log_bytes!(payment_hash.0), total_value, payment_data.total_msat);
2249 for htlc in htlcs.iter() {
2252 } else if total_value == payment_data.total_msat {
2253 new_events.push(events::Event::PaymentReceived {
2255 payment_preimage: inbound_payment.get().payment_preimage,
2256 payment_secret: payment_data.payment_secret,
2258 user_payment_id: inbound_payment.get().user_payment_id,
2260 // Only ever generate at most one PaymentReceived
2261 // per registered payment_hash, even if it isn't
2263 inbound_payment.remove_entry();
2265 // Nothing to do - we haven't reached the total
2266 // payment value yet, wait until we receive more
2273 HTLCForwardInfo::AddHTLC { .. } => {
2274 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
2276 HTLCForwardInfo::FailHTLC { .. } => {
2277 panic!("Got pending fail of our own HTLC");
2285 for (htlc_source, payment_hash, failure_reason) in failed_forwards.drain(..) {
2286 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, failure_reason);
2289 for (counterparty_node_id, err) in handle_errors.drain(..) {
2290 let _ = handle_error!(self, err, counterparty_node_id);
2293 if new_events.is_empty() { return }
2294 let mut events = self.pending_events.lock().unwrap();
2295 events.append(&mut new_events);
2298 /// Free the background events, generally called from timer_tick_occurred.
2300 /// Exposed for testing to allow us to process events quickly without generating accidental
2301 /// BroadcastChannelUpdate events in timer_tick_occurred.
2303 /// Expects the caller to have a total_consistency_lock read lock.
2304 fn process_background_events(&self) -> bool {
2305 let mut background_events = Vec::new();
2306 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
2307 if background_events.is_empty() {
2311 for event in background_events.drain(..) {
2313 BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)) => {
2314 // The channel has already been closed, so no use bothering to care about the
2315 // monitor updating completing.
2316 let _ = self.chain_monitor.update_channel(funding_txo, update);
2323 #[cfg(any(test, feature = "_test_utils"))]
2324 pub(crate) fn test_process_background_events(&self) {
2325 self.process_background_events();
2328 /// If a peer is disconnected we mark any channels with that peer as 'disabled'.
2329 /// After some time, if channels are still disabled we need to broadcast a ChannelUpdate
2330 /// to inform the network about the uselessness of these channels.
2332 /// This method handles all the details, and must be called roughly once per minute.
2334 /// Note that in some rare cases this may generate a `chain::Watch::update_channel` call.
2335 pub fn timer_tick_occurred(&self) {
2336 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
2337 let mut should_persist = NotifyOption::SkipPersist;
2338 if self.process_background_events() { should_persist = NotifyOption::DoPersist; }
2340 let mut channel_state_lock = self.channel_state.lock().unwrap();
2341 let channel_state = &mut *channel_state_lock;
2342 for (_, chan) in channel_state.by_id.iter_mut() {
2343 match chan.channel_update_status() {
2344 ChannelUpdateStatus::Enabled if !chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged),
2345 ChannelUpdateStatus::Disabled if chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged),
2346 ChannelUpdateStatus::DisabledStaged if chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
2347 ChannelUpdateStatus::EnabledStaged if !chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
2348 ChannelUpdateStatus::DisabledStaged if !chan.is_live() => {
2349 if let Ok(update) = self.get_channel_update(&chan) {
2350 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2354 should_persist = NotifyOption::DoPersist;
2355 chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
2357 ChannelUpdateStatus::EnabledStaged if chan.is_live() => {
2358 if let Ok(update) = self.get_channel_update(&chan) {
2359 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2363 should_persist = NotifyOption::DoPersist;
2364 chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
2374 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
2375 /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
2376 /// along the path (including in our own channel on which we received it).
2377 /// Returns false if no payment was found to fail backwards, true if the process of failing the
2378 /// HTLC backwards has been started.
2379 pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) -> bool {
2380 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2382 let mut channel_state = Some(self.channel_state.lock().unwrap());
2383 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
2384 if let Some(mut sources) = removed_source {
2385 for htlc in sources.drain(..) {
2386 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
2387 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
2388 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
2389 self.best_block.read().unwrap().height()));
2390 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
2391 HTLCSource::PreviousHopData(htlc.prev_hop), payment_hash,
2392 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data });
2398 // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
2399 // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
2400 // be surfaced to the user.
2401 fn fail_holding_cell_htlcs(&self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: [u8; 32]) {
2402 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
2404 HTLCSource::PreviousHopData(HTLCPreviousHopData { .. }) => {
2405 let (failure_code, onion_failure_data) =
2406 match self.channel_state.lock().unwrap().by_id.entry(channel_id) {
2407 hash_map::Entry::Occupied(chan_entry) => {
2408 if let Ok(upd) = self.get_channel_update(&chan_entry.get()) {
2409 (0x1000|7, upd.encode_with_len())
2411 (0x4000|10, Vec::new())
2414 hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
2416 let channel_state = self.channel_state.lock().unwrap();
2417 self.fail_htlc_backwards_internal(channel_state,
2418 htlc_src, &payment_hash, HTLCFailReason::Reason { failure_code, data: onion_failure_data});
2420 HTLCSource::OutboundRoute { session_priv, .. } => {
2422 let mut session_priv_bytes = [0; 32];
2423 session_priv_bytes.copy_from_slice(&session_priv[..]);
2424 self.pending_outbound_payments.lock().unwrap().remove(&session_priv_bytes)
2426 self.pending_events.lock().unwrap().push(
2427 events::Event::PaymentFailed {
2429 rejected_by_dest: false,
2437 log_trace!(self.logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
2444 /// Fails an HTLC backwards to the sender of it to us.
2445 /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
2446 /// There are several callsites that do stupid things like loop over a list of payment_hashes
2447 /// to fail and take the channel_state lock for each iteration (as we take ownership and may
2448 /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
2449 /// still-available channels.
2450 fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
2451 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
2452 //identify whether we sent it or not based on the (I presume) very different runtime
2453 //between the branches here. We should make this async and move it into the forward HTLCs
2456 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
2457 // from block_connected which may run during initialization prior to the chain_monitor
2458 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
2460 HTLCSource::OutboundRoute { ref path, session_priv, .. } => {
2462 let mut session_priv_bytes = [0; 32];
2463 session_priv_bytes.copy_from_slice(&session_priv[..]);
2464 !self.pending_outbound_payments.lock().unwrap().remove(&session_priv_bytes)
2466 log_trace!(self.logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
2469 log_trace!(self.logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
2470 mem::drop(channel_state_lock);
2471 match &onion_error {
2472 &HTLCFailReason::LightningError { ref err } => {
2474 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());
2476 let (channel_update, payment_retryable, _, _) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
2477 // TODO: If we decided to blame ourselves (or one of our channels) in
2478 // process_onion_failure we should close that channel as it implies our
2479 // next-hop is needlessly blaming us!
2480 if let Some(update) = channel_update {
2481 self.channel_state.lock().unwrap().pending_msg_events.push(
2482 events::MessageSendEvent::PaymentFailureNetworkUpdate {
2487 self.pending_events.lock().unwrap().push(
2488 events::Event::PaymentFailed {
2489 payment_hash: payment_hash.clone(),
2490 rejected_by_dest: !payment_retryable,
2492 error_code: onion_error_code,
2494 error_data: onion_error_data
2498 &HTLCFailReason::Reason {
2504 // we get a fail_malformed_htlc from the first hop
2505 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
2506 // failures here, but that would be insufficient as get_route
2507 // generally ignores its view of our own channels as we provide them via
2509 // TODO: For non-temporary failures, we really should be closing the
2510 // channel here as we apparently can't relay through them anyway.
2511 self.pending_events.lock().unwrap().push(
2512 events::Event::PaymentFailed {
2513 payment_hash: payment_hash.clone(),
2514 rejected_by_dest: path.len() == 1,
2516 error_code: Some(*failure_code),
2518 error_data: Some(data.clone()),
2524 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret, .. }) => {
2525 let err_packet = match onion_error {
2526 HTLCFailReason::Reason { failure_code, data } => {
2527 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
2528 let packet = onion_utils::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
2529 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
2531 HTLCFailReason::LightningError { err } => {
2532 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards with pre-built LightningError", log_bytes!(payment_hash.0));
2533 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
2537 let mut forward_event = None;
2538 if channel_state_lock.forward_htlcs.is_empty() {
2539 forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
2541 match channel_state_lock.forward_htlcs.entry(short_channel_id) {
2542 hash_map::Entry::Occupied(mut entry) => {
2543 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id, err_packet });
2545 hash_map::Entry::Vacant(entry) => {
2546 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id, err_packet }));
2549 mem::drop(channel_state_lock);
2550 if let Some(time) = forward_event {
2551 let mut pending_events = self.pending_events.lock().unwrap();
2552 pending_events.push(events::Event::PendingHTLCsForwardable {
2553 time_forwardable: time
2560 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
2561 /// generating message events for the net layer to claim the payment, if possible. Thus, you
2562 /// should probably kick the net layer to go send messages if this returns true!
2564 /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
2565 /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentReceived`
2566 /// event matches your expectation. If you fail to do so and call this method, you may provide
2567 /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
2569 /// May panic if called except in response to a PaymentReceived event.
2571 /// [`create_inbound_payment`]: Self::create_inbound_payment
2572 /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
2573 pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
2574 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
2576 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2578 let mut channel_state = Some(self.channel_state.lock().unwrap());
2579 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
2580 if let Some(mut sources) = removed_source {
2581 assert!(!sources.is_empty());
2583 // If we are claiming an MPP payment, we have to take special care to ensure that each
2584 // channel exists before claiming all of the payments (inside one lock).
2585 // Note that channel existance is sufficient as we should always get a monitor update
2586 // which will take care of the real HTLC claim enforcement.
2588 // If we find an HTLC which we would need to claim but for which we do not have a
2589 // channel, we will fail all parts of the MPP payment. While we could wait and see if
2590 // the sender retries the already-failed path(s), it should be a pretty rare case where
2591 // we got all the HTLCs and then a channel closed while we were waiting for the user to
2592 // provide the preimage, so worrying too much about the optimal handling isn't worth
2594 let mut valid_mpp = true;
2595 for htlc in sources.iter() {
2596 if let None = channel_state.as_ref().unwrap().short_to_id.get(&htlc.prev_hop.short_channel_id) {
2602 let mut errs = Vec::new();
2603 let mut claimed_any_htlcs = false;
2604 for htlc in sources.drain(..) {
2606 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
2607 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
2608 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
2609 self.best_block.read().unwrap().height()));
2610 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
2611 HTLCSource::PreviousHopData(htlc.prev_hop), &payment_hash,
2612 HTLCFailReason::Reason { failure_code: 0x4000|15, data: htlc_msat_height_data });
2614 match self.claim_funds_from_hop(channel_state.as_mut().unwrap(), htlc.prev_hop, payment_preimage) {
2616 if let msgs::ErrorAction::IgnoreError = e.1.err.action {
2617 // We got a temporary failure updating monitor, but will claim the
2618 // HTLC when the monitor updating is restored (or on chain).
2619 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", e.1.err.err);
2620 claimed_any_htlcs = true;
2621 } else { errs.push(e); }
2623 Err(None) => unreachable!("We already checked for channel existence, we can't fail here!"),
2624 Ok(()) => claimed_any_htlcs = true,
2629 // Now that we've done the entire above loop in one lock, we can handle any errors
2630 // which were generated.
2631 channel_state.take();
2633 for (counterparty_node_id, err) in errs.drain(..) {
2634 let res: Result<(), _> = Err(err);
2635 let _ = handle_error!(self, res, counterparty_node_id);
2642 fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard<ChannelHolder<Signer>>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> Result<(), Option<(PublicKey, MsgHandleErrInternal)>> {
2643 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
2644 let channel_state = &mut **channel_state_lock;
2645 let chan_id = match channel_state.short_to_id.get(&prev_hop.short_channel_id) {
2646 Some(chan_id) => chan_id.clone(),
2652 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(chan_id) {
2653 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2654 match chan.get_mut().get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger) {
2655 Ok((msgs, monitor_option)) => {
2656 if let Some(monitor_update) = monitor_option {
2657 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2658 if was_frozen_for_monitor {
2659 assert!(msgs.is_none());
2661 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())));
2665 if let Some((msg, commitment_signed)) = msgs {
2666 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2667 node_id: chan.get().get_counterparty_node_id(),
2668 updates: msgs::CommitmentUpdate {
2669 update_add_htlcs: Vec::new(),
2670 update_fulfill_htlcs: vec![msg],
2671 update_fail_htlcs: Vec::new(),
2672 update_fail_malformed_htlcs: Vec::new(),
2681 // TODO: Do something with e?
2682 // This should only occur if we are claiming an HTLC at the same time as the
2683 // HTLC is being failed (eg because a block is being connected and this caused
2684 // an HTLC to time out). This should, of course, only occur if the user is the
2685 // one doing the claiming (as it being a part of a peer claim would imply we're
2686 // about to lose funds) and only if the lock in claim_funds was dropped as a
2687 // previous HTLC was failed (thus not for an MPP payment).
2688 debug_assert!(false, "This shouldn't be reachable except in absurdly rare cases between monitor updates and HTLC timeouts: {:?}", e);
2692 } else { unreachable!(); }
2695 fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_preimage: PaymentPreimage) {
2697 HTLCSource::OutboundRoute { session_priv, .. } => {
2698 mem::drop(channel_state_lock);
2700 let mut session_priv_bytes = [0; 32];
2701 session_priv_bytes.copy_from_slice(&session_priv[..]);
2702 self.pending_outbound_payments.lock().unwrap().remove(&session_priv_bytes)
2704 let mut pending_events = self.pending_events.lock().unwrap();
2705 pending_events.push(events::Event::PaymentSent {
2709 log_trace!(self.logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
2712 HTLCSource::PreviousHopData(hop_data) => {
2713 let prev_outpoint = hop_data.outpoint;
2714 if let Err((counterparty_node_id, err)) = match self.claim_funds_from_hop(&mut channel_state_lock, hop_data, payment_preimage) {
2717 let preimage_update = ChannelMonitorUpdate {
2718 update_id: CLOSED_CHANNEL_UPDATE_ID,
2719 updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
2720 payment_preimage: payment_preimage.clone(),
2723 // We update the ChannelMonitor on the backward link, after
2724 // receiving an offchain preimage event from the forward link (the
2725 // event being update_fulfill_htlc).
2726 if let Err(e) = self.chain_monitor.update_channel(prev_outpoint, preimage_update) {
2727 log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
2728 payment_preimage, e);
2732 Err(Some(res)) => Err(res),
2734 mem::drop(channel_state_lock);
2735 let res: Result<(), _> = Err(err);
2736 let _ = handle_error!(self, res, counterparty_node_id);
2742 /// Gets the node_id held by this ChannelManager
2743 pub fn get_our_node_id(&self) -> PublicKey {
2744 self.our_network_pubkey.clone()
2747 /// Restores a single, given channel to normal operation after a
2748 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
2751 /// All ChannelMonitor updates up to and including highest_applied_update_id must have been
2752 /// fully committed in every copy of the given channels' ChannelMonitors.
2754 /// Note that there is no effect to calling with a highest_applied_update_id other than the
2755 /// current latest ChannelMonitorUpdate and one call to this function after multiple
2756 /// ChannelMonitorUpdateErr::TemporaryFailures is fine. The highest_applied_update_id field
2757 /// exists largely only to prevent races between this and concurrent update_monitor calls.
2759 /// Thus, the anticipated use is, at a high level:
2760 /// 1) You register a chain::Watch with this ChannelManager,
2761 /// 2) it stores each update to disk, and begins updating any remote (eg watchtower) copies of
2762 /// said ChannelMonitors as it can, returning ChannelMonitorUpdateErr::TemporaryFailures
2763 /// any time it cannot do so instantly,
2764 /// 3) update(s) are applied to each remote copy of a ChannelMonitor,
2765 /// 4) once all remote copies are updated, you call this function with the update_id that
2766 /// completed, and once it is the latest the Channel will be re-enabled.
2767 pub fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64) {
2768 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2770 let (mut pending_failures, chan_restoration_res) = {
2771 let mut channel_lock = self.channel_state.lock().unwrap();
2772 let channel_state = &mut *channel_lock;
2773 let mut channel = match channel_state.by_id.entry(funding_txo.to_channel_id()) {
2774 hash_map::Entry::Occupied(chan) => chan,
2775 hash_map::Entry::Vacant(_) => return,
2777 if !channel.get().is_awaiting_monitor_update() || channel.get().get_latest_monitor_update_id() != highest_applied_update_id {
2781 let (raa, commitment_update, order, pending_forwards, pending_failures, funding_broadcastable, funding_locked) = channel.get_mut().monitor_updating_restored(&self.logger);
2782 (pending_failures, handle_chan_restoration_locked!(self, channel_lock, channel_state, channel, raa, commitment_update, order, None, pending_forwards, funding_broadcastable, funding_locked))
2784 post_handle_chan_restoration!(self, chan_restoration_res);
2785 for failure in pending_failures.drain(..) {
2786 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2790 fn internal_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
2791 if msg.chain_hash != self.genesis_hash {
2792 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
2795 let channel = Channel::new_from_req(&self.fee_estimator, &self.keys_manager, counterparty_node_id.clone(), their_features, msg, 0, &self.default_configuration)
2796 .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
2797 let mut channel_state_lock = self.channel_state.lock().unwrap();
2798 let channel_state = &mut *channel_state_lock;
2799 match channel_state.by_id.entry(channel.channel_id()) {
2800 hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!".to_owned(), msg.temporary_channel_id.clone())),
2801 hash_map::Entry::Vacant(entry) => {
2802 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
2803 node_id: counterparty_node_id.clone(),
2804 msg: channel.get_accept_channel(),
2806 entry.insert(channel);
2812 fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
2813 let (value, output_script, user_id) = {
2814 let mut channel_lock = self.channel_state.lock().unwrap();
2815 let channel_state = &mut *channel_lock;
2816 match channel_state.by_id.entry(msg.temporary_channel_id) {
2817 hash_map::Entry::Occupied(mut chan) => {
2818 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2819 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
2821 try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration, their_features), channel_state, chan);
2822 (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
2824 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
2827 let mut pending_events = self.pending_events.lock().unwrap();
2828 pending_events.push(events::Event::FundingGenerationReady {
2829 temporary_channel_id: msg.temporary_channel_id,
2830 channel_value_satoshis: value,
2832 user_channel_id: user_id,
2837 fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
2838 let ((funding_msg, monitor), mut chan) = {
2839 let best_block = *self.best_block.read().unwrap();
2840 let mut channel_lock = self.channel_state.lock().unwrap();
2841 let channel_state = &mut *channel_lock;
2842 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
2843 hash_map::Entry::Occupied(mut chan) => {
2844 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2845 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
2847 (try_chan_entry!(self, chan.get_mut().funding_created(msg, best_block, &self.logger), channel_state, chan), chan.remove())
2849 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
2852 // Because we have exclusive ownership of the channel here we can release the channel_state
2853 // lock before watch_channel
2854 if let Err(e) = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor) {
2856 ChannelMonitorUpdateErr::PermanentFailure => {
2857 // Note that we reply with the new channel_id in error messages if we gave up on the
2858 // channel, not the temporary_channel_id. This is compatible with ourselves, but the
2859 // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
2860 // any messages referencing a previously-closed channel anyway.
2861 // We do not do a force-close here as that would generate a monitor update for
2862 // a monitor that we didn't manage to store (and that we don't care about - we
2863 // don't respond with the funding_signed so the channel can never go on chain).
2864 let (_monitor_update, failed_htlcs) = chan.force_shutdown(true);
2865 assert!(failed_htlcs.is_empty());
2866 return Err(MsgHandleErrInternal::send_err_msg_no_close("ChannelMonitor storage failure".to_owned(), funding_msg.channel_id));
2868 ChannelMonitorUpdateErr::TemporaryFailure => {
2869 // There's no problem signing a counterparty's funding transaction if our monitor
2870 // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
2871 // accepted payment from yet. We do, however, need to wait to send our funding_locked
2872 // until we have persisted our monitor.
2873 chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
2877 let mut channel_state_lock = self.channel_state.lock().unwrap();
2878 let channel_state = &mut *channel_state_lock;
2879 match channel_state.by_id.entry(funding_msg.channel_id) {
2880 hash_map::Entry::Occupied(_) => {
2881 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
2883 hash_map::Entry::Vacant(e) => {
2884 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
2885 node_id: counterparty_node_id.clone(),
2894 fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
2896 let best_block = *self.best_block.read().unwrap();
2897 let mut channel_lock = self.channel_state.lock().unwrap();
2898 let channel_state = &mut *channel_lock;
2899 match channel_state.by_id.entry(msg.channel_id) {
2900 hash_map::Entry::Occupied(mut chan) => {
2901 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2902 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2904 let (monitor, funding_tx) = match chan.get_mut().funding_signed(&msg, best_block, &self.logger) {
2905 Ok(update) => update,
2906 Err(e) => try_chan_entry!(self, Err(e), channel_state, chan),
2908 if let Err(e) = self.chain_monitor.watch_channel(chan.get().get_funding_txo().unwrap(), monitor) {
2909 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
2913 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2916 log_info!(self.logger, "Broadcasting funding transaction with txid {}", funding_tx.txid());
2917 self.tx_broadcaster.broadcast_transaction(&funding_tx);
2921 fn internal_funding_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
2922 let mut channel_state_lock = self.channel_state.lock().unwrap();
2923 let channel_state = &mut *channel_state_lock;
2924 match channel_state.by_id.entry(msg.channel_id) {
2925 hash_map::Entry::Occupied(mut chan) => {
2926 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2927 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2929 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
2930 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
2931 log_trace!(self.logger, "Sending announcement_signatures for {} in response to funding_locked", log_bytes!(chan.get().channel_id()));
2932 // If we see locking block before receiving remote funding_locked, we broadcast our
2933 // announcement_sigs at remote funding_locked reception. If we receive remote
2934 // funding_locked before seeing locking block, we broadcast our announcement_sigs at locking
2935 // block connection. We should guanrantee to broadcast announcement_sigs to our peer whatever
2936 // the order of the events but our peer may not receive it due to disconnection. The specs
2937 // lacking an acknowledgement for announcement_sigs we may have to re-send them at peer
2938 // connection in the future if simultaneous misses by both peers due to network/hardware
2939 // failures is an issue. Note, to achieve its goal, only one of the announcement_sigs needs
2940 // to be received, from then sigs are going to be flood to the whole network.
2941 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2942 node_id: counterparty_node_id.clone(),
2943 msg: announcement_sigs,
2948 hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2952 fn internal_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
2953 let (mut dropped_htlcs, chan_option) = {
2954 let mut channel_state_lock = self.channel_state.lock().unwrap();
2955 let channel_state = &mut *channel_state_lock;
2957 match channel_state.by_id.entry(msg.channel_id.clone()) {
2958 hash_map::Entry::Occupied(mut chan_entry) => {
2959 if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
2960 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2962 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);
2963 if let Some(msg) = shutdown {
2964 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2965 node_id: counterparty_node_id.clone(),
2969 if let Some(msg) = closing_signed {
2970 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2971 node_id: counterparty_node_id.clone(),
2975 if chan_entry.get().is_shutdown() {
2976 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2977 channel_state.short_to_id.remove(&short_id);
2979 (dropped_htlcs, Some(chan_entry.remove_entry().1))
2980 } else { (dropped_htlcs, None) }
2982 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2985 for htlc_source in dropped_htlcs.drain(..) {
2986 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() });
2988 if let Some(chan) = chan_option {
2989 if let Ok(update) = self.get_channel_update(&chan) {
2990 let mut channel_state = self.channel_state.lock().unwrap();
2991 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2999 fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
3000 let (tx, chan_option) = {
3001 let mut channel_state_lock = self.channel_state.lock().unwrap();
3002 let channel_state = &mut *channel_state_lock;
3003 match channel_state.by_id.entry(msg.channel_id.clone()) {
3004 hash_map::Entry::Occupied(mut chan_entry) => {
3005 if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
3006 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
3008 let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&self.fee_estimator, &msg), channel_state, chan_entry);
3009 if let Some(msg) = closing_signed {
3010 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
3011 node_id: counterparty_node_id.clone(),
3016 // We're done with this channel, we've got a signed closing transaction and
3017 // will send the closing_signed back to the remote peer upon return. This
3018 // also implies there are no pending HTLCs left on the channel, so we can
3019 // fully delete it from tracking (the channel monitor is still around to
3020 // watch for old state broadcasts)!
3021 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
3022 channel_state.short_to_id.remove(&short_id);
3024 (tx, Some(chan_entry.remove_entry().1))
3025 } else { (tx, None) }
3027 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3030 if let Some(broadcast_tx) = tx {
3031 log_info!(self.logger, "Broadcasting {}", log_tx!(broadcast_tx));
3032 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
3034 if let Some(chan) = chan_option {
3035 if let Ok(update) = self.get_channel_update(&chan) {
3036 let mut channel_state = self.channel_state.lock().unwrap();
3037 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3045 fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
3046 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
3047 //determine the state of the payment based on our response/if we forward anything/the time
3048 //we take to respond. We should take care to avoid allowing such an attack.
3050 //TODO: There exists a further attack where a node may garble the onion data, forward it to
3051 //us repeatedly garbled in different ways, and compare our error messages, which are
3052 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
3053 //but we should prevent it anyway.
3055 let (pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
3056 let channel_state = &mut *channel_state_lock;
3058 match channel_state.by_id.entry(msg.channel_id) {
3059 hash_map::Entry::Occupied(mut chan) => {
3060 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3061 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
3064 let create_pending_htlc_status = |chan: &Channel<Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
3065 // Ensure error_code has the UPDATE flag set, since by default we send a
3066 // channel update along as part of failing the HTLC.
3067 assert!((error_code & 0x1000) != 0);
3068 // If the update_add is completely bogus, the call will Err and we will close,
3069 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
3070 // want to reject the new HTLC and fail it backwards instead of forwarding.
3071 match pending_forward_info {
3072 PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
3073 let reason = if let Ok(upd) = self.get_channel_update(chan) {
3074 onion_utils::build_first_hop_failure_packet(incoming_shared_secret, error_code, &{
3075 let mut res = Vec::with_capacity(8 + 128);
3076 // TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
3077 res.extend_from_slice(&byte_utils::be16_to_array(0));
3078 res.extend_from_slice(&upd.encode_with_len()[..]);
3082 // The only case where we'd be unable to
3083 // successfully get a channel update is if the
3084 // channel isn't in the fully-funded state yet,
3085 // implying our counterparty is trying to route
3086 // payments over the channel back to themselves
3087 // (cause no one else should know the short_id
3088 // is a lightning channel yet). We should have
3089 // no problem just calling this
3090 // unknown_next_peer (0x4000|10).
3091 onion_utils::build_first_hop_failure_packet(incoming_shared_secret, 0x4000|10, &[])
3093 let msg = msgs::UpdateFailHTLC {
3094 channel_id: msg.channel_id,
3095 htlc_id: msg.htlc_id,
3098 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
3100 _ => pending_forward_info
3103 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.logger), channel_state, chan);
3105 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3110 fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
3111 let mut channel_lock = self.channel_state.lock().unwrap();
3113 let channel_state = &mut *channel_lock;
3114 match channel_state.by_id.entry(msg.channel_id) {
3115 hash_map::Entry::Occupied(mut chan) => {
3116 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3117 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
3119 try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
3121 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3124 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
3128 fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
3129 let mut channel_lock = self.channel_state.lock().unwrap();
3130 let channel_state = &mut *channel_lock;
3131 match channel_state.by_id.entry(msg.channel_id) {
3132 hash_map::Entry::Occupied(mut chan) => {
3133 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3134 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
3136 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::LightningError { err: msg.reason.clone() }), channel_state, chan);
3138 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3143 fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
3144 let mut channel_lock = self.channel_state.lock().unwrap();
3145 let channel_state = &mut *channel_lock;
3146 match channel_state.by_id.entry(msg.channel_id) {
3147 hash_map::Entry::Occupied(mut chan) => {
3148 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3149 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
3151 if (msg.failure_code & 0x8000) == 0 {
3152 let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
3153 try_chan_entry!(self, Err(chan_err), channel_state, chan);
3155 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);
3158 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3162 fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
3163 let mut channel_state_lock = self.channel_state.lock().unwrap();
3164 let channel_state = &mut *channel_state_lock;
3165 match channel_state.by_id.entry(msg.channel_id) {
3166 hash_map::Entry::Occupied(mut chan) => {
3167 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3168 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
3170 let (revoke_and_ack, commitment_signed, closing_signed, monitor_update) =
3171 match chan.get_mut().commitment_signed(&msg, &self.fee_estimator, &self.logger) {
3172 Err((None, e)) => try_chan_entry!(self, Err(e), channel_state, chan),
3173 Err((Some(update), e)) => {
3174 assert!(chan.get().is_awaiting_monitor_update());
3175 let _ = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), update);
3176 try_chan_entry!(self, Err(e), channel_state, chan);
3181 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3182 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some());
3183 //TODO: Rebroadcast closing_signed if present on monitor update restoration
3185 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
3186 node_id: counterparty_node_id.clone(),
3187 msg: revoke_and_ack,
3189 if let Some(msg) = commitment_signed {
3190 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3191 node_id: counterparty_node_id.clone(),
3192 updates: msgs::CommitmentUpdate {
3193 update_add_htlcs: Vec::new(),
3194 update_fulfill_htlcs: Vec::new(),
3195 update_fail_htlcs: Vec::new(),
3196 update_fail_malformed_htlcs: Vec::new(),
3198 commitment_signed: msg,
3202 if let Some(msg) = closing_signed {
3203 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
3204 node_id: counterparty_node_id.clone(),
3210 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3215 fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, Vec<(PendingHTLCInfo, u64)>)]) {
3216 for &mut (prev_short_channel_id, prev_funding_outpoint, ref mut pending_forwards) in per_source_pending_forwards {
3217 let mut forward_event = None;
3218 if !pending_forwards.is_empty() {
3219 let mut channel_state = self.channel_state.lock().unwrap();
3220 if channel_state.forward_htlcs.is_empty() {
3221 forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS))
3223 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
3224 match channel_state.forward_htlcs.entry(match forward_info.routing {
3225 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
3226 PendingHTLCRouting::Receive { .. } => 0,
3228 hash_map::Entry::Occupied(mut entry) => {
3229 entry.get_mut().push(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_funding_outpoint,
3230 prev_htlc_id, forward_info });
3232 hash_map::Entry::Vacant(entry) => {
3233 entry.insert(vec!(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_funding_outpoint,
3234 prev_htlc_id, forward_info }));
3239 match forward_event {
3241 let mut pending_events = self.pending_events.lock().unwrap();
3242 pending_events.push(events::Event::PendingHTLCsForwardable {
3243 time_forwardable: time
3251 fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
3252 let mut htlcs_to_fail = Vec::new();
3254 let mut channel_state_lock = self.channel_state.lock().unwrap();
3255 let channel_state = &mut *channel_state_lock;
3256 match channel_state.by_id.entry(msg.channel_id) {
3257 hash_map::Entry::Occupied(mut chan) => {
3258 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3259 break Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
3261 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
3262 let (commitment_update, pending_forwards, pending_failures, closing_signed, monitor_update, htlcs_to_fail_in) =
3263 break_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &self.fee_estimator, &self.logger), channel_state, chan);
3264 htlcs_to_fail = htlcs_to_fail_in;
3265 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3266 if was_frozen_for_monitor {
3267 assert!(commitment_update.is_none() && closing_signed.is_none() && pending_forwards.is_empty() && pending_failures.is_empty());
3268 break Err(MsgHandleErrInternal::ignore_no_close("Previous monitor update failure prevented responses to RAA".to_owned()));
3270 if let Err(e) = handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, commitment_update.is_some(), pending_forwards, pending_failures) {
3272 } else { unreachable!(); }
3275 if let Some(updates) = commitment_update {
3276 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3277 node_id: counterparty_node_id.clone(),
3281 if let Some(msg) = closing_signed {
3282 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
3283 node_id: counterparty_node_id.clone(),
3287 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()))
3289 hash_map::Entry::Vacant(_) => break Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3292 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id);
3294 Ok((pending_forwards, mut pending_failures, short_channel_id, channel_outpoint)) => {
3295 for failure in pending_failures.drain(..) {
3296 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
3298 self.forward_htlcs(&mut [(short_channel_id, channel_outpoint, pending_forwards)]);
3305 fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
3306 let mut channel_lock = self.channel_state.lock().unwrap();
3307 let channel_state = &mut *channel_lock;
3308 match channel_state.by_id.entry(msg.channel_id) {
3309 hash_map::Entry::Occupied(mut chan) => {
3310 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3311 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
3313 try_chan_entry!(self, chan.get_mut().update_fee(&self.fee_estimator, &msg), channel_state, chan);
3315 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3320 fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
3321 let mut channel_state_lock = self.channel_state.lock().unwrap();
3322 let channel_state = &mut *channel_state_lock;
3324 match channel_state.by_id.entry(msg.channel_id) {
3325 hash_map::Entry::Occupied(mut chan) => {
3326 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3327 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
3329 if !chan.get().is_usable() {
3330 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
3333 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
3334 msg: try_chan_entry!(self, chan.get_mut().announcement_signatures(&self.our_network_key, self.get_our_node_id(), self.genesis_hash.clone(), msg), channel_state, chan),
3335 update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
3338 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3343 fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<(), MsgHandleErrInternal> {
3344 let mut channel_state_lock = self.channel_state.lock().unwrap();
3345 let channel_state = &mut *channel_state_lock;
3346 let chan_id = match channel_state.short_to_id.get(&msg.contents.short_channel_id) {
3347 Some(chan_id) => chan_id.clone(),
3349 // It's not a local channel
3353 match channel_state.by_id.entry(chan_id) {
3354 hash_map::Entry::Occupied(mut chan) => {
3355 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3356 // TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
3357 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), chan_id));
3359 try_chan_entry!(self, chan.get_mut().channel_update(&msg), channel_state, chan);
3361 hash_map::Entry::Vacant(_) => unreachable!()
3366 fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
3367 let (htlcs_failed_forward, chan_restoration_res) = {
3368 let mut channel_state_lock = self.channel_state.lock().unwrap();
3369 let channel_state = &mut *channel_state_lock;
3371 match channel_state.by_id.entry(msg.channel_id) {
3372 hash_map::Entry::Occupied(mut chan) => {
3373 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3374 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
3376 // Currently, we expect all holding cell update_adds to be dropped on peer
3377 // disconnect, so Channel's reestablish will never hand us any holding cell
3378 // freed HTLCs to fail backwards. If in the future we no longer drop pending
3379 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
3380 let (funding_locked, revoke_and_ack, commitment_update, monitor_update_opt, order, htlcs_failed_forward, shutdown) =
3381 try_chan_entry!(self, chan.get_mut().channel_reestablish(msg, &self.logger), channel_state, chan);
3382 if let Some(msg) = shutdown {
3383 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
3384 node_id: counterparty_node_id.clone(),
3388 (htlcs_failed_forward, handle_chan_restoration_locked!(self, channel_state_lock, channel_state, chan, revoke_and_ack, commitment_update, order, monitor_update_opt, Vec::new(), None, funding_locked))
3390 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3393 post_handle_chan_restoration!(self, chan_restoration_res);
3394 self.fail_holding_cell_htlcs(htlcs_failed_forward, msg.channel_id);
3398 /// Begin Update fee process. Allowed only on an outbound channel.
3399 /// If successful, will generate a UpdateHTLCs event, so you should probably poll
3400 /// PeerManager::process_events afterwards.
3401 /// Note: This API is likely to change!
3402 /// (C-not exported) Cause its doc(hidden) anyway
3404 pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u32) -> Result<(), APIError> {
3405 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3406 let counterparty_node_id;
3407 let err: Result<(), _> = loop {
3408 let mut channel_state_lock = self.channel_state.lock().unwrap();
3409 let channel_state = &mut *channel_state_lock;
3411 match channel_state.by_id.entry(channel_id) {
3412 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: format!("Failed to find corresponding channel for id {}", channel_id.to_hex())}),
3413 hash_map::Entry::Occupied(mut chan) => {
3414 if !chan.get().is_outbound() {
3415 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel".to_owned()});
3417 if chan.get().is_awaiting_monitor_update() {
3418 return Err(APIError::MonitorUpdateFailed);
3420 if !chan.get().is_live() {
3421 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected".to_owned()});
3423 counterparty_node_id = chan.get().get_counterparty_node_id();
3424 if let Some((update_fee, commitment_signed, monitor_update)) =
3425 break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw, &self.logger), channel_state, chan)
3427 if let Err(_e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3430 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3431 node_id: chan.get().get_counterparty_node_id(),
3432 updates: msgs::CommitmentUpdate {
3433 update_add_htlcs: Vec::new(),
3434 update_fulfill_htlcs: Vec::new(),
3435 update_fail_htlcs: Vec::new(),
3436 update_fail_malformed_htlcs: Vec::new(),
3437 update_fee: Some(update_fee),
3447 match handle_error!(self, err, counterparty_node_id) {
3448 Ok(_) => unreachable!(),
3449 Err(e) => { Err(APIError::APIMisuseError { err: e.err })}
3453 /// Process pending events from the `chain::Watch`, returning whether any events were processed.
3454 fn process_pending_monitor_events(&self) -> bool {
3455 let mut failed_channels = Vec::new();
3456 let pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
3457 let has_pending_monitor_events = !pending_monitor_events.is_empty();
3458 for monitor_event in pending_monitor_events {
3459 match monitor_event {
3460 MonitorEvent::HTLCEvent(htlc_update) => {
3461 if let Some(preimage) = htlc_update.payment_preimage {
3462 log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
3463 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
3465 log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
3466 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() });
3469 MonitorEvent::CommitmentTxBroadcasted(funding_outpoint) => {
3470 let mut channel_lock = self.channel_state.lock().unwrap();
3471 let channel_state = &mut *channel_lock;
3472 let by_id = &mut channel_state.by_id;
3473 let short_to_id = &mut channel_state.short_to_id;
3474 let pending_msg_events = &mut channel_state.pending_msg_events;
3475 if let Some(mut chan) = by_id.remove(&funding_outpoint.to_channel_id()) {
3476 if let Some(short_id) = chan.get_short_channel_id() {
3477 short_to_id.remove(&short_id);
3479 failed_channels.push(chan.force_shutdown(false));
3480 if let Ok(update) = self.get_channel_update(&chan) {
3481 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3485 pending_msg_events.push(events::MessageSendEvent::HandleError {
3486 node_id: chan.get_counterparty_node_id(),
3487 action: msgs::ErrorAction::SendErrorMessage {
3488 msg: msgs::ErrorMessage { channel_id: chan.channel_id(), data: "Channel force-closed".to_owned() }
3496 for failure in failed_channels.drain(..) {
3497 self.finish_force_close_channel(failure);
3500 has_pending_monitor_events
3503 /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
3504 /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
3505 /// update was applied.
3507 /// This should only apply to HTLCs which were added to the holding cell because we were
3508 /// waiting on a monitor update to finish. In that case, we don't want to free the holding cell
3509 /// directly in `channel_monitor_updated` as it may introduce deadlocks calling back into user
3510 /// code to inform them of a channel monitor update.
3511 fn check_free_holding_cells(&self) -> bool {
3512 let mut has_monitor_update = false;
3513 let mut failed_htlcs = Vec::new();
3514 let mut handle_errors = Vec::new();
3516 let mut channel_state_lock = self.channel_state.lock().unwrap();
3517 let channel_state = &mut *channel_state_lock;
3518 let by_id = &mut channel_state.by_id;
3519 let short_to_id = &mut channel_state.short_to_id;
3520 let pending_msg_events = &mut channel_state.pending_msg_events;
3522 by_id.retain(|channel_id, chan| {
3523 match chan.maybe_free_holding_cell_htlcs(&self.logger) {
3524 Ok((commitment_opt, holding_cell_failed_htlcs)) => {
3525 if !holding_cell_failed_htlcs.is_empty() {
3526 failed_htlcs.push((holding_cell_failed_htlcs, *channel_id));
3528 if let Some((commitment_update, monitor_update)) = commitment_opt {
3529 if let Err(e) = self.chain_monitor.update_channel(chan.get_funding_txo().unwrap(), monitor_update) {
3530 has_monitor_update = true;
3531 let (res, close_channel) = handle_monitor_err!(self, e, short_to_id, chan, RAACommitmentOrder::CommitmentFirst, false, true, Vec::new(), Vec::new(), channel_id);
3532 handle_errors.push((chan.get_counterparty_node_id(), res));
3533 if close_channel { return false; }
3535 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3536 node_id: chan.get_counterparty_node_id(),
3537 updates: commitment_update,
3544 let (close_channel, res) = convert_chan_err!(self, e, short_to_id, chan, channel_id);
3545 handle_errors.push((chan.get_counterparty_node_id(), Err(res)));
3552 let has_update = has_monitor_update || !failed_htlcs.is_empty();
3553 for (failures, channel_id) in failed_htlcs.drain(..) {
3554 self.fail_holding_cell_htlcs(failures, channel_id);
3557 for (counterparty_node_id, err) in handle_errors.drain(..) {
3558 let _ = handle_error!(self, err, counterparty_node_id);
3564 /// Handle a list of channel failures during a block_connected or block_disconnected call,
3565 /// pushing the channel monitor update (if any) to the background events queue and removing the
3567 fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
3568 for mut failure in failed_channels.drain(..) {
3569 // Either a commitment transactions has been confirmed on-chain or
3570 // Channel::block_disconnected detected that the funding transaction has been
3571 // reorganized out of the main chain.
3572 // We cannot broadcast our latest local state via monitor update (as
3573 // Channel::force_shutdown tries to make us do) as we may still be in initialization,
3574 // so we track the update internally and handle it when the user next calls
3575 // timer_tick_occurred, guaranteeing we're running normally.
3576 if let Some((funding_txo, update)) = failure.0.take() {
3577 assert_eq!(update.updates.len(), 1);
3578 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
3579 assert!(should_broadcast);
3580 } else { unreachable!(); }
3581 self.pending_background_events.lock().unwrap().push(BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)));
3583 self.finish_force_close_channel(failure);
3587 fn set_payment_hash_secret_map(&self, payment_hash: PaymentHash, payment_preimage: Option<PaymentPreimage>, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32, user_payment_id: u64) -> Result<PaymentSecret, APIError> {
3588 assert!(invoice_expiry_delta_secs <= 60*60*24*365); // Sadly bitcoin timestamps are u32s, so panic before 2106
3590 let payment_secret = PaymentSecret(self.keys_manager.get_secure_random_bytes());
3592 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3593 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
3594 match payment_secrets.entry(payment_hash) {
3595 hash_map::Entry::Vacant(e) => {
3596 e.insert(PendingInboundPayment {
3597 payment_secret, min_value_msat, user_payment_id, payment_preimage,
3598 // We assume that highest_seen_timestamp is pretty close to the current time -
3599 // its updated when we receive a new block with the maximum time we've seen in
3600 // a header. It should never be more than two hours in the future.
3601 // Thus, we add two hours here as a buffer to ensure we absolutely
3602 // never fail a payment too early.
3603 // Note that we assume that received blocks have reasonably up-to-date
3605 expiry_time: self.highest_seen_timestamp.load(Ordering::Acquire) as u64 + invoice_expiry_delta_secs as u64 + 7200,
3608 hash_map::Entry::Occupied(_) => return Err(APIError::APIMisuseError { err: "Duplicate payment hash".to_owned() }),
3613 /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
3616 /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
3617 /// [`PaymentHash`] and [`PaymentPreimage`] for you, returning the first and storing the second.
3619 /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentReceived`], which
3620 /// will have the [`PaymentReceived::payment_preimage`] field filled in. That should then be
3621 /// passed directly to [`claim_funds`].
3623 /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
3625 /// [`claim_funds`]: Self::claim_funds
3626 /// [`PaymentReceived`]: events::Event::PaymentReceived
3627 /// [`PaymentReceived::payment_preimage`]: events::Event::PaymentReceived::payment_preimage
3628 /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
3629 pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32, user_payment_id: u64) -> (PaymentHash, PaymentSecret) {
3630 let payment_preimage = PaymentPreimage(self.keys_manager.get_secure_random_bytes());
3631 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
3634 self.set_payment_hash_secret_map(payment_hash, Some(payment_preimage), min_value_msat, invoice_expiry_delta_secs, user_payment_id)
3635 .expect("RNG Generated Duplicate PaymentHash"))
3638 /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
3639 /// stored external to LDK.
3641 /// A [`PaymentReceived`] event will only be generated if the [`PaymentSecret`] matches a
3642 /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
3643 /// the `min_value_msat` provided here, if one is provided.
3645 /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) must be globally unique. This
3646 /// method may return an Err if another payment with the same payment_hash is still pending.
3648 /// `user_payment_id` will be provided back in [`PaymentReceived::user_payment_id`] events to
3649 /// allow tracking of which events correspond with which calls to this and
3650 /// [`create_inbound_payment`]. `user_payment_id` has no meaning inside of LDK, it is simply
3651 /// copied to events and otherwise ignored. It may be used to correlate PaymentReceived events
3652 /// with invoice metadata stored elsewhere.
3654 /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
3655 /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
3656 /// before a [`PaymentReceived`] event will be generated, ensuring that we do not provide the
3657 /// sender "proof-of-payment" unless they have paid the required amount.
3659 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
3660 /// in excess of the current time. This should roughly match the expiry time set in the invoice.
3661 /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
3662 /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
3663 /// invoices when no timeout is set.
3665 /// Note that we use block header time to time-out pending inbound payments (with some margin
3666 /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
3667 /// accept a payment and generate a [`PaymentReceived`] event for some time after the expiry.
3668 /// If you need exact expiry semantics, you should enforce them upon receipt of
3669 /// [`PaymentReceived`].
3671 /// Pending inbound payments are stored in memory and in serialized versions of this
3672 /// [`ChannelManager`]. If potentially unbounded numbers of inbound payments may exist and
3673 /// space is limited, you may wish to rate-limit inbound payment creation.
3675 /// May panic if `invoice_expiry_delta_secs` is greater than one year.
3677 /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry`
3678 /// set to at least [`MIN_FINAL_CLTV_EXPIRY`].
3680 /// [`create_inbound_payment`]: Self::create_inbound_payment
3681 /// [`PaymentReceived`]: events::Event::PaymentReceived
3682 /// [`PaymentReceived::user_payment_id`]: events::Event::PaymentReceived::user_payment_id
3683 pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32, user_payment_id: u64) -> Result<PaymentSecret, APIError> {
3684 self.set_payment_hash_secret_map(payment_hash, None, min_value_msat, invoice_expiry_delta_secs, user_payment_id)
3687 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
3688 pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
3689 let events = core::cell::RefCell::new(Vec::new());
3690 let event_handler = |event| events.borrow_mut().push(event);
3691 self.process_pending_events(&event_handler);
3696 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> MessageSendEventsProvider for ChannelManager<Signer, M, T, K, F, L>
3697 where M::Target: chain::Watch<Signer>,
3698 T::Target: BroadcasterInterface,
3699 K::Target: KeysInterface<Signer = Signer>,
3700 F::Target: FeeEstimator,
3703 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
3704 let events = RefCell::new(Vec::new());
3705 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
3706 let mut result = NotifyOption::SkipPersist;
3708 // TODO: This behavior should be documented. It's unintuitive that we query
3709 // ChannelMonitors when clearing other events.
3710 if self.process_pending_monitor_events() {
3711 result = NotifyOption::DoPersist;
3714 if self.check_free_holding_cells() {
3715 result = NotifyOption::DoPersist;
3718 let mut pending_events = Vec::new();
3719 let mut channel_state = self.channel_state.lock().unwrap();
3720 mem::swap(&mut pending_events, &mut channel_state.pending_msg_events);
3722 if !pending_events.is_empty() {
3723 events.replace(pending_events);
3732 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> EventsProvider for ChannelManager<Signer, M, T, K, F, L>
3734 M::Target: chain::Watch<Signer>,
3735 T::Target: BroadcasterInterface,
3736 K::Target: KeysInterface<Signer = Signer>,
3737 F::Target: FeeEstimator,
3740 /// Processes events that must be periodically handled.
3742 /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
3743 /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
3745 /// Pending events are persisted as part of [`ChannelManager`]. While these events are cleared
3746 /// when processed, an [`EventHandler`] must be able to handle previously seen events when
3747 /// restarting from an old state.
3748 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
3749 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
3750 let mut result = NotifyOption::SkipPersist;
3752 // TODO: This behavior should be documented. It's unintuitive that we query
3753 // ChannelMonitors when clearing other events.
3754 if self.process_pending_monitor_events() {
3755 result = NotifyOption::DoPersist;
3758 let mut pending_events = std::mem::replace(&mut *self.pending_events.lock().unwrap(), vec![]);
3759 if !pending_events.is_empty() {
3760 result = NotifyOption::DoPersist;
3763 for event in pending_events.drain(..) {
3764 handler.handle_event(event);
3772 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> chain::Listen for ChannelManager<Signer, M, T, K, F, L>
3774 M::Target: chain::Watch<Signer>,
3775 T::Target: BroadcasterInterface,
3776 K::Target: KeysInterface<Signer = Signer>,
3777 F::Target: FeeEstimator,
3780 fn block_connected(&self, block: &Block, height: u32) {
3782 let best_block = self.best_block.read().unwrap();
3783 assert_eq!(best_block.block_hash(), block.header.prev_blockhash,
3784 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
3785 assert_eq!(best_block.height(), height - 1,
3786 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
3789 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
3790 self.transactions_confirmed(&block.header, &txdata, height);
3791 self.best_block_updated(&block.header, height);
3794 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
3795 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3796 let new_height = height - 1;
3798 let mut best_block = self.best_block.write().unwrap();
3799 assert_eq!(best_block.block_hash(), header.block_hash(),
3800 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
3801 assert_eq!(best_block.height(), height,
3802 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
3803 *best_block = BestBlock::new(header.prev_blockhash, new_height)
3806 self.do_chain_event(Some(new_height), |channel| channel.best_block_updated(new_height, header.time));
3810 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> chain::Confirm for ChannelManager<Signer, M, T, K, F, L>
3812 M::Target: chain::Watch<Signer>,
3813 T::Target: BroadcasterInterface,
3814 K::Target: KeysInterface<Signer = Signer>,
3815 F::Target: FeeEstimator,
3818 fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3819 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3820 // during initialization prior to the chain_monitor being fully configured in some cases.
3821 // See the docs for `ChannelManagerReadArgs` for more.
3823 let block_hash = header.block_hash();
3824 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
3826 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3827 self.do_chain_event(Some(height), |channel| channel.transactions_confirmed(&block_hash, height, txdata, &self.logger).map(|a| (a, Vec::new())));
3830 fn best_block_updated(&self, header: &BlockHeader, height: u32) {
3831 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3832 // during initialization prior to the chain_monitor being fully configured in some cases.
3833 // See the docs for `ChannelManagerReadArgs` for more.
3835 let block_hash = header.block_hash();
3836 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
3838 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3840 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
3842 self.do_chain_event(Some(height), |channel| channel.best_block_updated(height, header.time));
3844 macro_rules! max_time {
3845 ($timestamp: expr) => {
3847 // Update $timestamp to be the max of its current value and the block
3848 // timestamp. This should keep us close to the current time without relying on
3849 // having an explicit local time source.
3850 // Just in case we end up in a race, we loop until we either successfully
3851 // update $timestamp or decide we don't need to.
3852 let old_serial = $timestamp.load(Ordering::Acquire);
3853 if old_serial >= header.time as usize { break; }
3854 if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
3860 max_time!(self.last_node_announcement_serial);
3861 max_time!(self.highest_seen_timestamp);
3862 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
3863 payment_secrets.retain(|_, inbound_payment| {
3864 inbound_payment.expiry_time > header.time as u64
3868 fn get_relevant_txids(&self) -> Vec<Txid> {
3869 let channel_state = self.channel_state.lock().unwrap();
3870 let mut res = Vec::with_capacity(channel_state.short_to_id.len());
3871 for chan in channel_state.by_id.values() {
3872 if let Some(funding_txo) = chan.get_funding_txo() {
3873 res.push(funding_txo.txid);
3879 fn transaction_unconfirmed(&self, txid: &Txid) {
3880 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3881 self.do_chain_event(None, |channel| {
3882 if let Some(funding_txo) = channel.get_funding_txo() {
3883 if funding_txo.txid == *txid {
3884 channel.funding_transaction_unconfirmed().map(|_| (None, Vec::new()))
3885 } else { Ok((None, Vec::new())) }
3886 } else { Ok((None, Vec::new())) }
3891 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
3893 M::Target: chain::Watch<Signer>,
3894 T::Target: BroadcasterInterface,
3895 K::Target: KeysInterface<Signer = Signer>,
3896 F::Target: FeeEstimator,
3899 /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
3900 /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
3902 fn do_chain_event<FN: Fn(&mut Channel<Signer>) -> Result<(Option<msgs::FundingLocked>, Vec<(HTLCSource, PaymentHash)>), msgs::ErrorMessage>>
3903 (&self, height_opt: Option<u32>, f: FN) {
3904 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3905 // during initialization prior to the chain_monitor being fully configured in some cases.
3906 // See the docs for `ChannelManagerReadArgs` for more.
3908 let mut failed_channels = Vec::new();
3909 let mut timed_out_htlcs = Vec::new();
3911 let mut channel_lock = self.channel_state.lock().unwrap();
3912 let channel_state = &mut *channel_lock;
3913 let short_to_id = &mut channel_state.short_to_id;
3914 let pending_msg_events = &mut channel_state.pending_msg_events;
3915 channel_state.by_id.retain(|_, channel| {
3916 let res = f(channel);
3917 if let Ok((chan_res, mut timed_out_pending_htlcs)) = res {
3918 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
3919 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
3920 timed_out_htlcs.push((source, payment_hash, HTLCFailReason::Reason {
3921 failure_code: 0x1000 | 14, // expiry_too_soon, or at least it is now
3925 if let Some(funding_locked) = chan_res {
3926 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
3927 node_id: channel.get_counterparty_node_id(),
3928 msg: funding_locked,
3930 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
3931 log_trace!(self.logger, "Sending funding_locked and announcement_signatures for {}", log_bytes!(channel.channel_id()));
3932 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
3933 node_id: channel.get_counterparty_node_id(),
3934 msg: announcement_sigs,
3937 log_trace!(self.logger, "Sending funding_locked WITHOUT announcement_signatures for {}", log_bytes!(channel.channel_id()));
3939 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
3941 } else if let Err(e) = res {
3942 if let Some(short_id) = channel.get_short_channel_id() {
3943 short_to_id.remove(&short_id);
3945 // It looks like our counterparty went on-chain or funding transaction was
3946 // reorged out of the main chain. Close the channel.
3947 failed_channels.push(channel.force_shutdown(true));
3948 if let Ok(update) = self.get_channel_update(&channel) {
3949 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3953 pending_msg_events.push(events::MessageSendEvent::HandleError {
3954 node_id: channel.get_counterparty_node_id(),
3955 action: msgs::ErrorAction::SendErrorMessage { msg: e },
3962 if let Some(height) = height_opt {
3963 channel_state.claimable_htlcs.retain(|payment_hash, htlcs| {
3964 htlcs.retain(|htlc| {
3965 // If height is approaching the number of blocks we think it takes us to get
3966 // our commitment transaction confirmed before the HTLC expires, plus the
3967 // number of blocks we generally consider it to take to do a commitment update,
3968 // just give up on it and fail the HTLC.
3969 if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
3970 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
3971 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(height));
3972 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(), HTLCFailReason::Reason {
3973 failure_code: 0x4000 | 15,
3974 data: htlc_msat_height_data
3979 !htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
3984 self.handle_init_event_channel_failures(failed_channels);
3986 for (source, payment_hash, reason) in timed_out_htlcs.drain(..) {
3987 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, reason);
3991 /// Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool
3992 /// indicating whether persistence is necessary. Only one listener on
3993 /// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
3995 /// Note that the feature `allow_wallclock_use` must be enabled to use this function.
3996 #[cfg(any(test, feature = "allow_wallclock_use"))]
3997 pub fn await_persistable_update_timeout(&self, max_wait: Duration) -> bool {
3998 self.persistence_notifier.wait_timeout(max_wait)
4001 /// Blocks until ChannelManager needs to be persisted. Only one listener on
4002 /// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
4004 pub fn await_persistable_update(&self) {
4005 self.persistence_notifier.wait()
4008 #[cfg(any(test, feature = "_test_utils"))]
4009 pub fn get_persistence_condvar_value(&self) -> bool {
4010 let mutcond = &self.persistence_notifier.persistence_lock;
4011 let &(ref mtx, _) = mutcond;
4012 let guard = mtx.lock().unwrap();
4017 impl<Signer: Sign, M: Deref , T: Deref , K: Deref , F: Deref , L: Deref >
4018 ChannelMessageHandler for ChannelManager<Signer, M, T, K, F, L>
4019 where M::Target: chain::Watch<Signer>,
4020 T::Target: BroadcasterInterface,
4021 K::Target: KeysInterface<Signer = Signer>,
4022 F::Target: FeeEstimator,
4025 fn handle_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) {
4026 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4027 let _ = handle_error!(self, self.internal_open_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
4030 fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) {
4031 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4032 let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
4035 fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
4036 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4037 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
4040 fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
4041 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4042 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
4045 fn handle_funding_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingLocked) {
4046 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4047 let _ = handle_error!(self, self.internal_funding_locked(counterparty_node_id, msg), *counterparty_node_id);
4050 fn handle_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) {
4051 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4052 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, their_features, msg), *counterparty_node_id);
4055 fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
4056 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4057 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
4060 fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
4061 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4062 let _ = handle_error!(self, self.internal_update_add_htlc(counterparty_node_id, msg), *counterparty_node_id);
4065 fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
4066 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4067 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
4070 fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
4071 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4072 let _ = handle_error!(self, self.internal_update_fail_htlc(counterparty_node_id, msg), *counterparty_node_id);
4075 fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
4076 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4077 let _ = handle_error!(self, self.internal_update_fail_malformed_htlc(counterparty_node_id, msg), *counterparty_node_id);
4080 fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
4081 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4082 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
4085 fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
4086 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4087 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
4090 fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
4091 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4092 let _ = handle_error!(self, self.internal_update_fee(counterparty_node_id, msg), *counterparty_node_id);
4095 fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
4096 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4097 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
4100 fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
4101 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4102 let _ = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id);
4105 fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
4106 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4107 let _ = handle_error!(self, self.internal_channel_reestablish(counterparty_node_id, msg), *counterparty_node_id);
4110 fn peer_disconnected(&self, counterparty_node_id: &PublicKey, no_connection_possible: bool) {
4111 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4112 let mut failed_channels = Vec::new();
4113 let mut no_channels_remain = true;
4115 let mut channel_state_lock = self.channel_state.lock().unwrap();
4116 let channel_state = &mut *channel_state_lock;
4117 let short_to_id = &mut channel_state.short_to_id;
4118 let pending_msg_events = &mut channel_state.pending_msg_events;
4119 if no_connection_possible {
4120 log_debug!(self.logger, "Failing all channels with {} due to no_connection_possible", log_pubkey!(counterparty_node_id));
4121 channel_state.by_id.retain(|_, chan| {
4122 if chan.get_counterparty_node_id() == *counterparty_node_id {
4123 if let Some(short_id) = chan.get_short_channel_id() {
4124 short_to_id.remove(&short_id);
4126 failed_channels.push(chan.force_shutdown(true));
4127 if let Ok(update) = self.get_channel_update(&chan) {
4128 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4138 log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(counterparty_node_id));
4139 channel_state.by_id.retain(|_, chan| {
4140 if chan.get_counterparty_node_id() == *counterparty_node_id {
4141 chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger);
4142 if chan.is_shutdown() {
4143 if let Some(short_id) = chan.get_short_channel_id() {
4144 short_to_id.remove(&short_id);
4148 no_channels_remain = false;
4154 pending_msg_events.retain(|msg| {
4156 &events::MessageSendEvent::SendAcceptChannel { ref node_id, .. } => node_id != counterparty_node_id,
4157 &events::MessageSendEvent::SendOpenChannel { ref node_id, .. } => node_id != counterparty_node_id,
4158 &events::MessageSendEvent::SendFundingCreated { ref node_id, .. } => node_id != counterparty_node_id,
4159 &events::MessageSendEvent::SendFundingSigned { ref node_id, .. } => node_id != counterparty_node_id,
4160 &events::MessageSendEvent::SendFundingLocked { ref node_id, .. } => node_id != counterparty_node_id,
4161 &events::MessageSendEvent::SendAnnouncementSignatures { ref node_id, .. } => node_id != counterparty_node_id,
4162 &events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => node_id != counterparty_node_id,
4163 &events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => node_id != counterparty_node_id,
4164 &events::MessageSendEvent::SendClosingSigned { ref node_id, .. } => node_id != counterparty_node_id,
4165 &events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != counterparty_node_id,
4166 &events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != counterparty_node_id,
4167 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
4168 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
4169 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
4170 &events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != counterparty_node_id,
4171 &events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
4172 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
4173 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
4174 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
4178 if no_channels_remain {
4179 self.per_peer_state.write().unwrap().remove(counterparty_node_id);
4182 for failure in failed_channels.drain(..) {
4183 self.finish_force_close_channel(failure);
4187 fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init) {
4188 log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
4190 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4193 let mut peer_state_lock = self.per_peer_state.write().unwrap();
4194 match peer_state_lock.entry(counterparty_node_id.clone()) {
4195 hash_map::Entry::Vacant(e) => {
4196 e.insert(Mutex::new(PeerState {
4197 latest_features: init_msg.features.clone(),
4200 hash_map::Entry::Occupied(e) => {
4201 e.get().lock().unwrap().latest_features = init_msg.features.clone();
4206 let mut channel_state_lock = self.channel_state.lock().unwrap();
4207 let channel_state = &mut *channel_state_lock;
4208 let pending_msg_events = &mut channel_state.pending_msg_events;
4209 channel_state.by_id.retain(|_, chan| {
4210 if chan.get_counterparty_node_id() == *counterparty_node_id {
4211 if !chan.have_received_message() {
4212 // If we created this (outbound) channel while we were disconnected from the
4213 // peer we probably failed to send the open_channel message, which is now
4214 // lost. We can't have had anything pending related to this channel, so we just
4218 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
4219 node_id: chan.get_counterparty_node_id(),
4220 msg: chan.get_channel_reestablish(&self.logger),
4226 //TODO: Also re-broadcast announcement_signatures
4229 fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
4230 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4232 if msg.channel_id == [0; 32] {
4233 for chan in self.list_channels() {
4234 if chan.remote_network_id == *counterparty_node_id {
4235 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
4236 let _ = self.force_close_channel_with_peer(&chan.channel_id, Some(counterparty_node_id));
4240 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
4241 let _ = self.force_close_channel_with_peer(&msg.channel_id, Some(counterparty_node_id));
4246 /// Used to signal to the ChannelManager persister that the manager needs to be re-persisted to
4247 /// disk/backups, through `await_persistable_update_timeout` and `await_persistable_update`.
4248 struct PersistenceNotifier {
4249 /// Users won't access the persistence_lock directly, but rather wait on its bool using
4250 /// `wait_timeout` and `wait`.
4251 persistence_lock: (Mutex<bool>, Condvar),
4254 impl PersistenceNotifier {
4257 persistence_lock: (Mutex::new(false), Condvar::new()),
4263 let &(ref mtx, ref cvar) = &self.persistence_lock;
4264 let mut guard = mtx.lock().unwrap();
4269 guard = cvar.wait(guard).unwrap();
4270 let result = *guard;
4278 #[cfg(any(test, feature = "allow_wallclock_use"))]
4279 fn wait_timeout(&self, max_wait: Duration) -> bool {
4280 let current_time = Instant::now();
4282 let &(ref mtx, ref cvar) = &self.persistence_lock;
4283 let mut guard = mtx.lock().unwrap();
4288 guard = cvar.wait_timeout(guard, max_wait).unwrap().0;
4289 // Due to spurious wakeups that can happen on `wait_timeout`, here we need to check if the
4290 // desired wait time has actually passed, and if not then restart the loop with a reduced wait
4291 // time. Note that this logic can be highly simplified through the use of
4292 // `Condvar::wait_while` and `Condvar::wait_timeout_while`, if and when our MSRV is raised to
4294 let elapsed = current_time.elapsed();
4295 let result = *guard;
4296 if result || elapsed >= max_wait {
4300 match max_wait.checked_sub(elapsed) {
4301 None => return result,
4307 // Signal to the ChannelManager persister that there are updates necessitating persisting to disk.
4309 let &(ref persist_mtx, ref cnd) = &self.persistence_lock;
4310 let mut persistence_lock = persist_mtx.lock().unwrap();
4311 *persistence_lock = true;
4312 mem::drop(persistence_lock);
4317 const SERIALIZATION_VERSION: u8 = 1;
4318 const MIN_SERIALIZATION_VERSION: u8 = 1;
4320 impl Writeable for PendingHTLCRouting {
4321 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
4323 &PendingHTLCRouting::Forward { ref onion_packet, ref short_channel_id } => {
4325 onion_packet.write(writer)?;
4326 short_channel_id.write(writer)?;
4328 &PendingHTLCRouting::Receive { ref payment_data, ref incoming_cltv_expiry } => {
4330 payment_data.payment_secret.write(writer)?;
4331 payment_data.total_msat.write(writer)?;
4332 incoming_cltv_expiry.write(writer)?;
4339 impl Readable for PendingHTLCRouting {
4340 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<PendingHTLCRouting, DecodeError> {
4341 match Readable::read(reader)? {
4342 0u8 => Ok(PendingHTLCRouting::Forward {
4343 onion_packet: Readable::read(reader)?,
4344 short_channel_id: Readable::read(reader)?,
4346 1u8 => Ok(PendingHTLCRouting::Receive {
4347 payment_data: msgs::FinalOnionHopData {
4348 payment_secret: Readable::read(reader)?,
4349 total_msat: Readable::read(reader)?,
4351 incoming_cltv_expiry: Readable::read(reader)?,
4353 _ => Err(DecodeError::InvalidValue),
4358 impl_writeable_tlv_based!(PendingHTLCInfo, {
4360 (2, incoming_shared_secret),
4362 (6, amt_to_forward),
4363 (8, outgoing_cltv_value)
4366 impl Writeable for HTLCFailureMsg {
4367 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
4369 &HTLCFailureMsg::Relay(ref fail_msg) => {
4371 fail_msg.write(writer)?;
4373 &HTLCFailureMsg::Malformed(ref fail_msg) => {
4375 fail_msg.write(writer)?;
4382 impl Readable for HTLCFailureMsg {
4383 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
4384 match <u8 as Readable>::read(reader)? {
4385 0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
4386 1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
4387 _ => Err(DecodeError::InvalidValue),
4392 impl Writeable for PendingHTLCStatus {
4393 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
4395 &PendingHTLCStatus::Forward(ref forward_info) => {
4397 forward_info.write(writer)?;
4399 &PendingHTLCStatus::Fail(ref fail_msg) => {
4401 fail_msg.write(writer)?;
4408 impl Readable for PendingHTLCStatus {
4409 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
4410 match <u8 as Readable>::read(reader)? {
4411 0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
4412 1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
4413 _ => Err(DecodeError::InvalidValue),
4418 impl_writeable_tlv_based!(HTLCPreviousHopData, {
4419 (0, short_channel_id),
4422 (6, incoming_packet_shared_secret)
4425 impl Writeable for ClaimableHTLC {
4426 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
4427 write_tlv_fields!(writer, {
4430 (4, self.payment_data.payment_secret),
4431 (6, self.payment_data.total_msat),
4432 (8, self.cltv_expiry)
4438 impl Readable for ClaimableHTLC {
4439 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
4440 let mut prev_hop = HTLCPreviousHopData {
4441 short_channel_id: 0, htlc_id: 0,
4442 incoming_packet_shared_secret: [0; 32],
4443 outpoint: OutPoint::null(),
4446 let mut payment_secret = PaymentSecret([0; 32]);
4447 let mut total_msat = 0;
4448 let mut cltv_expiry = 0;
4449 read_tlv_fields!(reader, {
4452 (4, payment_secret),
4459 payment_data: msgs::FinalOnionHopData {
4468 impl Writeable for HTLCSource {
4469 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
4471 &HTLCSource::PreviousHopData(ref hop_data) => {
4473 hop_data.write(writer)?;
4475 &HTLCSource::OutboundRoute { ref path, ref session_priv, ref first_hop_htlc_msat } => {
4477 path.write(writer)?;
4478 session_priv.write(writer)?;
4479 first_hop_htlc_msat.write(writer)?;
4486 impl Readable for HTLCSource {
4487 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCSource, DecodeError> {
4488 match <u8 as Readable>::read(reader)? {
4489 0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
4490 1 => Ok(HTLCSource::OutboundRoute {
4491 path: Readable::read(reader)?,
4492 session_priv: Readable::read(reader)?,
4493 first_hop_htlc_msat: Readable::read(reader)?,
4495 _ => Err(DecodeError::InvalidValue),
4500 impl Writeable for HTLCFailReason {
4501 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
4503 &HTLCFailReason::LightningError { ref err } => {
4507 &HTLCFailReason::Reason { ref failure_code, ref data } => {
4509 failure_code.write(writer)?;
4510 data.write(writer)?;
4517 impl Readable for HTLCFailReason {
4518 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
4519 match <u8 as Readable>::read(reader)? {
4520 0 => Ok(HTLCFailReason::LightningError { err: Readable::read(reader)? }),
4521 1 => Ok(HTLCFailReason::Reason {
4522 failure_code: Readable::read(reader)?,
4523 data: Readable::read(reader)?,
4525 _ => Err(DecodeError::InvalidValue),
4530 impl Writeable for HTLCForwardInfo {
4531 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
4533 &HTLCForwardInfo::AddHTLC { ref prev_short_channel_id, ref prev_funding_outpoint, ref prev_htlc_id, ref forward_info } => {
4535 prev_short_channel_id.write(writer)?;
4536 prev_funding_outpoint.write(writer)?;
4537 prev_htlc_id.write(writer)?;
4538 forward_info.write(writer)?;
4540 &HTLCForwardInfo::FailHTLC { ref htlc_id, ref err_packet } => {
4542 htlc_id.write(writer)?;
4543 err_packet.write(writer)?;
4550 impl Readable for HTLCForwardInfo {
4551 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCForwardInfo, DecodeError> {
4552 match <u8 as Readable>::read(reader)? {
4553 0 => Ok(HTLCForwardInfo::AddHTLC {
4554 prev_short_channel_id: Readable::read(reader)?,
4555 prev_funding_outpoint: Readable::read(reader)?,
4556 prev_htlc_id: Readable::read(reader)?,
4557 forward_info: Readable::read(reader)?,
4559 1 => Ok(HTLCForwardInfo::FailHTLC {
4560 htlc_id: Readable::read(reader)?,
4561 err_packet: Readable::read(reader)?,
4563 _ => Err(DecodeError::InvalidValue),
4568 impl_writeable_tlv_based!(PendingInboundPayment, {
4569 (0, payment_secret),
4571 (4, user_payment_id),
4572 (6, payment_preimage),
4573 (8, min_value_msat),
4576 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable for ChannelManager<Signer, M, T, K, F, L>
4577 where M::Target: chain::Watch<Signer>,
4578 T::Target: BroadcasterInterface,
4579 K::Target: KeysInterface<Signer = Signer>,
4580 F::Target: FeeEstimator,
4583 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
4584 let _consistency_lock = self.total_consistency_lock.write().unwrap();
4586 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
4588 self.genesis_hash.write(writer)?;
4590 let best_block = self.best_block.read().unwrap();
4591 best_block.height().write(writer)?;
4592 best_block.block_hash().write(writer)?;
4595 let channel_state = self.channel_state.lock().unwrap();
4596 let mut unfunded_channels = 0;
4597 for (_, channel) in channel_state.by_id.iter() {
4598 if !channel.is_funding_initiated() {
4599 unfunded_channels += 1;
4602 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
4603 for (_, channel) in channel_state.by_id.iter() {
4604 if channel.is_funding_initiated() {
4605 channel.write(writer)?;
4609 (channel_state.forward_htlcs.len() as u64).write(writer)?;
4610 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
4611 short_channel_id.write(writer)?;
4612 (pending_forwards.len() as u64).write(writer)?;
4613 for forward in pending_forwards {
4614 forward.write(writer)?;
4618 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
4619 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
4620 payment_hash.write(writer)?;
4621 (previous_hops.len() as u64).write(writer)?;
4622 for htlc in previous_hops.iter() {
4623 htlc.write(writer)?;
4627 let per_peer_state = self.per_peer_state.write().unwrap();
4628 (per_peer_state.len() as u64).write(writer)?;
4629 for (peer_pubkey, peer_state_mutex) in per_peer_state.iter() {
4630 peer_pubkey.write(writer)?;
4631 let peer_state = peer_state_mutex.lock().unwrap();
4632 peer_state.latest_features.write(writer)?;
4635 let events = self.pending_events.lock().unwrap();
4636 (events.len() as u64).write(writer)?;
4637 for event in events.iter() {
4638 event.write(writer)?;
4641 let background_events = self.pending_background_events.lock().unwrap();
4642 (background_events.len() as u64).write(writer)?;
4643 for event in background_events.iter() {
4645 BackgroundEvent::ClosingMonitorUpdate((funding_txo, monitor_update)) => {
4647 funding_txo.write(writer)?;
4648 monitor_update.write(writer)?;
4653 (self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
4654 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
4656 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
4657 (pending_inbound_payments.len() as u64).write(writer)?;
4658 for (hash, pending_payment) in pending_inbound_payments.iter() {
4659 hash.write(writer)?;
4660 pending_payment.write(writer)?;
4663 let pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
4664 (pending_outbound_payments.len() as u64).write(writer)?;
4665 for session_priv in pending_outbound_payments.iter() {
4666 session_priv.write(writer)?;
4669 write_tlv_fields!(writer, {}, {});
4675 /// Arguments for the creation of a ChannelManager that are not deserialized.
4677 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
4679 /// 1) Deserialize all stored ChannelMonitors.
4680 /// 2) Deserialize the ChannelManager by filling in this struct and calling:
4681 /// <(BlockHash, ChannelManager)>::read(reader, args)
4682 /// This may result in closing some Channels if the ChannelMonitor is newer than the stored
4683 /// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
4684 /// 3) If you are not fetching full blocks, register all relevant ChannelMonitor outpoints the same
4685 /// way you would handle a `chain::Filter` call using ChannelMonitor::get_outputs_to_watch() and
4686 /// ChannelMonitor::get_funding_txo().
4687 /// 4) Reconnect blocks on your ChannelMonitors.
4688 /// 5) Disconnect/connect blocks on the ChannelManager.
4689 /// 6) Move the ChannelMonitors into your local chain::Watch.
4691 /// Note that the ordering of #4-6 is not of importance, however all three must occur before you
4692 /// call any other methods on the newly-deserialized ChannelManager.
4694 /// Note that because some channels may be closed during deserialization, it is critical that you
4695 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
4696 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
4697 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
4698 /// not force-close the same channels but consider them live), you may end up revoking a state for
4699 /// which you've already broadcasted the transaction.
4700 pub struct ChannelManagerReadArgs<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4701 where M::Target: chain::Watch<Signer>,
4702 T::Target: BroadcasterInterface,
4703 K::Target: KeysInterface<Signer = Signer>,
4704 F::Target: FeeEstimator,
4707 /// The keys provider which will give us relevant keys. Some keys will be loaded during
4708 /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
4710 pub keys_manager: K,
4712 /// The fee_estimator for use in the ChannelManager in the future.
4714 /// No calls to the FeeEstimator will be made during deserialization.
4715 pub fee_estimator: F,
4716 /// The chain::Watch for use in the ChannelManager in the future.
4718 /// No calls to the chain::Watch will be made during deserialization. It is assumed that
4719 /// you have deserialized ChannelMonitors separately and will add them to your
4720 /// chain::Watch after deserializing this ChannelManager.
4721 pub chain_monitor: M,
4723 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
4724 /// used to broadcast the latest local commitment transactions of channels which must be
4725 /// force-closed during deserialization.
4726 pub tx_broadcaster: T,
4727 /// The Logger for use in the ChannelManager and which may be used to log information during
4728 /// deserialization.
4730 /// Default settings used for new channels. Any existing channels will continue to use the
4731 /// runtime settings which were stored when the ChannelManager was serialized.
4732 pub default_config: UserConfig,
4734 /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
4735 /// value.get_funding_txo() should be the key).
4737 /// If a monitor is inconsistent with the channel state during deserialization the channel will
4738 /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
4739 /// is true for missing channels as well. If there is a monitor missing for which we find
4740 /// channel data Err(DecodeError::InvalidValue) will be returned.
4742 /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
4745 /// (C-not exported) because we have no HashMap bindings
4746 pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<Signer>>,
4749 impl<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4750 ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>
4751 where M::Target: chain::Watch<Signer>,
4752 T::Target: BroadcasterInterface,
4753 K::Target: KeysInterface<Signer = Signer>,
4754 F::Target: FeeEstimator,
4757 /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
4758 /// HashMap for you. This is primarily useful for C bindings where it is not practical to
4759 /// populate a HashMap directly from C.
4760 pub fn new(keys_manager: K, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, logger: L, default_config: UserConfig,
4761 mut channel_monitors: Vec<&'a mut ChannelMonitor<Signer>>) -> Self {
4763 keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, default_config,
4764 channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
4769 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
4770 // SipmleArcChannelManager type:
4771 impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4772 ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, Arc<ChannelManager<Signer, M, T, K, F, L>>)
4773 where M::Target: chain::Watch<Signer>,
4774 T::Target: BroadcasterInterface,
4775 K::Target: KeysInterface<Signer = Signer>,
4776 F::Target: FeeEstimator,
4779 fn read<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
4780 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<Signer, M, T, K, F, L>)>::read(reader, args)?;
4781 Ok((blockhash, Arc::new(chan_manager)))
4785 impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4786 ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, ChannelManager<Signer, M, T, K, F, L>)
4787 where M::Target: chain::Watch<Signer>,
4788 T::Target: BroadcasterInterface,
4789 K::Target: KeysInterface<Signer = Signer>,
4790 F::Target: FeeEstimator,
4793 fn read<R: ::std::io::Read>(reader: &mut R, mut args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
4794 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
4796 let genesis_hash: BlockHash = Readable::read(reader)?;
4797 let best_block_height: u32 = Readable::read(reader)?;
4798 let best_block_hash: BlockHash = Readable::read(reader)?;
4800 let mut failed_htlcs = Vec::new();
4802 let channel_count: u64 = Readable::read(reader)?;
4803 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
4804 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
4805 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
4806 for _ in 0..channel_count {
4807 let mut channel: Channel<Signer> = Channel::read(reader, &args.keys_manager)?;
4808 let funding_txo = channel.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
4809 funding_txo_set.insert(funding_txo.clone());
4810 if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
4811 if channel.get_cur_holder_commitment_transaction_number() < monitor.get_cur_holder_commitment_number() ||
4812 channel.get_revoked_counterparty_commitment_transaction_number() < monitor.get_min_seen_secret() ||
4813 channel.get_cur_counterparty_commitment_transaction_number() < monitor.get_cur_counterparty_commitment_number() ||
4814 channel.get_latest_monitor_update_id() > monitor.get_latest_update_id() {
4815 // If the channel is ahead of the monitor, return InvalidValue:
4816 return Err(DecodeError::InvalidValue);
4817 } else if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
4818 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
4819 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
4820 channel.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
4821 // But if the channel is behind of the monitor, close the channel:
4822 let (_, mut new_failed_htlcs) = channel.force_shutdown(true);
4823 failed_htlcs.append(&mut new_failed_htlcs);
4824 monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
4826 if let Some(short_channel_id) = channel.get_short_channel_id() {
4827 short_to_id.insert(short_channel_id, channel.channel_id());
4829 by_id.insert(channel.channel_id(), channel);
4832 return Err(DecodeError::InvalidValue);
4836 for (ref funding_txo, ref mut monitor) in args.channel_monitors.iter_mut() {
4837 if !funding_txo_set.contains(funding_txo) {
4838 monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
4842 const MAX_ALLOC_SIZE: usize = 1024 * 64;
4843 let forward_htlcs_count: u64 = Readable::read(reader)?;
4844 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
4845 for _ in 0..forward_htlcs_count {
4846 let short_channel_id = Readable::read(reader)?;
4847 let pending_forwards_count: u64 = Readable::read(reader)?;
4848 let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
4849 for _ in 0..pending_forwards_count {
4850 pending_forwards.push(Readable::read(reader)?);
4852 forward_htlcs.insert(short_channel_id, pending_forwards);
4855 let claimable_htlcs_count: u64 = Readable::read(reader)?;
4856 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
4857 for _ in 0..claimable_htlcs_count {
4858 let payment_hash = Readable::read(reader)?;
4859 let previous_hops_len: u64 = Readable::read(reader)?;
4860 let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
4861 for _ in 0..previous_hops_len {
4862 previous_hops.push(Readable::read(reader)?);
4864 claimable_htlcs.insert(payment_hash, previous_hops);
4867 let peer_count: u64 = Readable::read(reader)?;
4868 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState>)>()));
4869 for _ in 0..peer_count {
4870 let peer_pubkey = Readable::read(reader)?;
4871 let peer_state = PeerState {
4872 latest_features: Readable::read(reader)?,
4874 per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
4877 let event_count: u64 = Readable::read(reader)?;
4878 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>()));
4879 for _ in 0..event_count {
4880 match MaybeReadable::read(reader)? {
4881 Some(event) => pending_events_read.push(event),
4886 let background_event_count: u64 = Readable::read(reader)?;
4887 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>()));
4888 for _ in 0..background_event_count {
4889 match <u8 as Readable>::read(reader)? {
4890 0 => pending_background_events_read.push(BackgroundEvent::ClosingMonitorUpdate((Readable::read(reader)?, Readable::read(reader)?))),
4891 _ => return Err(DecodeError::InvalidValue),
4895 let last_node_announcement_serial: u32 = Readable::read(reader)?;
4896 let highest_seen_timestamp: u32 = Readable::read(reader)?;
4898 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
4899 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
4900 for _ in 0..pending_inbound_payment_count {
4901 if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
4902 return Err(DecodeError::InvalidValue);
4906 let pending_outbound_payments_count: u64 = Readable::read(reader)?;
4907 let mut pending_outbound_payments: HashSet<[u8; 32]> = HashSet::with_capacity(cmp::min(pending_outbound_payments_count as usize, MAX_ALLOC_SIZE/32));
4908 for _ in 0..pending_outbound_payments_count {
4909 if !pending_outbound_payments.insert(Readable::read(reader)?) {
4910 return Err(DecodeError::InvalidValue);
4914 read_tlv_fields!(reader, {}, {});
4916 let mut secp_ctx = Secp256k1::new();
4917 secp_ctx.seeded_randomize(&args.keys_manager.get_secure_random_bytes());
4919 let channel_manager = ChannelManager {
4921 fee_estimator: args.fee_estimator,
4922 chain_monitor: args.chain_monitor,
4923 tx_broadcaster: args.tx_broadcaster,
4925 best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
4927 channel_state: Mutex::new(ChannelHolder {
4932 pending_msg_events: Vec::new(),
4934 pending_inbound_payments: Mutex::new(pending_inbound_payments),
4935 pending_outbound_payments: Mutex::new(pending_outbound_payments),
4937 our_network_key: args.keys_manager.get_node_secret(),
4938 our_network_pubkey: PublicKey::from_secret_key(&secp_ctx, &args.keys_manager.get_node_secret()),
4941 last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
4942 highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
4944 per_peer_state: RwLock::new(per_peer_state),
4946 pending_events: Mutex::new(pending_events_read),
4947 pending_background_events: Mutex::new(pending_background_events_read),
4948 total_consistency_lock: RwLock::new(()),
4949 persistence_notifier: PersistenceNotifier::new(),
4951 keys_manager: args.keys_manager,
4952 logger: args.logger,
4953 default_configuration: args.default_config,
4956 for htlc_source in failed_htlcs.drain(..) {
4957 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() });
4960 //TODO: Broadcast channel update for closed channels, but only after we've made a
4961 //connection or two.
4963 Ok((best_block_hash.clone(), channel_manager))
4969 use ln::channelmanager::PersistenceNotifier;
4971 use core::sync::atomic::{AtomicBool, Ordering};
4973 use core::time::Duration;
4976 fn test_wait_timeout() {
4977 let persistence_notifier = Arc::new(PersistenceNotifier::new());
4978 let thread_notifier = Arc::clone(&persistence_notifier);
4980 let exit_thread = Arc::new(AtomicBool::new(false));
4981 let exit_thread_clone = exit_thread.clone();
4982 thread::spawn(move || {
4984 let &(ref persist_mtx, ref cnd) = &thread_notifier.persistence_lock;
4985 let mut persistence_lock = persist_mtx.lock().unwrap();
4986 *persistence_lock = true;
4989 if exit_thread_clone.load(Ordering::SeqCst) {
4995 // Check that we can block indefinitely until updates are available.
4996 let _ = persistence_notifier.wait();
4998 // Check that the PersistenceNotifier will return after the given duration if updates are
5001 if persistence_notifier.wait_timeout(Duration::from_millis(100)) {
5006 exit_thread.store(true, Ordering::SeqCst);
5008 // Check that the PersistenceNotifier will return after the given duration even if no updates
5011 if !persistence_notifier.wait_timeout(Duration::from_millis(100)) {
5018 #[cfg(all(any(test, feature = "_test_utils"), feature = "unstable"))]
5021 use chain::chainmonitor::ChainMonitor;
5022 use chain::channelmonitor::Persist;
5023 use chain::keysinterface::{KeysManager, InMemorySigner};
5024 use ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage};
5025 use ln::features::{InitFeatures, InvoiceFeatures};
5026 use ln::functional_test_utils::*;
5027 use ln::msgs::ChannelMessageHandler;
5028 use routing::network_graph::NetworkGraph;
5029 use routing::router::get_route;
5030 use util::test_utils;
5031 use util::config::UserConfig;
5032 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
5034 use bitcoin::hashes::Hash;
5035 use bitcoin::hashes::sha256::Hash as Sha256;
5036 use bitcoin::{Block, BlockHeader, Transaction, TxOut};
5038 use std::sync::Mutex;
5042 struct NodeHolder<'a, P: Persist<InMemorySigner>> {
5043 node: &'a ChannelManager<InMemorySigner,
5044 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
5045 &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
5046 &'a test_utils::TestLogger, &'a P>,
5047 &'a test_utils::TestBroadcaster, &'a KeysManager,
5048 &'a test_utils::TestFeeEstimator, &'a test_utils::TestLogger>
5053 fn bench_sends(bench: &mut Bencher) {
5054 bench_two_sends(bench, test_utils::TestPersister::new(), test_utils::TestPersister::new());
5057 pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Bencher, persister_a: P, persister_b: P) {
5058 // Do a simple benchmark of sending a payment back and forth between two nodes.
5059 // Note that this is unrealistic as each payment send will require at least two fsync
5061 let network = bitcoin::Network::Testnet;
5062 let genesis_hash = bitcoin::blockdata::constants::genesis_block(network).header.block_hash();
5064 let tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
5065 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
5067 let mut config: UserConfig = Default::default();
5068 config.own_channel_config.minimum_depth = 1;
5070 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
5071 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
5072 let seed_a = [1u8; 32];
5073 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
5074 let node_a = ChannelManager::new(&fee_estimator, &chain_monitor_a, &tx_broadcaster, &logger_a, &keys_manager_a, config.clone(), ChainParameters {
5076 best_block: BestBlock::from_genesis(network),
5078 let node_a_holder = NodeHolder { node: &node_a };
5080 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
5081 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
5082 let seed_b = [2u8; 32];
5083 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
5084 let node_b = ChannelManager::new(&fee_estimator, &chain_monitor_b, &tx_broadcaster, &logger_b, &keys_manager_b, config.clone(), ChainParameters {
5086 best_block: BestBlock::from_genesis(network),
5088 let node_b_holder = NodeHolder { node: &node_b };
5090 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
5091 node_b.handle_open_channel(&node_a.get_our_node_id(), InitFeatures::known(), &get_event_msg!(node_a_holder, MessageSendEvent::SendOpenChannel, node_b.get_our_node_id()));
5092 node_a.handle_accept_channel(&node_b.get_our_node_id(), InitFeatures::known(), &get_event_msg!(node_b_holder, MessageSendEvent::SendAcceptChannel, node_a.get_our_node_id()));
5095 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
5096 tx = Transaction { version: 2, lock_time: 0, input: Vec::new(), output: vec![TxOut {
5097 value: 8_000_000, script_pubkey: output_script,
5099 node_a.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
5100 } else { panic!(); }
5102 node_b.handle_funding_created(&node_a.get_our_node_id(), &get_event_msg!(node_a_holder, MessageSendEvent::SendFundingCreated, node_b.get_our_node_id()));
5103 node_a.handle_funding_signed(&node_b.get_our_node_id(), &get_event_msg!(node_b_holder, MessageSendEvent::SendFundingSigned, node_a.get_our_node_id()));
5105 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
5108 header: BlockHeader { version: 0x20000000, prev_blockhash: genesis_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5111 Listen::block_connected(&node_a, &block, 1);
5112 Listen::block_connected(&node_b, &block, 1);
5114 node_a.handle_funding_locked(&node_b.get_our_node_id(), &get_event_msg!(node_b_holder, MessageSendEvent::SendFundingLocked, node_a.get_our_node_id()));
5115 node_b.handle_funding_locked(&node_a.get_our_node_id(), &get_event_msg!(node_a_holder, MessageSendEvent::SendFundingLocked, node_b.get_our_node_id()));
5117 let dummy_graph = NetworkGraph::new(genesis_hash);
5119 let mut payment_count: u64 = 0;
5120 macro_rules! send_payment {
5121 ($node_a: expr, $node_b: expr) => {
5122 let usable_channels = $node_a.list_usable_channels();
5123 let route = get_route(&$node_a.get_our_node_id(), &dummy_graph, &$node_b.get_our_node_id(), Some(InvoiceFeatures::known()),
5124 Some(&usable_channels.iter().map(|r| r).collect::<Vec<_>>()), &[], 10_000, TEST_FINAL_CLTV, &logger_a).unwrap();
5126 let mut payment_preimage = PaymentPreimage([0; 32]);
5127 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
5129 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
5130 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, 0).unwrap();
5132 $node_a.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5133 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
5134 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
5135 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
5136 let (raa, cs) = get_revoke_commit_msgs!(NodeHolder { node: &$node_b }, $node_a.get_our_node_id());
5137 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
5138 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
5139 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &get_event_msg!(NodeHolder { node: &$node_a }, MessageSendEvent::SendRevokeAndACK, $node_b.get_our_node_id()));
5141 expect_pending_htlcs_forwardable!(NodeHolder { node: &$node_b });
5142 expect_payment_received!(NodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
5143 assert!($node_b.claim_funds(payment_preimage));
5145 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
5146 MessageSendEvent::UpdateHTLCs { node_id, updates } => {
5147 assert_eq!(node_id, $node_a.get_our_node_id());
5148 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5149 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
5151 _ => panic!("Failed to generate claim event"),
5154 let (raa, cs) = get_revoke_commit_msgs!(NodeHolder { node: &$node_a }, $node_b.get_our_node_id());
5155 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
5156 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
5157 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &get_event_msg!(NodeHolder { node: &$node_b }, MessageSendEvent::SendRevokeAndACK, $node_a.get_our_node_id()));
5159 expect_payment_sent!(NodeHolder { node: &$node_a }, payment_preimage);
5164 send_payment!(node_a, node_b);
5165 send_payment!(node_b, node_a);