1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level channel management and payment tracking stuff lives here.
12 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
13 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
14 //! upon reconnect to the relevant peer(s).
16 //! It does not manage routing logic (see routing::router::get_route for that) nor does it manage constructing
17 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
18 //! imply it needs to fail HTLCs/payments/channels it manages).
21 use bitcoin::blockdata::block::{Block, BlockHeader};
22 use bitcoin::blockdata::constants::genesis_block;
23 use bitcoin::network::constants::Network;
25 use bitcoin::hashes::{Hash, HashEngine};
26 use bitcoin::hashes::hmac::{Hmac, HmacEngine};
27 use bitcoin::hashes::sha256::Hash as Sha256;
28 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
29 use bitcoin::hashes::cmp::fixed_time_eq;
30 use bitcoin::hash_types::BlockHash;
32 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
33 use bitcoin::secp256k1::Secp256k1;
34 use bitcoin::secp256k1::ecdh::SharedSecret;
35 use bitcoin::secp256k1;
39 use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
40 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, ChannelMonitorUpdateErr, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent, CLOSED_CHANNEL_UPDATE_ID};
41 use chain::transaction::{OutPoint, TransactionData};
42 use ln::channel::{Channel, ChannelError};
43 use ln::features::{InitFeatures, NodeFeatures};
44 use routing::router::{Route, RouteHop};
46 use ln::msgs::NetAddress;
48 use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, OptionalField};
49 use chain::keysinterface::{Sign, KeysInterface, KeysManager, InMemorySigner};
50 use util::config::UserConfig;
51 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
52 use util::{byte_utils, events};
53 use util::ser::{Readable, ReadableArgs, MaybeReadable, Writeable, Writer};
54 use util::chacha20::{ChaCha20, ChaChaReader};
55 use util::logger::Logger;
56 use util::errors::APIError;
59 use std::collections::{HashMap, hash_map, HashSet};
60 use std::io::{Cursor, Read};
61 use std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard};
62 use std::sync::atomic::{AtomicUsize, Ordering};
63 use std::time::Duration;
64 #[cfg(any(test, feature = "allow_wallclock_use"))]
65 use std::time::Instant;
66 use std::marker::{Sync, Send};
68 use bitcoin::hashes::hex::ToHex;
70 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
72 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
73 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
74 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
76 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
77 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
78 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
79 // before we forward it.
81 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
82 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
83 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
84 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
85 // our payment, which we can use to decode errors or inform the user that the payment was sent.
87 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
88 enum PendingHTLCRouting {
90 onion_packet: msgs::OnionPacket,
91 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
94 payment_data: Option<msgs::FinalOnionHopData>,
95 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
99 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
100 pub(super) struct PendingHTLCInfo {
101 routing: PendingHTLCRouting,
102 incoming_shared_secret: [u8; 32],
103 payment_hash: PaymentHash,
104 pub(super) amt_to_forward: u64,
105 pub(super) outgoing_cltv_value: u32,
108 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
109 pub(super) enum HTLCFailureMsg {
110 Relay(msgs::UpdateFailHTLC),
111 Malformed(msgs::UpdateFailMalformedHTLC),
114 /// Stores whether we can't forward an HTLC or relevant forwarding info
115 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
116 pub(super) enum PendingHTLCStatus {
117 Forward(PendingHTLCInfo),
118 Fail(HTLCFailureMsg),
121 pub(super) enum HTLCForwardInfo {
123 forward_info: PendingHTLCInfo,
125 // These fields are produced in `forward_htlcs()` and consumed in
126 // `process_pending_htlc_forwards()` for constructing the
127 // `HTLCSource::PreviousHopData` for failed and forwarded
129 prev_short_channel_id: u64,
131 prev_funding_outpoint: OutPoint,
135 err_packet: msgs::OnionErrorPacket,
139 /// Tracks the inbound corresponding to an outbound HTLC
140 #[derive(Clone, PartialEq)]
141 pub(crate) struct HTLCPreviousHopData {
142 short_channel_id: u64,
144 incoming_packet_shared_secret: [u8; 32],
146 // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
147 // channel with a preimage provided by the forward channel.
151 struct ClaimableHTLC {
152 prev_hop: HTLCPreviousHopData,
154 /// Filled in when the HTLC was received with a payment_secret packet, which contains a
155 /// total_msat (which may differ from value if this is a Multi-Path Payment) and a
156 /// payment_secret which prevents path-probing attacks and can associate different HTLCs which
157 /// are part of the same payment.
158 payment_data: Option<msgs::FinalOnionHopData>,
162 /// Tracks the inbound corresponding to an outbound HTLC
163 #[derive(Clone, PartialEq)]
164 pub(crate) enum HTLCSource {
165 PreviousHopData(HTLCPreviousHopData),
168 session_priv: SecretKey,
169 /// Technically we can recalculate this from the route, but we cache it here to avoid
170 /// doing a double-pass on route when we get a failure back
171 first_hop_htlc_msat: u64,
176 pub fn dummy() -> Self {
177 HTLCSource::OutboundRoute {
179 session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
180 first_hop_htlc_msat: 0,
185 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
186 pub(super) enum HTLCFailReason {
188 err: msgs::OnionErrorPacket,
196 /// payment_hash type, use to cross-lock hop
197 /// (C-not exported) as we just use [u8; 32] directly
198 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
199 pub struct PaymentHash(pub [u8;32]);
200 /// payment_preimage type, use to route payment between hop
201 /// (C-not exported) as we just use [u8; 32] directly
202 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
203 pub struct PaymentPreimage(pub [u8;32]);
204 /// payment_secret type, use to authenticate sender to the receiver and tie MPP HTLCs together
205 /// (C-not exported) as we just use [u8; 32] directly
206 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
207 pub struct PaymentSecret(pub [u8;32]);
209 type ShutdownResult = (Option<OutPoint>, ChannelMonitorUpdate, Vec<(HTLCSource, PaymentHash)>);
211 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
212 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
213 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
214 /// channel_state lock. We then return the set of things that need to be done outside the lock in
215 /// this struct and call handle_error!() on it.
217 struct MsgHandleErrInternal {
218 err: msgs::LightningError,
219 shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
221 impl MsgHandleErrInternal {
223 fn send_err_msg_no_close(err: String, channel_id: [u8; 32]) -> Self {
225 err: LightningError {
227 action: msgs::ErrorAction::SendErrorMessage {
228 msg: msgs::ErrorMessage {
234 shutdown_finish: None,
238 fn ignore_no_close(err: String) -> Self {
240 err: LightningError {
242 action: msgs::ErrorAction::IgnoreError,
244 shutdown_finish: None,
248 fn from_no_close(err: msgs::LightningError) -> Self {
249 Self { err, shutdown_finish: None }
252 fn from_finish_shutdown(err: String, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
254 err: LightningError {
256 action: msgs::ErrorAction::SendErrorMessage {
257 msg: msgs::ErrorMessage {
263 shutdown_finish: Some((shutdown_res, channel_update)),
267 fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
270 ChannelError::Ignore(msg) => LightningError {
272 action: msgs::ErrorAction::IgnoreError,
274 ChannelError::Close(msg) => LightningError {
276 action: msgs::ErrorAction::SendErrorMessage {
277 msg: msgs::ErrorMessage {
283 ChannelError::CloseDelayBroadcast(msg) => LightningError {
285 action: msgs::ErrorAction::SendErrorMessage {
286 msg: msgs::ErrorMessage {
293 shutdown_finish: None,
298 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
299 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
300 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
301 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
302 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
304 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
305 /// be sent in the order they appear in the return value, however sometimes the order needs to be
306 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
307 /// they were originally sent). In those cases, this enum is also returned.
308 #[derive(Clone, PartialEq)]
309 pub(super) enum RAACommitmentOrder {
310 /// Send the CommitmentUpdate messages first
312 /// Send the RevokeAndACK message first
316 // Note this is only exposed in cfg(test):
317 pub(super) struct ChannelHolder<Signer: Sign> {
318 pub(super) by_id: HashMap<[u8; 32], Channel<Signer>>,
319 pub(super) short_to_id: HashMap<u64, [u8; 32]>,
320 /// short channel id -> forward infos. Key of 0 means payments received
321 /// Note that while this is held in the same mutex as the channels themselves, no consistency
322 /// guarantees are made about the existence of a channel with the short id here, nor the short
323 /// ids in the PendingHTLCInfo!
324 pub(super) forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
325 /// (payment_hash, payment_secret) -> Vec<HTLCs> for tracking HTLCs that
326 /// were to us and can be failed/claimed by the user
327 /// Note that while this is held in the same mutex as the channels themselves, no consistency
328 /// guarantees are made about the channels given here actually existing anymore by the time you
330 claimable_htlcs: HashMap<(PaymentHash, Option<PaymentSecret>), Vec<ClaimableHTLC>>,
331 /// Messages to send to peers - pushed to in the same lock that they are generated in (except
332 /// for broadcast messages, where ordering isn't as strict).
333 pub(super) pending_msg_events: Vec<MessageSendEvent>,
336 /// State we hold per-peer. In the future we should put channels in here, but for now we only hold
337 /// the latest Init features we heard from the peer.
339 latest_features: InitFeatures,
342 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
343 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
345 /// SimpleArcChannelManager is useful when you need a ChannelManager with a static lifetime, e.g.
346 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
347 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
348 /// SimpleRefChannelManager is the more appropriate type. Defining these type aliases prevents
349 /// issues such as overly long function definitions. Note that the ChannelManager can take any
350 /// type that implements KeysInterface for its keys manager, but this type alias chooses the
351 /// concrete type of the KeysManager.
352 pub type SimpleArcChannelManager<M, T, F, L> = Arc<ChannelManager<InMemorySigner, Arc<M>, Arc<T>, Arc<KeysManager>, Arc<F>, Arc<L>>>;
354 /// SimpleRefChannelManager is a type alias for a ChannelManager reference, and is the reference
355 /// counterpart to the SimpleArcChannelManager type alias. Use this type by default when you don't
356 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
357 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
358 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
359 /// helps with issues such as long function definitions. Note that the ChannelManager can take any
360 /// type that implements KeysInterface for its keys manager, but this type alias chooses the
361 /// concrete type of the KeysManager.
362 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManager<InMemorySigner, &'a M, &'b T, &'c KeysManager, &'d F, &'e L>;
364 /// Manager which keeps track of a number of channels and sends messages to the appropriate
365 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
367 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
368 /// to individual Channels.
370 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
371 /// all peers during write/read (though does not modify this instance, only the instance being
372 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
373 /// called funding_transaction_generated for outbound channels).
375 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
376 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
377 /// returning from chain::Watch::watch_/update_channel, with ChannelManagers, writing updates
378 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
379 /// the serialization process). If the deserialized version is out-of-date compared to the
380 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
381 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
383 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
384 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
385 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
386 /// block_connected() to step towards your best block) upon deserialization before using the
389 /// Note that ChannelManager is responsible for tracking liveness of its channels and generating
390 /// ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid
391 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
392 /// offline for a full minute. In order to track this, you must call
393 /// timer_chan_freshness_every_min roughly once per minute, though it doesn't have to be perfect.
395 /// Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager
396 /// a SimpleRefChannelManager, for conciseness. See their documentation for more details, but
397 /// essentially you should default to using a SimpleRefChannelManager, and use a
398 /// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
399 /// you're using lightning-net-tokio.
400 pub struct ChannelManager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
401 where M::Target: chain::Watch<Signer>,
402 T::Target: BroadcasterInterface,
403 K::Target: KeysInterface<Signer = Signer>,
404 F::Target: FeeEstimator,
407 default_configuration: UserConfig,
408 genesis_hash: BlockHash,
414 pub(super) latest_block_height: AtomicUsize,
416 latest_block_height: AtomicUsize,
417 last_block_hash: Mutex<BlockHash>,
418 secp_ctx: Secp256k1<secp256k1::All>,
420 #[cfg(any(test, feature = "_test_utils"))]
421 pub(super) channel_state: Mutex<ChannelHolder<Signer>>,
422 #[cfg(not(any(test, feature = "_test_utils")))]
423 channel_state: Mutex<ChannelHolder<Signer>>,
424 our_network_key: SecretKey,
426 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
427 /// value increases strictly since we don't assume access to a time source.
428 last_node_announcement_serial: AtomicUsize,
430 /// The bulk of our storage will eventually be here (channels and message queues and the like).
431 /// If we are connected to a peer we always at least have an entry here, even if no channels
432 /// are currently open with that peer.
433 /// Because adding or removing an entry is rare, we usually take an outer read lock and then
434 /// operate on the inner value freely. Sadly, this prevents parallel operation when opening a
436 per_peer_state: RwLock<HashMap<PublicKey, Mutex<PeerState>>>,
438 pending_events: Mutex<Vec<events::Event>>,
439 /// Used when we have to take a BIG lock to make sure everything is self-consistent.
440 /// Essentially just when we're serializing ourselves out.
441 /// Taken first everywhere where we are making changes before any other locks.
442 /// When acquiring this lock in read mode, rather than acquiring it directly, call
443 /// `PersistenceNotifierGuard::new(..)` and pass the lock to it, to ensure the PersistenceNotifier
444 /// the lock contains sends out a notification when the lock is released.
445 total_consistency_lock: RwLock<()>,
447 persistence_notifier: PersistenceNotifier,
454 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
455 /// desirable to notify any listeners on `wait_timeout`/`wait` that new updates are available for
456 /// persistence. Therefore, this struct is responsible for locking the total consistency lock and,
457 /// upon going out of scope, sending the aforementioned notification (since the lock being released
458 /// indicates that the updates are ready for persistence).
459 struct PersistenceNotifierGuard<'a> {
460 persistence_notifier: &'a PersistenceNotifier,
461 // We hold onto this result so the lock doesn't get released immediately.
462 _read_guard: RwLockReadGuard<'a, ()>,
465 impl<'a> PersistenceNotifierGuard<'a> {
466 fn new(lock: &'a RwLock<()>, notifier: &'a PersistenceNotifier) -> Self {
467 let read_guard = lock.read().unwrap();
470 persistence_notifier: notifier,
471 _read_guard: read_guard,
476 impl<'a> Drop for PersistenceNotifierGuard<'a> {
478 self.persistence_notifier.notify();
482 /// The amount of time we require our counterparty wait to claim their money (ie time between when
483 /// we, or our watchtower, must check for them having broadcast a theft transaction).
484 pub(crate) const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
485 /// The amount of time we're willing to wait to claim money back to us
486 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 6 * 24 * 7;
488 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
489 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
490 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
491 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
492 /// CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
493 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
494 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
496 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
497 // ie that if the next-hop peer fails the HTLC within
498 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
499 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
500 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
501 // LATENCY_GRACE_PERIOD_BLOCKS.
504 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - CLTV_CLAIM_BUFFER - ANTI_REORG_DELAY - LATENCY_GRACE_PERIOD_BLOCKS;
506 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
507 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
510 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
512 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
514 pub struct ChannelDetails {
515 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
516 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
517 /// Note that this means this value is *not* persistent - it can change once during the
518 /// lifetime of the channel.
519 pub channel_id: [u8; 32],
520 /// The position of the funding transaction in the chain. None if the funding transaction has
521 /// not yet been confirmed and the channel fully opened.
522 pub short_channel_id: Option<u64>,
523 /// The node_id of our counterparty
524 pub remote_network_id: PublicKey,
525 /// The Features the channel counterparty provided upon last connection.
526 /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
527 /// many routing-relevant features are present in the init context.
528 pub counterparty_features: InitFeatures,
529 /// The value, in satoshis, of this channel as appears in the funding output
530 pub channel_value_satoshis: u64,
531 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
533 /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
534 /// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
535 /// available for inclusion in new outbound HTLCs). This further does not include any pending
536 /// outgoing HTLCs which are awaiting some other resolution to be sent.
537 pub outbound_capacity_msat: u64,
538 /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
539 /// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
540 /// available for inclusion in new inbound HTLCs).
541 /// Note that there are some corner cases not fully handled here, so the actual available
542 /// inbound capacity may be slightly higher than this.
543 pub inbound_capacity_msat: u64,
544 /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
545 /// the peer is connected, and (c) no monitor update failure is pending resolution.
549 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
550 /// Err() type describing which state the payment is in, see the description of individual enum
552 #[derive(Clone, Debug)]
553 pub enum PaymentSendFailure {
554 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
555 /// send the payment at all. No channel state has been changed or messages sent to peers, and
556 /// once you've changed the parameter at error, you can freely retry the payment in full.
557 ParameterError(APIError),
558 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
559 /// from attempting to send the payment at all. No channel state has been changed or messages
560 /// sent to peers, and once you've changed the parameter at error, you can freely retry the
563 /// The results here are ordered the same as the paths in the route object which was passed to
565 PathParameterError(Vec<Result<(), APIError>>),
566 /// All paths which were attempted failed to send, with no channel state change taking place.
567 /// You can freely retry the payment in full (though you probably want to do so over different
568 /// paths than the ones selected).
569 AllFailedRetrySafe(Vec<APIError>),
570 /// Some paths which were attempted failed to send, though possibly not all. At least some
571 /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
572 /// in over-/re-payment.
574 /// The results here are ordered the same as the paths in the route object which was passed to
575 /// send_payment, and any Errs which are not APIError::MonitorUpdateFailed can be safely
576 /// retried (though there is currently no API with which to do so).
578 /// Any entries which contain Err(APIError::MonitorUpdateFailed) or Ok(()) MUST NOT be retried
579 /// as they will result in over-/re-payment. These HTLCs all either successfully sent (in the
580 /// case of Ok(())) or will send once channel_monitor_updated is called on the next-hop channel
581 /// with the latest update_id.
582 PartialFailure(Vec<Result<(), APIError>>),
585 macro_rules! handle_error {
586 ($self: ident, $internal: expr, $counterparty_node_id: expr) => {
589 Err(MsgHandleErrInternal { err, shutdown_finish }) => {
590 #[cfg(debug_assertions)]
592 // In testing, ensure there are no deadlocks where the lock is already held upon
593 // entering the macro.
594 assert!($self.channel_state.try_lock().is_ok());
597 let mut msg_events = Vec::with_capacity(2);
599 if let Some((shutdown_res, update_option)) = shutdown_finish {
600 $self.finish_force_close_channel(shutdown_res);
601 if let Some(update) = update_option {
602 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
608 log_error!($self.logger, "{}", err.err);
609 if let msgs::ErrorAction::IgnoreError = err.action {
611 msg_events.push(events::MessageSendEvent::HandleError {
612 node_id: $counterparty_node_id,
613 action: err.action.clone()
617 if !msg_events.is_empty() {
618 $self.channel_state.lock().unwrap().pending_msg_events.append(&mut msg_events);
621 // Return error in case higher-API need one
628 macro_rules! break_chan_entry {
629 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
632 Err(ChannelError::Ignore(msg)) => {
633 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
635 Err(ChannelError::Close(msg)) => {
636 log_trace!($self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
637 let (channel_id, mut chan) = $entry.remove_entry();
638 if let Some(short_id) = chan.get_short_channel_id() {
639 $channel_state.short_to_id.remove(&short_id);
641 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()))
643 Err(ChannelError::CloseDelayBroadcast(_)) => { panic!("Wait is only generated on receipt of channel_reestablish, which is handled by try_chan_entry, we don't bother to support it here"); }
648 macro_rules! try_chan_entry {
649 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
652 Err(ChannelError::Ignore(msg)) => {
653 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
655 Err(ChannelError::Close(msg)) => {
656 log_trace!($self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
657 let (channel_id, mut chan) = $entry.remove_entry();
658 if let Some(short_id) = chan.get_short_channel_id() {
659 $channel_state.short_to_id.remove(&short_id);
661 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()))
663 Err(ChannelError::CloseDelayBroadcast(msg)) => {
664 log_error!($self.logger, "Channel {} need to be shutdown but closing transactions not broadcast due to {}", log_bytes!($entry.key()[..]), msg);
665 let (channel_id, mut chan) = $entry.remove_entry();
666 if let Some(short_id) = chan.get_short_channel_id() {
667 $channel_state.short_to_id.remove(&short_id);
669 let shutdown_res = chan.force_shutdown(false);
670 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, shutdown_res, $self.get_channel_update(&chan).ok()))
676 macro_rules! handle_monitor_err {
677 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
678 handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, Vec::new(), Vec::new())
680 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
682 ChannelMonitorUpdateErr::PermanentFailure => {
683 log_error!($self.logger, "Closing channel {} due to monitor update PermanentFailure", log_bytes!($entry.key()[..]));
684 let (channel_id, mut chan) = $entry.remove_entry();
685 if let Some(short_id) = chan.get_short_channel_id() {
686 $channel_state.short_to_id.remove(&short_id);
688 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
689 // chain in a confused state! We need to move them into the ChannelMonitor which
690 // will be responsible for failing backwards once things confirm on-chain.
691 // It's ok that we drop $failed_forwards here - at this point we'd rather they
692 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
693 // us bother trying to claim it just to forward on to another peer. If we're
694 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
695 // given up the preimage yet, so might as well just wait until the payment is
696 // retried, avoiding the on-chain fees.
697 let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure".to_owned(), channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()));
700 ChannelMonitorUpdateErr::TemporaryFailure => {
701 log_info!($self.logger, "Disabling channel {} due to monitor update TemporaryFailure. On restore will send {} and process {} forwards and {} fails",
702 log_bytes!($entry.key()[..]),
703 if $resend_commitment && $resend_raa {
705 RAACommitmentOrder::CommitmentFirst => { "commitment then RAA" },
706 RAACommitmentOrder::RevokeAndACKFirst => { "RAA then commitment" },
708 } else if $resend_commitment { "commitment" }
709 else if $resend_raa { "RAA" }
711 (&$failed_forwards as &Vec<(PendingHTLCInfo, u64)>).len(),
712 (&$failed_fails as &Vec<(HTLCSource, PaymentHash, HTLCFailReason)>).len());
713 if !$resend_commitment {
714 debug_assert!($action_type == RAACommitmentOrder::RevokeAndACKFirst || !$resend_raa);
717 debug_assert!($action_type == RAACommitmentOrder::CommitmentFirst || !$resend_commitment);
719 $entry.get_mut().monitor_update_failed($resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
720 Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor".to_owned()), *$entry.key()))
726 macro_rules! return_monitor_err {
727 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
728 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment);
730 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
731 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
735 // Does not break in case of TemporaryFailure!
736 macro_rules! maybe_break_monitor_err {
737 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
738 match (handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment), $err) {
739 (e, ChannelMonitorUpdateErr::PermanentFailure) => {
742 (_, ChannelMonitorUpdateErr::TemporaryFailure) => { },
747 macro_rules! handle_chan_restoration_locked {
748 ($self: ident, $channel_lock: expr, $channel_state: expr, $channel_entry: expr,
749 $raa: expr, $commitment_update: expr, $order: expr, $chanmon_update: expr,
750 $pending_forwards: expr, $broadcast_safe: expr, $funding_locked: expr) => { {
751 let mut htlc_forwards = None;
752 let mut funding_broadcast_safe = None;
753 let counterparty_node_id = $channel_entry.get().get_counterparty_node_id();
754 let channel_id = $channel_entry.get().channel_id();
757 let forwards: Vec<(PendingHTLCInfo, u64)> = $pending_forwards; // Force type-checking to resolve
758 if !forwards.is_empty() {
759 htlc_forwards = Some(($channel_entry.get().get_short_channel_id().expect("We can't have pending forwards before funding confirmation"),
760 $channel_entry.get().get_funding_txo().unwrap(), forwards));
762 if $chanmon_update.is_some() {
763 assert!($commitment_update.is_some());
764 assert!($funding_locked.is_none());
767 if let Some(msg) = $funding_locked {
768 $channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
769 node_id: counterparty_node_id,
772 if let Some(announcement_sigs) = $self.get_announcement_sigs($channel_entry.get()) {
773 $channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
774 node_id: counterparty_node_id,
775 msg: announcement_sigs,
778 $channel_state.short_to_id.insert($channel_entry.get().get_short_channel_id().unwrap(), channel_id);
781 macro_rules! handle_cs { () => {
782 if let Some(monitor_update) = $chanmon_update {
783 assert!($order == RAACommitmentOrder::RevokeAndACKFirst);
784 assert!(!$broadcast_safe);
785 assert!($commitment_update.is_some());
786 if let Err(e) = $self.chain_monitor.update_channel($channel_entry.get().get_funding_txo().unwrap(), monitor_update) {
787 break handle_monitor_err!($self, e, $channel_state, $channel_entry, RAACommitmentOrder::CommitmentFirst, false, true);
790 if let Some(update) = $commitment_update {
791 $channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
792 node_id: counterparty_node_id,
797 macro_rules! handle_raa { () => {
798 if let Some(revoke_and_ack) = $raa {
799 $channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
800 node_id: counterparty_node_id,
806 RAACommitmentOrder::CommitmentFirst => {
810 RAACommitmentOrder::RevokeAndACKFirst => {
816 funding_broadcast_safe = Some(events::Event::FundingBroadcastSafe {
817 funding_txo: $channel_entry.get().get_funding_txo().unwrap(),
818 user_channel_id: $channel_entry.get().get_user_id(),
824 (htlc_forwards, funding_broadcast_safe, res, channel_id, counterparty_node_id)
828 macro_rules! post_handle_chan_restoration {
829 ($self: ident, $locked_res: expr, $pending_failures: expr, $forwarding_failures: expr) => { {
830 let (htlc_forwards, funding_broadcast_safe, res, channel_id, counterparty_node_id) = $locked_res;
832 let _ = handle_error!($self, res, counterparty_node_id);
834 if let Some(ev) = funding_broadcast_safe {
835 $self.pending_events.lock().unwrap().push(ev);
838 let forwarding_failures: Vec<(HTLCSource, PaymentHash)> = $forwarding_failures; // Force type-checking to resolve
839 $self.fail_holding_cell_htlcs(forwarding_failures, channel_id);
841 let mut pending_failures: Vec<(HTLCSource, PaymentHash, HTLCFailReason)> = $pending_failures; // Force type-checking to resolve
842 for failure in pending_failures.drain(..) {
843 $self.fail_htlc_backwards_internal($self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
845 if let Some(forwards) = htlc_forwards {
846 $self.forward_htlcs(&mut [forwards][..]);
851 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
852 where M::Target: chain::Watch<Signer>,
853 T::Target: BroadcasterInterface,
854 K::Target: KeysInterface<Signer = Signer>,
855 F::Target: FeeEstimator,
858 /// Constructs a new ChannelManager to hold several channels and route between them.
860 /// This is the main "logic hub" for all channel-related actions, and implements
861 /// ChannelMessageHandler.
863 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
865 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
867 /// Users must provide the current blockchain height from which to track onchain channel
868 /// funding outpoints and send payments with reliable timelocks.
870 /// Users need to notify the new ChannelManager when a new block is connected or
871 /// disconnected using its `block_connected` and `block_disconnected` methods.
872 pub fn new(network: Network, fee_est: F, chain_monitor: M, tx_broadcaster: T, logger: L, keys_manager: K, config: UserConfig, current_blockchain_height: usize) -> Self {
873 let mut secp_ctx = Secp256k1::new();
874 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
877 default_configuration: config.clone(),
878 genesis_hash: genesis_block(network).header.block_hash(),
879 fee_estimator: fee_est,
883 latest_block_height: AtomicUsize::new(current_blockchain_height),
884 last_block_hash: Mutex::new(Default::default()),
887 channel_state: Mutex::new(ChannelHolder{
888 by_id: HashMap::new(),
889 short_to_id: HashMap::new(),
890 forward_htlcs: HashMap::new(),
891 claimable_htlcs: HashMap::new(),
892 pending_msg_events: Vec::new(),
894 our_network_key: keys_manager.get_node_secret(),
896 last_node_announcement_serial: AtomicUsize::new(0),
898 per_peer_state: RwLock::new(HashMap::new()),
900 pending_events: Mutex::new(Vec::new()),
901 total_consistency_lock: RwLock::new(()),
902 persistence_notifier: PersistenceNotifier::new(),
910 /// Creates a new outbound channel to the given remote node and with the given value.
912 /// user_id will be provided back as user_channel_id in FundingGenerationReady and
913 /// FundingBroadcastSafe events to allow tracking of which events correspond with which
914 /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
915 /// may wish to avoid using 0 for user_id here.
917 /// If successful, will generate a SendOpenChannel message event, so you should probably poll
918 /// PeerManager::process_events afterwards.
920 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
921 /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
922 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> {
923 if channel_value_satoshis < 1000 {
924 return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
927 let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
928 let channel = Channel::new_outbound(&self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, config)?;
929 let res = channel.get_open_channel(self.genesis_hash.clone());
931 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
932 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
933 debug_assert!(&self.total_consistency_lock.try_write().is_err());
935 let mut channel_state = self.channel_state.lock().unwrap();
936 match channel_state.by_id.entry(channel.channel_id()) {
937 hash_map::Entry::Occupied(_) => {
938 if cfg!(feature = "fuzztarget") {
939 return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
941 panic!("RNG is bad???");
944 hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
946 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
947 node_id: their_network_key,
953 fn list_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<Signer>)) -> bool>(&self, f: Fn) -> Vec<ChannelDetails> {
954 let mut res = Vec::new();
956 let channel_state = self.channel_state.lock().unwrap();
957 res.reserve(channel_state.by_id.len());
958 for (channel_id, channel) in channel_state.by_id.iter().filter(f) {
959 let (inbound_capacity_msat, outbound_capacity_msat) = channel.get_inbound_outbound_available_balance_msat();
960 res.push(ChannelDetails {
961 channel_id: (*channel_id).clone(),
962 short_channel_id: channel.get_short_channel_id(),
963 remote_network_id: channel.get_counterparty_node_id(),
964 counterparty_features: InitFeatures::empty(),
965 channel_value_satoshis: channel.get_value_satoshis(),
966 inbound_capacity_msat,
967 outbound_capacity_msat,
968 user_id: channel.get_user_id(),
969 is_live: channel.is_live(),
973 let per_peer_state = self.per_peer_state.read().unwrap();
974 for chan in res.iter_mut() {
975 if let Some(peer_state) = per_peer_state.get(&chan.remote_network_id) {
976 chan.counterparty_features = peer_state.lock().unwrap().latest_features.clone();
982 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
983 /// more information.
984 pub fn list_channels(&self) -> Vec<ChannelDetails> {
985 self.list_channels_with_filter(|_| true)
988 /// Gets the list of usable channels, in random order. Useful as an argument to
989 /// get_route to ensure non-announced channels are used.
991 /// These are guaranteed to have their is_live value set to true, see the documentation for
992 /// ChannelDetails::is_live for more info on exactly what the criteria are.
993 pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
994 // Note we use is_live here instead of usable which leads to somewhat confused
995 // internal/external nomenclature, but that's ok cause that's probably what the user
996 // really wanted anyway.
997 self.list_channels_with_filter(|&(_, ref channel)| channel.is_live())
1000 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
1001 /// will be accepted on the given channel, and after additional timeout/the closing of all
1002 /// pending HTLCs, the channel will be closed on chain.
1004 /// May generate a SendShutdown message event on success, which should be relayed.
1005 pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
1006 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1008 let (mut failed_htlcs, chan_option) = {
1009 let mut channel_state_lock = self.channel_state.lock().unwrap();
1010 let channel_state = &mut *channel_state_lock;
1011 match channel_state.by_id.entry(channel_id.clone()) {
1012 hash_map::Entry::Occupied(mut chan_entry) => {
1013 let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
1014 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1015 node_id: chan_entry.get().get_counterparty_node_id(),
1018 if chan_entry.get().is_shutdown() {
1019 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1020 channel_state.short_to_id.remove(&short_id);
1022 (failed_htlcs, Some(chan_entry.remove_entry().1))
1023 } else { (failed_htlcs, None) }
1025 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()})
1028 for htlc_source in failed_htlcs.drain(..) {
1029 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() });
1031 let chan_update = if let Some(chan) = chan_option {
1032 if let Ok(update) = self.get_channel_update(&chan) {
1037 if let Some(update) = chan_update {
1038 let mut channel_state = self.channel_state.lock().unwrap();
1039 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1048 fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
1049 let (funding_txo_option, monitor_update, mut failed_htlcs) = shutdown_res;
1050 log_trace!(self.logger, "Finishing force-closure of channel {} HTLCs to fail", failed_htlcs.len());
1051 for htlc_source in failed_htlcs.drain(..) {
1052 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() });
1054 if let Some(funding_txo) = funding_txo_option {
1055 // There isn't anything we can do if we get an update failure - we're already
1056 // force-closing. The monitor update on the required in-memory copy should broadcast
1057 // the latest local state, which is the best we can do anyway. Thus, it is safe to
1058 // ignore the result here.
1059 let _ = self.chain_monitor.update_channel(funding_txo, monitor_update);
1063 fn force_close_channel_with_peer(&self, channel_id: &[u8; 32], peer_node_id: Option<&PublicKey>) -> Result<(), APIError> {
1065 let mut channel_state_lock = self.channel_state.lock().unwrap();
1066 let channel_state = &mut *channel_state_lock;
1067 if let hash_map::Entry::Occupied(chan) = channel_state.by_id.entry(channel_id.clone()) {
1068 if let Some(node_id) = peer_node_id {
1069 if chan.get().get_counterparty_node_id() != *node_id {
1070 // Error or Ok here doesn't matter - the result is only exposed publicly
1071 // when peer_node_id is None anyway.
1075 if let Some(short_id) = chan.get().get_short_channel_id() {
1076 channel_state.short_to_id.remove(&short_id);
1078 chan.remove_entry().1
1080 return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()});
1083 log_trace!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
1084 self.finish_force_close_channel(chan.force_shutdown(true));
1085 if let Ok(update) = self.get_channel_update(&chan) {
1086 let mut channel_state = self.channel_state.lock().unwrap();
1087 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1095 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
1096 /// the chain and rejecting new HTLCs on the given channel. Fails if channel_id is unknown to the manager.
1097 pub fn force_close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
1098 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1099 self.force_close_channel_with_peer(channel_id, None)
1102 /// Force close all channels, immediately broadcasting the latest local commitment transaction
1103 /// for each to the chain and rejecting new HTLCs on each.
1104 pub fn force_close_all_channels(&self) {
1105 for chan in self.list_channels() {
1106 let _ = self.force_close_channel(&chan.channel_id);
1110 fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder<Signer>>) {
1111 macro_rules! return_malformed_err {
1112 ($msg: expr, $err_code: expr) => {
1114 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
1115 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
1116 channel_id: msg.channel_id,
1117 htlc_id: msg.htlc_id,
1118 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
1119 failure_code: $err_code,
1120 })), self.channel_state.lock().unwrap());
1125 if let Err(_) = msg.onion_routing_packet.public_key {
1126 return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
1129 let shared_secret = {
1130 let mut arr = [0; 32];
1131 arr.copy_from_slice(&SharedSecret::new(&msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
1134 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(&shared_secret);
1136 if msg.onion_routing_packet.version != 0 {
1137 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1138 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1139 //the hash doesn't really serve any purpose - in the case of hashing all data, the
1140 //receiving node would have to brute force to figure out which version was put in the
1141 //packet by the node that send us the message, in the case of hashing the hop_data, the
1142 //node knows the HMAC matched, so they already know what is there...
1143 return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
1146 let mut hmac = HmacEngine::<Sha256>::new(&mu);
1147 hmac.input(&msg.onion_routing_packet.hop_data);
1148 hmac.input(&msg.payment_hash.0[..]);
1149 if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
1150 return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
1153 let mut channel_state = None;
1154 macro_rules! return_err {
1155 ($msg: expr, $err_code: expr, $data: expr) => {
1157 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
1158 if channel_state.is_none() {
1159 channel_state = Some(self.channel_state.lock().unwrap());
1161 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1162 channel_id: msg.channel_id,
1163 htlc_id: msg.htlc_id,
1164 reason: onion_utils::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1165 })), channel_state.unwrap());
1170 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1171 let mut chacha_stream = ChaChaReader { chacha: &mut chacha, read: Cursor::new(&msg.onion_routing_packet.hop_data[..]) };
1172 let (next_hop_data, next_hop_hmac) = {
1173 match msgs::OnionHopData::read(&mut chacha_stream) {
1175 let error_code = match err {
1176 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1177 msgs::DecodeError::UnknownRequiredFeature|
1178 msgs::DecodeError::InvalidValue|
1179 msgs::DecodeError::ShortRead => 0x4000 | 22, // invalid_onion_payload
1180 _ => 0x2000 | 2, // Should never happen
1182 return_err!("Unable to decode our hop data", error_code, &[0;0]);
1185 let mut hmac = [0; 32];
1186 if let Err(_) = chacha_stream.read_exact(&mut hmac[..]) {
1187 return_err!("Unable to decode hop data", 0x4000 | 22, &[0;0]);
1194 let pending_forward_info = if next_hop_hmac == [0; 32] {
1197 // In tests, make sure that the initial onion pcket data is, at least, non-0.
1198 // We could do some fancy randomness test here, but, ehh, whatever.
1199 // This checks for the issue where you can calculate the path length given the
1200 // onion data as all the path entries that the originator sent will be here
1201 // as-is (and were originally 0s).
1202 // Of course reverse path calculation is still pretty easy given naive routing
1203 // algorithms, but this fixes the most-obvious case.
1204 let mut next_bytes = [0; 32];
1205 chacha_stream.read_exact(&mut next_bytes).unwrap();
1206 assert_ne!(next_bytes[..], [0; 32][..]);
1207 chacha_stream.read_exact(&mut next_bytes).unwrap();
1208 assert_ne!(next_bytes[..], [0; 32][..]);
1212 // final_expiry_too_soon
1213 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure we have at least
1214 // HTLC_FAIL_BACK_BUFFER blocks to go.
1215 // Also, ensure that, in the case of an unknown payment hash, our payment logic has enough time to fail the HTLC backward
1216 // before our onchain logic triggers a channel closure (see HTLC_FAIL_BACK_BUFFER rational).
1217 if (msg.cltv_expiry as u64) <= self.latest_block_height.load(Ordering::Acquire) as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1 {
1218 return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1220 // final_incorrect_htlc_amount
1221 if next_hop_data.amt_to_forward > msg.amount_msat {
1222 return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1224 // final_incorrect_cltv_expiry
1225 if next_hop_data.outgoing_cltv_value != msg.cltv_expiry {
1226 return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1229 let payment_data = match next_hop_data.format {
1230 msgs::OnionHopDataFormat::Legacy { .. } => None,
1231 msgs::OnionHopDataFormat::NonFinalNode { .. } => return_err!("Got non final data with an HMAC of 0", 0x4000 | 22, &[0;0]),
1232 msgs::OnionHopDataFormat::FinalNode { payment_data } => payment_data,
1235 // Note that we could obviously respond immediately with an update_fulfill_htlc
1236 // message, however that would leak that we are the recipient of this payment, so
1237 // instead we stay symmetric with the forwarding case, only responding (after a
1238 // delay) once they've send us a commitment_signed!
1240 PendingHTLCStatus::Forward(PendingHTLCInfo {
1241 routing: PendingHTLCRouting::Receive {
1243 incoming_cltv_expiry: msg.cltv_expiry,
1245 payment_hash: msg.payment_hash.clone(),
1246 incoming_shared_secret: shared_secret,
1247 amt_to_forward: next_hop_data.amt_to_forward,
1248 outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1251 let mut new_packet_data = [0; 20*65];
1252 let read_pos = chacha_stream.read(&mut new_packet_data).unwrap();
1253 #[cfg(debug_assertions)]
1255 // Check two things:
1256 // a) that the behavior of our stream here will return Ok(0) even if the TLV
1257 // read above emptied out our buffer and the unwrap() wont needlessly panic
1258 // b) that we didn't somehow magically end up with extra data.
1260 debug_assert!(chacha_stream.read(&mut t).unwrap() == 0);
1262 // Once we've emptied the set of bytes our peer gave us, encrypt 0 bytes until we
1263 // fill the onion hop data we'll forward to our next-hop peer.
1264 chacha_stream.chacha.process_in_place(&mut new_packet_data[read_pos..]);
1266 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1268 let blinding_factor = {
1269 let mut sha = Sha256::engine();
1270 sha.input(&new_pubkey.serialize()[..]);
1271 sha.input(&shared_secret);
1272 Sha256::from_engine(sha).into_inner()
1275 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor[..]) {
1277 } else { Ok(new_pubkey) };
1279 let outgoing_packet = msgs::OnionPacket {
1282 hop_data: new_packet_data,
1283 hmac: next_hop_hmac.clone(),
1286 let short_channel_id = match next_hop_data.format {
1287 msgs::OnionHopDataFormat::Legacy { short_channel_id } => short_channel_id,
1288 msgs::OnionHopDataFormat::NonFinalNode { short_channel_id } => short_channel_id,
1289 msgs::OnionHopDataFormat::FinalNode { .. } => {
1290 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0;0]);
1294 PendingHTLCStatus::Forward(PendingHTLCInfo {
1295 routing: PendingHTLCRouting::Forward {
1296 onion_packet: outgoing_packet,
1299 payment_hash: msg.payment_hash.clone(),
1300 incoming_shared_secret: shared_secret,
1301 amt_to_forward: next_hop_data.amt_to_forward,
1302 outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1306 channel_state = Some(self.channel_state.lock().unwrap());
1307 if let &PendingHTLCStatus::Forward(PendingHTLCInfo { ref routing, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1308 // If short_channel_id is 0 here, we'll reject the HTLC as there cannot be a channel
1309 // with a short_channel_id of 0. This is important as various things later assume
1310 // short_channel_id is non-0 in any ::Forward.
1311 if let &PendingHTLCRouting::Forward { ref short_channel_id, .. } = routing {
1312 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1313 let forwarding_id = match id_option {
1314 None => { // unknown_next_peer
1315 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1317 Some(id) => id.clone(),
1319 if let Some((err, code, chan_update)) = loop {
1320 let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1322 // Note that we could technically not return an error yet here and just hope
1323 // that the connection is reestablished or monitor updated by the time we get
1324 // around to doing the actual forward, but better to fail early if we can and
1325 // hopefully an attacker trying to path-trace payments cannot make this occur
1326 // on a small/per-node/per-channel scale.
1327 if !chan.is_live() { // channel_disabled
1328 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1330 if *amt_to_forward < chan.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
1331 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1333 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) });
1334 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1335 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())));
1337 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1338 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())));
1340 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1341 // Theoretically, channel counterparty shouldn't send us a HTLC expiring now, but we want to be robust wrt to counterparty
1342 // packet sanitization (see HTLC_FAIL_BACK_BUFFER rational)
1343 if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
1344 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1346 if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1347 break Some(("CLTV expiry is too far in the future", 21, None));
1349 // In theory, we would be safe against unitentional channel-closure, if we only required a margin of LATENCY_GRACE_PERIOD_BLOCKS.
1350 // But, to be safe against policy reception, we use a longuer delay.
1351 if (*outgoing_cltv_value) as u64 <= (cur_height + HTLC_FAIL_BACK_BUFFER) as u64 {
1352 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1358 let mut res = Vec::with_capacity(8 + 128);
1359 if let Some(chan_update) = chan_update {
1360 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1361 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1363 else if code == 0x1000 | 13 {
1364 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1366 else if code == 0x1000 | 20 {
1367 // TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
1368 res.extend_from_slice(&byte_utils::be16_to_array(0));
1370 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1372 return_err!(err, code, &res[..]);
1377 (pending_forward_info, channel_state.unwrap())
1380 /// only fails if the channel does not yet have an assigned short_id
1381 /// May be called with channel_state already locked!
1382 fn get_channel_update(&self, chan: &Channel<Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
1383 let short_channel_id = match chan.get_short_channel_id() {
1384 None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
1388 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_counterparty_node_id().serialize()[..];
1390 let unsigned = msgs::UnsignedChannelUpdate {
1391 chain_hash: self.genesis_hash,
1393 timestamp: chan.get_update_time_counter(),
1394 flags: (!were_node_one) as u8 | ((!chan.is_live() as u8) << 1),
1395 cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1396 htlc_minimum_msat: chan.get_counterparty_htlc_minimum_msat(),
1397 htlc_maximum_msat: OptionalField::Present(chan.get_announced_htlc_max_msat()),
1398 fee_base_msat: chan.get_holder_fee_base_msat(&self.fee_estimator),
1399 fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1400 excess_data: Vec::new(),
1403 let msg_hash = Sha256dHash::hash(&unsigned.encode()[..]);
1404 let sig = self.secp_ctx.sign(&hash_to_message!(&msg_hash[..]), &self.our_network_key);
1406 Ok(msgs::ChannelUpdate {
1412 // Only public for testing, this should otherwise never be called direcly
1413 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> {
1414 log_trace!(self.logger, "Attempting to send payment for path with next hop {}", path.first().unwrap().short_channel_id);
1415 let prng_seed = self.keys_manager.get_secure_random_bytes();
1416 let session_priv = SecretKey::from_slice(&self.keys_manager.get_secure_random_bytes()[..]).expect("RNG is busted");
1418 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
1419 .map_err(|_| APIError::RouteError{err: "Pubkey along hop was maliciously selected"})?;
1420 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, payment_secret, cur_height)?;
1421 if onion_utils::route_size_insane(&onion_payloads) {
1422 return Err(APIError::RouteError{err: "Route size too large considering onion data"});
1424 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash);
1426 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1428 let err: Result<(), _> = loop {
1429 let mut channel_lock = self.channel_state.lock().unwrap();
1430 let id = match channel_lock.short_to_id.get(&path.first().unwrap().short_channel_id) {
1431 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
1432 Some(id) => id.clone(),
1435 let channel_state = &mut *channel_lock;
1436 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1438 if chan.get().get_counterparty_node_id() != path.first().unwrap().pubkey {
1439 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1441 if !chan.get().is_live() {
1442 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!".to_owned()});
1444 break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1446 session_priv: session_priv.clone(),
1447 first_hop_htlc_msat: htlc_msat,
1448 }, onion_packet, &self.logger), channel_state, chan)
1450 Some((update_add, commitment_signed, monitor_update)) => {
1451 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
1452 maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true);
1453 // Note that MonitorUpdateFailed here indicates (per function docs)
1454 // that we will resend the commitment update once monitor updating
1455 // is restored. Therefore, we must return an error indicating that
1456 // it is unsafe to retry the payment wholesale, which we do in the
1457 // send_payment check for MonitorUpdateFailed, below.
1458 return Err(APIError::MonitorUpdateFailed);
1461 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1462 node_id: path.first().unwrap().pubkey,
1463 updates: msgs::CommitmentUpdate {
1464 update_add_htlcs: vec![update_add],
1465 update_fulfill_htlcs: Vec::new(),
1466 update_fail_htlcs: Vec::new(),
1467 update_fail_malformed_htlcs: Vec::new(),
1475 } else { unreachable!(); }
1479 match handle_error!(self, err, path.first().unwrap().pubkey) {
1480 Ok(_) => unreachable!(),
1482 Err(APIError::ChannelUnavailable { err: e.err })
1487 /// Sends a payment along a given route.
1489 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1490 /// fields for more info.
1492 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1493 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1494 /// next hop knows the preimage to payment_hash they can claim an additional amount as
1495 /// specified in the last hop in the route! Thus, you should probably do your own
1496 /// payment_preimage tracking (which you should already be doing as they represent "proof of
1497 /// payment") and prevent double-sends yourself.
1499 /// May generate SendHTLCs message(s) event on success, which should be relayed.
1501 /// Each path may have a different return value, and PaymentSendValue may return a Vec with
1502 /// each entry matching the corresponding-index entry in the route paths, see
1503 /// PaymentSendFailure for more info.
1505 /// In general, a path may raise:
1506 /// * APIError::RouteError when an invalid route or forwarding parameter (cltv_delta, fee,
1507 /// node public key) is specified.
1508 /// * APIError::ChannelUnavailable if the next-hop channel is not available for updates
1509 /// (including due to previous monitor update failure or new permanent monitor update
1511 /// * APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1512 /// relevant updates.
1514 /// Note that depending on the type of the PaymentSendFailure the HTLC may have been
1515 /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
1516 /// different route unless you intend to pay twice!
1518 /// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
1519 /// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
1520 /// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
1521 /// must not contain multiple paths as multi-path payments require a recipient-provided
1523 /// If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
1524 /// bit set (either as required or as available). If multiple paths are present in the Route,
1525 /// we assume the invoice had the basic_mpp feature set.
1526 pub fn send_payment(&self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>) -> Result<(), PaymentSendFailure> {
1527 if route.paths.len() < 1 {
1528 return Err(PaymentSendFailure::ParameterError(APIError::RouteError{err: "There must be at least one path to send over"}));
1530 if route.paths.len() > 10 {
1531 // This limit is completely arbitrary - there aren't any real fundamental path-count
1532 // limits. After we support retrying individual paths we should likely bump this, but
1533 // for now more than 10 paths likely carries too much one-path failure.
1534 return Err(PaymentSendFailure::ParameterError(APIError::RouteError{err: "Sending over more than 10 paths is not currently supported"}));
1536 let mut total_value = 0;
1537 let our_node_id = self.get_our_node_id();
1538 let mut path_errs = Vec::with_capacity(route.paths.len());
1539 'path_check: for path in route.paths.iter() {
1540 if path.len() < 1 || path.len() > 20 {
1541 path_errs.push(Err(APIError::RouteError{err: "Path didn't go anywhere/had bogus size"}));
1542 continue 'path_check;
1544 for (idx, hop) in path.iter().enumerate() {
1545 if idx != path.len() - 1 && hop.pubkey == our_node_id {
1546 path_errs.push(Err(APIError::RouteError{err: "Path went through us but wasn't a simple rebalance loop to us"}));
1547 continue 'path_check;
1550 total_value += path.last().unwrap().fee_msat;
1551 path_errs.push(Ok(()));
1553 if path_errs.iter().any(|e| e.is_err()) {
1554 return Err(PaymentSendFailure::PathParameterError(path_errs));
1557 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1558 let mut results = Vec::new();
1559 for path in route.paths.iter() {
1560 results.push(self.send_payment_along_path(&path, &payment_hash, payment_secret, total_value, cur_height));
1562 let mut has_ok = false;
1563 let mut has_err = false;
1564 for res in results.iter() {
1565 if res.is_ok() { has_ok = true; }
1566 if res.is_err() { has_err = true; }
1567 if let &Err(APIError::MonitorUpdateFailed) = res {
1568 // MonitorUpdateFailed is inherently unsafe to retry, so we call it a
1575 if has_err && has_ok {
1576 Err(PaymentSendFailure::PartialFailure(results))
1578 Err(PaymentSendFailure::AllFailedRetrySafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1584 /// Call this upon creation of a funding transaction for the given channel.
1586 /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1587 /// or your counterparty can steal your funds!
1589 /// Panics if a funding transaction has already been provided for this channel.
1591 /// May panic if the funding_txo is duplicative with some other channel (note that this should
1592 /// be trivially prevented by using unique funding transaction keys per-channel).
1593 pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1594 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1597 let (res, chan) = match self.channel_state.lock().unwrap().by_id.remove(temporary_channel_id) {
1599 (chan.get_outbound_funding_created(funding_txo, &self.logger)
1600 .map_err(|e| if let ChannelError::Close(msg) = e {
1601 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(true), None)
1602 } else { unreachable!(); })
1607 match handle_error!(self, res, chan.get_counterparty_node_id()) {
1608 Ok(funding_msg) => {
1611 Err(_) => { return; }
1615 let mut channel_state = self.channel_state.lock().unwrap();
1616 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1617 node_id: chan.get_counterparty_node_id(),
1620 match channel_state.by_id.entry(chan.channel_id()) {
1621 hash_map::Entry::Occupied(_) => {
1622 panic!("Generated duplicate funding txid?");
1624 hash_map::Entry::Vacant(e) => {
1630 fn get_announcement_sigs(&self, chan: &Channel<Signer>) -> Option<msgs::AnnouncementSignatures> {
1631 if !chan.should_announce() {
1632 log_trace!(self.logger, "Can't send announcement_signatures for private channel {}", log_bytes!(chan.channel_id()));
1636 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1638 Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1640 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1641 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1643 Some(msgs::AnnouncementSignatures {
1644 channel_id: chan.channel_id(),
1645 short_channel_id: chan.get_short_channel_id().unwrap(),
1646 node_signature: our_node_sig,
1647 bitcoin_signature: our_bitcoin_sig,
1652 // Messages of up to 64KB should never end up more than half full with addresses, as that would
1653 // be absurd. We ensure this by checking that at least 500 (our stated public contract on when
1654 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
1656 const HALF_MESSAGE_IS_ADDRS: u32 = ::std::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
1659 // ...by failing to compile if the number of addresses that would be half of a message is
1660 // smaller than 500:
1661 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 500;
1663 /// Generates a signed node_announcement from the given arguments and creates a
1664 /// BroadcastNodeAnnouncement event. Note that such messages will be ignored unless peers have
1665 /// seen a channel_announcement from us (ie unless we have public channels open).
1667 /// RGB is a node "color" and alias is a printable human-readable string to describe this node
1668 /// to humans. They carry no in-protocol meaning.
1670 /// addresses represent the set (possibly empty) of socket addresses on which this node accepts
1671 /// incoming connections. These will be broadcast to the network, publicly tying these
1672 /// addresses together. If you wish to preserve user privacy, addresses should likely contain
1673 /// only Tor Onion addresses.
1675 /// Panics if addresses is absurdly large (more than 500).
1676 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: Vec<NetAddress>) {
1677 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1679 if addresses.len() > 500 {
1680 panic!("More than half the message size was taken up by public addresses!");
1683 let announcement = msgs::UnsignedNodeAnnouncement {
1684 features: NodeFeatures::known(),
1685 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1686 node_id: self.get_our_node_id(),
1687 rgb, alias, addresses,
1688 excess_address_data: Vec::new(),
1689 excess_data: Vec::new(),
1691 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1693 let mut channel_state = self.channel_state.lock().unwrap();
1694 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
1695 msg: msgs::NodeAnnouncement {
1696 signature: self.secp_ctx.sign(&msghash, &self.our_network_key),
1697 contents: announcement
1702 /// Processes HTLCs which are pending waiting on random forward delay.
1704 /// Should only really ever be called in response to a PendingHTLCsForwardable event.
1705 /// Will likely generate further events.
1706 pub fn process_pending_htlc_forwards(&self) {
1707 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1709 let mut new_events = Vec::new();
1710 let mut failed_forwards = Vec::new();
1711 let mut handle_errors = Vec::new();
1713 let mut channel_state_lock = self.channel_state.lock().unwrap();
1714 let channel_state = &mut *channel_state_lock;
1716 for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1717 if short_chan_id != 0 {
1718 let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1719 Some(chan_id) => chan_id.clone(),
1721 failed_forwards.reserve(pending_forwards.len());
1722 for forward_info in pending_forwards.drain(..) {
1723 match forward_info {
1724 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info,
1725 prev_funding_outpoint } => {
1726 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1727 short_channel_id: prev_short_channel_id,
1728 outpoint: prev_funding_outpoint,
1729 htlc_id: prev_htlc_id,
1730 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1732 failed_forwards.push((htlc_source, forward_info.payment_hash,
1733 HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() }
1736 HTLCForwardInfo::FailHTLC { .. } => {
1737 // Channel went away before we could fail it. This implies
1738 // the channel is now on chain and our counterparty is
1739 // trying to broadcast the HTLC-Timeout, but that's their
1740 // problem, not ours.
1747 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(forward_chan_id) {
1748 let mut add_htlc_msgs = Vec::new();
1749 let mut fail_htlc_msgs = Vec::new();
1750 for forward_info in pending_forwards.drain(..) {
1751 match forward_info {
1752 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1753 routing: PendingHTLCRouting::Forward {
1755 }, incoming_shared_secret, payment_hash, amt_to_forward, outgoing_cltv_value },
1756 prev_funding_outpoint } => {
1757 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);
1758 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1759 short_channel_id: prev_short_channel_id,
1760 outpoint: prev_funding_outpoint,
1761 htlc_id: prev_htlc_id,
1762 incoming_packet_shared_secret: incoming_shared_secret,
1764 match chan.get_mut().send_htlc(amt_to_forward, payment_hash, outgoing_cltv_value, htlc_source.clone(), onion_packet) {
1766 if let ChannelError::Ignore(msg) = e {
1767 log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
1769 panic!("Stated return value requirements in send_htlc() were not met");
1771 let chan_update = self.get_channel_update(chan.get()).unwrap();
1772 failed_forwards.push((htlc_source, payment_hash,
1773 HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.encode_with_len() }
1779 Some(msg) => { add_htlc_msgs.push(msg); },
1781 // Nothing to do here...we're waiting on a remote
1782 // revoke_and_ack before we can add anymore HTLCs. The Channel
1783 // will automatically handle building the update_add_htlc and
1784 // commitment_signed messages when we can.
1785 // TODO: Do some kind of timer to set the channel as !is_live()
1786 // as we don't really want others relying on us relaying through
1787 // this channel currently :/.
1793 HTLCForwardInfo::AddHTLC { .. } => {
1794 panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
1796 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
1797 log_trace!(self.logger, "Failing HTLC back to channel with short id {} after delay", short_chan_id);
1798 match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet) {
1800 if let ChannelError::Ignore(msg) = e {
1801 log_trace!(self.logger, "Failed to fail backwards to short_id {}: {}", short_chan_id, msg);
1803 panic!("Stated return value requirements in get_update_fail_htlc() were not met");
1805 // fail-backs are best-effort, we probably already have one
1806 // pending, and if not that's OK, if not, the channel is on
1807 // the chain and sending the HTLC-Timeout is their problem.
1810 Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
1812 // Nothing to do here...we're waiting on a remote
1813 // revoke_and_ack before we can update the commitment
1814 // transaction. The Channel will automatically handle
1815 // building the update_fail_htlc and commitment_signed
1816 // messages when we can.
1817 // We don't need any kind of timer here as they should fail
1818 // the channel onto the chain if they can't get our
1819 // update_fail_htlc in time, it's not our problem.
1826 if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
1827 let (commitment_msg, monitor_update) = match chan.get_mut().send_commitment(&self.logger) {
1830 // We surely failed send_commitment due to bad keys, in that case
1831 // close channel and then send error message to peer.
1832 let counterparty_node_id = chan.get().get_counterparty_node_id();
1833 let err: Result<(), _> = match e {
1834 ChannelError::Ignore(_) => {
1835 panic!("Stated return value requirements in send_commitment() were not met");
1837 ChannelError::Close(msg) => {
1838 log_trace!(self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
1839 let (channel_id, mut channel) = chan.remove_entry();
1840 if let Some(short_id) = channel.get_short_channel_id() {
1841 channel_state.short_to_id.remove(&short_id);
1843 Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, channel.force_shutdown(true), self.get_channel_update(&channel).ok()))
1845 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"); }
1847 handle_errors.push((counterparty_node_id, err));
1851 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
1852 handle_errors.push((chan.get().get_counterparty_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
1855 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1856 node_id: chan.get().get_counterparty_node_id(),
1857 updates: msgs::CommitmentUpdate {
1858 update_add_htlcs: add_htlc_msgs,
1859 update_fulfill_htlcs: Vec::new(),
1860 update_fail_htlcs: fail_htlc_msgs,
1861 update_fail_malformed_htlcs: Vec::new(),
1863 commitment_signed: commitment_msg,
1871 for forward_info in pending_forwards.drain(..) {
1872 match forward_info {
1873 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1874 routing: PendingHTLCRouting::Receive { payment_data, incoming_cltv_expiry },
1875 incoming_shared_secret, payment_hash, amt_to_forward, .. },
1876 prev_funding_outpoint } => {
1877 let prev_hop = HTLCPreviousHopData {
1878 short_channel_id: prev_short_channel_id,
1879 outpoint: prev_funding_outpoint,
1880 htlc_id: prev_htlc_id,
1881 incoming_packet_shared_secret: incoming_shared_secret,
1884 let mut total_value = 0;
1885 let payment_secret_opt =
1886 if let &Some(ref data) = &payment_data { Some(data.payment_secret.clone()) } else { None };
1887 let htlcs = channel_state.claimable_htlcs.entry((payment_hash, payment_secret_opt))
1888 .or_insert(Vec::new());
1889 htlcs.push(ClaimableHTLC {
1891 value: amt_to_forward,
1892 payment_data: payment_data.clone(),
1893 cltv_expiry: incoming_cltv_expiry,
1895 if let &Some(ref data) = &payment_data {
1896 for htlc in htlcs.iter() {
1897 total_value += htlc.value;
1898 if htlc.payment_data.as_ref().unwrap().total_msat != data.total_msat {
1899 total_value = msgs::MAX_VALUE_MSAT;
1901 if total_value >= msgs::MAX_VALUE_MSAT { break; }
1903 if total_value >= msgs::MAX_VALUE_MSAT || total_value > data.total_msat {
1904 for htlc in htlcs.iter() {
1905 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
1906 htlc_msat_height_data.extend_from_slice(
1907 &byte_utils::be32_to_array(
1908 self.latest_block_height.load(Ordering::Acquire)
1912 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
1913 short_channel_id: htlc.prev_hop.short_channel_id,
1914 outpoint: prev_funding_outpoint,
1915 htlc_id: htlc.prev_hop.htlc_id,
1916 incoming_packet_shared_secret: htlc.prev_hop.incoming_packet_shared_secret,
1918 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data }
1921 } else if total_value == data.total_msat {
1922 new_events.push(events::Event::PaymentReceived {
1924 payment_secret: Some(data.payment_secret),
1929 new_events.push(events::Event::PaymentReceived {
1931 payment_secret: None,
1932 amt: amt_to_forward,
1936 HTLCForwardInfo::AddHTLC { .. } => {
1937 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
1939 HTLCForwardInfo::FailHTLC { .. } => {
1940 panic!("Got pending fail of our own HTLC");
1948 for (htlc_source, payment_hash, failure_reason) in failed_forwards.drain(..) {
1949 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, failure_reason);
1952 for (counterparty_node_id, err) in handle_errors.drain(..) {
1953 let _ = handle_error!(self, err, counterparty_node_id);
1956 if new_events.is_empty() { return }
1957 let mut events = self.pending_events.lock().unwrap();
1958 events.append(&mut new_events);
1961 /// If a peer is disconnected we mark any channels with that peer as 'disabled'.
1962 /// After some time, if channels are still disabled we need to broadcast a ChannelUpdate
1963 /// to inform the network about the uselessness of these channels.
1965 /// This method handles all the details, and must be called roughly once per minute.
1966 pub fn timer_chan_freshness_every_min(&self) {
1967 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1968 let mut channel_state_lock = self.channel_state.lock().unwrap();
1969 let channel_state = &mut *channel_state_lock;
1970 for (_, chan) in channel_state.by_id.iter_mut() {
1971 if chan.is_disabled_staged() && !chan.is_live() {
1972 if let Ok(update) = self.get_channel_update(&chan) {
1973 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1978 } else if chan.is_disabled_staged() && chan.is_live() {
1980 } else if chan.is_disabled_marked() {
1981 chan.to_disabled_staged();
1986 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1987 /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
1988 /// along the path (including in our own channel on which we received it).
1989 /// Returns false if no payment was found to fail backwards, true if the process of failing the
1990 /// HTLC backwards has been started.
1991 pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, payment_secret: &Option<PaymentSecret>) -> bool {
1992 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1994 let mut channel_state = Some(self.channel_state.lock().unwrap());
1995 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(*payment_hash, *payment_secret));
1996 if let Some(mut sources) = removed_source {
1997 for htlc in sources.drain(..) {
1998 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1999 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
2000 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
2001 self.latest_block_height.load(Ordering::Acquire) as u32,
2003 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
2004 HTLCSource::PreviousHopData(htlc.prev_hop), payment_hash,
2005 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data });
2011 // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
2012 // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
2013 // be surfaced to the user.
2014 fn fail_holding_cell_htlcs(&self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: [u8; 32]) {
2015 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
2017 HTLCSource::PreviousHopData(HTLCPreviousHopData { .. }) => {
2018 let (failure_code, onion_failure_data) =
2019 match self.channel_state.lock().unwrap().by_id.entry(channel_id) {
2020 hash_map::Entry::Occupied(chan_entry) => {
2021 if let Ok(upd) = self.get_channel_update(&chan_entry.get()) {
2022 (0x1000|7, upd.encode_with_len())
2024 (0x4000|10, Vec::new())
2027 hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
2029 let channel_state = self.channel_state.lock().unwrap();
2030 self.fail_htlc_backwards_internal(channel_state,
2031 htlc_src, &payment_hash, HTLCFailReason::Reason { failure_code, data: onion_failure_data});
2033 HTLCSource::OutboundRoute { .. } => {
2034 self.pending_events.lock().unwrap().push(
2035 events::Event::PaymentFailed {
2037 rejected_by_dest: false,
2049 /// Fails an HTLC backwards to the sender of it to us.
2050 /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
2051 /// There are several callsites that do stupid things like loop over a list of payment_hashes
2052 /// to fail and take the channel_state lock for each iteration (as we take ownership and may
2053 /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
2054 /// still-available channels.
2055 fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
2056 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
2057 //identify whether we sent it or not based on the (I presume) very different runtime
2058 //between the branches here. We should make this async and move it into the forward HTLCs
2061 HTLCSource::OutboundRoute { ref path, .. } => {
2062 log_trace!(self.logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
2063 mem::drop(channel_state_lock);
2064 match &onion_error {
2065 &HTLCFailReason::LightningError { ref err } => {
2067 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());
2069 let (channel_update, payment_retryable, _, _) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
2070 // TODO: If we decided to blame ourselves (or one of our channels) in
2071 // process_onion_failure we should close that channel as it implies our
2072 // next-hop is needlessly blaming us!
2073 if let Some(update) = channel_update {
2074 self.channel_state.lock().unwrap().pending_msg_events.push(
2075 events::MessageSendEvent::PaymentFailureNetworkUpdate {
2080 self.pending_events.lock().unwrap().push(
2081 events::Event::PaymentFailed {
2082 payment_hash: payment_hash.clone(),
2083 rejected_by_dest: !payment_retryable,
2085 error_code: onion_error_code,
2087 error_data: onion_error_data
2091 &HTLCFailReason::Reason {
2097 // we get a fail_malformed_htlc from the first hop
2098 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
2099 // failures here, but that would be insufficient as get_route
2100 // generally ignores its view of our own channels as we provide them via
2102 // TODO: For non-temporary failures, we really should be closing the
2103 // channel here as we apparently can't relay through them anyway.
2104 self.pending_events.lock().unwrap().push(
2105 events::Event::PaymentFailed {
2106 payment_hash: payment_hash.clone(),
2107 rejected_by_dest: path.len() == 1,
2109 error_code: Some(*failure_code),
2111 error_data: Some(data.clone()),
2117 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret, .. }) => {
2118 let err_packet = match onion_error {
2119 HTLCFailReason::Reason { failure_code, data } => {
2120 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
2121 let packet = onion_utils::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
2122 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
2124 HTLCFailReason::LightningError { err } => {
2125 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards with pre-built LightningError", log_bytes!(payment_hash.0));
2126 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
2130 let mut forward_event = None;
2131 if channel_state_lock.forward_htlcs.is_empty() {
2132 forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
2134 match channel_state_lock.forward_htlcs.entry(short_channel_id) {
2135 hash_map::Entry::Occupied(mut entry) => {
2136 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id, err_packet });
2138 hash_map::Entry::Vacant(entry) => {
2139 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id, err_packet }));
2142 mem::drop(channel_state_lock);
2143 if let Some(time) = forward_event {
2144 let mut pending_events = self.pending_events.lock().unwrap();
2145 pending_events.push(events::Event::PendingHTLCsForwardable {
2146 time_forwardable: time
2153 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
2154 /// generating message events for the net layer to claim the payment, if possible. Thus, you
2155 /// should probably kick the net layer to go send messages if this returns true!
2157 /// You must specify the expected amounts for this HTLC, and we will only claim HTLCs
2158 /// available within a few percent of the expected amount. This is critical for several
2159 /// reasons : a) it avoids providing senders with `proof-of-payment` (in the form of the
2160 /// payment_preimage without having provided the full value and b) it avoids certain
2161 /// privacy-breaking recipient-probing attacks which may reveal payment activity to
2162 /// motivated attackers.
2164 /// Note that the privacy concerns in (b) are not relevant in payments with a payment_secret
2165 /// set. Thus, for such payments we will claim any payments which do not under-pay.
2167 /// May panic if called except in response to a PaymentReceived event.
2168 pub fn claim_funds(&self, payment_preimage: PaymentPreimage, payment_secret: &Option<PaymentSecret>, expected_amount: u64) -> bool {
2169 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
2171 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
2173 let mut channel_state = Some(self.channel_state.lock().unwrap());
2174 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(payment_hash, *payment_secret));
2175 if let Some(mut sources) = removed_source {
2176 assert!(!sources.is_empty());
2178 // If we are claiming an MPP payment, we have to take special care to ensure that each
2179 // channel exists before claiming all of the payments (inside one lock).
2180 // Note that channel existance is sufficient as we should always get a monitor update
2181 // which will take care of the real HTLC claim enforcement.
2183 // If we find an HTLC which we would need to claim but for which we do not have a
2184 // channel, we will fail all parts of the MPP payment. While we could wait and see if
2185 // the sender retries the already-failed path(s), it should be a pretty rare case where
2186 // we got all the HTLCs and then a channel closed while we were waiting for the user to
2187 // provide the preimage, so worrying too much about the optimal handling isn't worth
2190 let (is_mpp, mut valid_mpp) = if let &Some(ref data) = &sources[0].payment_data {
2191 assert!(payment_secret.is_some());
2192 (true, data.total_msat >= expected_amount)
2194 assert!(payment_secret.is_none());
2198 for htlc in sources.iter() {
2199 if !is_mpp || !valid_mpp { break; }
2200 if let None = channel_state.as_ref().unwrap().short_to_id.get(&htlc.prev_hop.short_channel_id) {
2205 let mut errs = Vec::new();
2206 let mut claimed_any_htlcs = false;
2207 for htlc in sources.drain(..) {
2208 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
2209 if (is_mpp && !valid_mpp) || (!is_mpp && (htlc.value < expected_amount || htlc.value > expected_amount * 2)) {
2210 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
2211 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
2212 self.latest_block_height.load(Ordering::Acquire) as u32,
2214 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
2215 HTLCSource::PreviousHopData(htlc.prev_hop), &payment_hash,
2216 HTLCFailReason::Reason { failure_code: 0x4000|15, data: htlc_msat_height_data });
2218 match self.claim_funds_from_hop(channel_state.as_mut().unwrap(), htlc.prev_hop, payment_preimage) {
2220 if let msgs::ErrorAction::IgnoreError = e.1.err.action {
2221 // We got a temporary failure updating monitor, but will claim the
2222 // HTLC when the monitor updating is restored (or on chain).
2223 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", e.1.err.err);
2224 claimed_any_htlcs = true;
2225 } else { errs.push(e); }
2227 Err(None) if is_mpp => unreachable!("We already checked for channel existence, we can't fail here!"),
2229 log_warn!(self.logger, "Channel we expected to claim an HTLC from was closed.");
2231 Ok(()) => claimed_any_htlcs = true,
2236 // Now that we've done the entire above loop in one lock, we can handle any errors
2237 // which were generated.
2238 channel_state.take();
2240 for (counterparty_node_id, err) in errs.drain(..) {
2241 let res: Result<(), _> = Err(err);
2242 let _ = handle_error!(self, res, counterparty_node_id);
2249 fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard<ChannelHolder<Signer>>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> Result<(), Option<(PublicKey, MsgHandleErrInternal)>> {
2250 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
2251 let channel_state = &mut **channel_state_lock;
2252 let chan_id = match channel_state.short_to_id.get(&prev_hop.short_channel_id) {
2253 Some(chan_id) => chan_id.clone(),
2259 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(chan_id) {
2260 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2261 match chan.get_mut().get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger) {
2262 Ok((msgs, monitor_option)) => {
2263 if let Some(monitor_update) = monitor_option {
2264 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2265 if was_frozen_for_monitor {
2266 assert!(msgs.is_none());
2268 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())));
2272 if let Some((msg, commitment_signed)) = msgs {
2273 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2274 node_id: chan.get().get_counterparty_node_id(),
2275 updates: msgs::CommitmentUpdate {
2276 update_add_htlcs: Vec::new(),
2277 update_fulfill_htlcs: vec![msg],
2278 update_fail_htlcs: Vec::new(),
2279 update_fail_malformed_htlcs: Vec::new(),
2288 // TODO: Do something with e?
2289 // This should only occur if we are claiming an HTLC at the same time as the
2290 // HTLC is being failed (eg because a block is being connected and this caused
2291 // an HTLC to time out). This should, of course, only occur if the user is the
2292 // one doing the claiming (as it being a part of a peer claim would imply we're
2293 // about to lose funds) and only if the lock in claim_funds was dropped as a
2294 // previous HTLC was failed (thus not for an MPP payment).
2295 debug_assert!(false, "This shouldn't be reachable except in absurdly rare cases between monitor updates and HTLC timeouts: {:?}", e);
2299 } else { unreachable!(); }
2302 fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_preimage: PaymentPreimage) {
2304 HTLCSource::OutboundRoute { .. } => {
2305 mem::drop(channel_state_lock);
2306 let mut pending_events = self.pending_events.lock().unwrap();
2307 pending_events.push(events::Event::PaymentSent {
2311 HTLCSource::PreviousHopData(hop_data) => {
2312 let prev_outpoint = hop_data.outpoint;
2313 if let Err((counterparty_node_id, err)) = match self.claim_funds_from_hop(&mut channel_state_lock, hop_data, payment_preimage) {
2316 let preimage_update = ChannelMonitorUpdate {
2317 update_id: CLOSED_CHANNEL_UPDATE_ID,
2318 updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
2319 payment_preimage: payment_preimage.clone(),
2322 // We update the ChannelMonitor on the backward link, after
2323 // receiving an offchain preimage event from the forward link (the
2324 // event being update_fulfill_htlc).
2325 if let Err(e) = self.chain_monitor.update_channel(prev_outpoint, preimage_update) {
2326 log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
2327 payment_preimage, e);
2331 Err(Some(res)) => Err(res),
2333 mem::drop(channel_state_lock);
2334 let res: Result<(), _> = Err(err);
2335 let _ = handle_error!(self, res, counterparty_node_id);
2341 /// Gets the node_id held by this ChannelManager
2342 pub fn get_our_node_id(&self) -> PublicKey {
2343 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
2346 /// Restores a single, given channel to normal operation after a
2347 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
2350 /// All ChannelMonitor updates up to and including highest_applied_update_id must have been
2351 /// fully committed in every copy of the given channels' ChannelMonitors.
2353 /// Note that there is no effect to calling with a highest_applied_update_id other than the
2354 /// current latest ChannelMonitorUpdate and one call to this function after multiple
2355 /// ChannelMonitorUpdateErr::TemporaryFailures is fine. The highest_applied_update_id field
2356 /// exists largely only to prevent races between this and concurrent update_monitor calls.
2358 /// In some cases, this may generate a monitor update, resulting in a call to the
2359 /// `chain::Watch`'s `update_channel` method for the same channel monitor which is being
2360 /// notified of a successful update here. Because of this, please be very careful with
2361 /// reentrancy bugs! It is incredibly easy to write an implementation of `update_channel` which
2362 /// will take a lock that is also held when calling this method.
2364 /// Thus, the anticipated use is, at a high level:
2365 /// 1) You register a chain::Watch with this ChannelManager,
2366 /// 2) it stores each update to disk, and begins updating any remote (eg watchtower) copies of
2367 /// said ChannelMonitors as it can, returning ChannelMonitorUpdateErr::TemporaryFailures
2368 /// any time it cannot do so instantly,
2369 /// 3) update(s) are applied to each remote copy of a ChannelMonitor,
2370 /// 4) once all remote copies are updated, you call this function with the update_id that
2371 /// completed, and once it is the latest the Channel will be re-enabled.
2372 pub fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64) {
2373 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
2375 let (pending_failures, forwarding_failures, chan_restoration_res) = {
2376 let mut channel_lock = self.channel_state.lock().unwrap();
2377 let channel_state = &mut *channel_lock;
2378 let mut channel = match channel_state.by_id.entry(funding_txo.to_channel_id()) {
2379 hash_map::Entry::Occupied(chan) => chan,
2380 hash_map::Entry::Vacant(_) => return,
2382 if !channel.get().is_awaiting_monitor_update() || channel.get().get_latest_monitor_update_id() != highest_applied_update_id {
2386 let (raa, commitment_update, order, chanmon_update, pending_forwards, pending_failures, forwarding_failures, needs_broadcast_safe, funding_locked) = channel.get_mut().monitor_updating_restored(&self.logger);
2387 (pending_failures, forwarding_failures, handle_chan_restoration_locked!(self, channel_lock, channel_state, channel, raa, commitment_update, order, chanmon_update, pending_forwards, needs_broadcast_safe, funding_locked))
2389 post_handle_chan_restoration!(self, chan_restoration_res, pending_failures, forwarding_failures);
2392 fn internal_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
2393 if msg.chain_hash != self.genesis_hash {
2394 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
2397 let channel = Channel::new_from_req(&self.fee_estimator, &self.keys_manager, counterparty_node_id.clone(), their_features, msg, 0, &self.default_configuration)
2398 .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
2399 let mut channel_state_lock = self.channel_state.lock().unwrap();
2400 let channel_state = &mut *channel_state_lock;
2401 match channel_state.by_id.entry(channel.channel_id()) {
2402 hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!".to_owned(), msg.temporary_channel_id.clone())),
2403 hash_map::Entry::Vacant(entry) => {
2404 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
2405 node_id: counterparty_node_id.clone(),
2406 msg: channel.get_accept_channel(),
2408 entry.insert(channel);
2414 fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
2415 let (value, output_script, user_id) = {
2416 let mut channel_lock = self.channel_state.lock().unwrap();
2417 let channel_state = &mut *channel_lock;
2418 match channel_state.by_id.entry(msg.temporary_channel_id) {
2419 hash_map::Entry::Occupied(mut chan) => {
2420 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2421 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
2423 try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration, their_features), channel_state, chan);
2424 (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
2426 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
2429 let mut pending_events = self.pending_events.lock().unwrap();
2430 pending_events.push(events::Event::FundingGenerationReady {
2431 temporary_channel_id: msg.temporary_channel_id,
2432 channel_value_satoshis: value,
2434 user_channel_id: user_id,
2439 fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
2440 let ((funding_msg, monitor), mut chan) = {
2441 let mut channel_lock = self.channel_state.lock().unwrap();
2442 let channel_state = &mut *channel_lock;
2443 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
2444 hash_map::Entry::Occupied(mut chan) => {
2445 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2446 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
2448 (try_chan_entry!(self, chan.get_mut().funding_created(msg, &self.logger), channel_state, chan), chan.remove())
2450 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
2453 // Because we have exclusive ownership of the channel here we can release the channel_state
2454 // lock before watch_channel
2455 if let Err(e) = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor) {
2457 ChannelMonitorUpdateErr::PermanentFailure => {
2458 // Note that we reply with the new channel_id in error messages if we gave up on the
2459 // channel, not the temporary_channel_id. This is compatible with ourselves, but the
2460 // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
2461 // any messages referencing a previously-closed channel anyway.
2462 // We do not do a force-close here as that would generate a monitor update for
2463 // a monitor that we didn't manage to store (and that we don't care about - we
2464 // don't respond with the funding_signed so the channel can never go on chain).
2465 let (_funding_txo_option, _monitor_update, failed_htlcs) = chan.force_shutdown(true);
2466 assert!(failed_htlcs.is_empty());
2467 return Err(MsgHandleErrInternal::send_err_msg_no_close("ChannelMonitor storage failure".to_owned(), funding_msg.channel_id));
2469 ChannelMonitorUpdateErr::TemporaryFailure => {
2470 // There's no problem signing a counterparty's funding transaction if our monitor
2471 // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
2472 // accepted payment from yet. We do, however, need to wait to send our funding_locked
2473 // until we have persisted our monitor.
2474 chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
2478 let mut channel_state_lock = self.channel_state.lock().unwrap();
2479 let channel_state = &mut *channel_state_lock;
2480 match channel_state.by_id.entry(funding_msg.channel_id) {
2481 hash_map::Entry::Occupied(_) => {
2482 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
2484 hash_map::Entry::Vacant(e) => {
2485 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
2486 node_id: counterparty_node_id.clone(),
2495 fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
2496 let (funding_txo, user_id) = {
2497 let mut channel_lock = self.channel_state.lock().unwrap();
2498 let channel_state = &mut *channel_lock;
2499 match channel_state.by_id.entry(msg.channel_id) {
2500 hash_map::Entry::Occupied(mut chan) => {
2501 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2502 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2504 let monitor = match chan.get_mut().funding_signed(&msg, &self.logger) {
2505 Ok(update) => update,
2506 Err(e) => try_chan_entry!(self, Err(e), channel_state, chan),
2508 if let Err(e) = self.chain_monitor.watch_channel(chan.get().get_funding_txo().unwrap(), monitor) {
2509 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
2511 (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
2513 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2516 let mut pending_events = self.pending_events.lock().unwrap();
2517 pending_events.push(events::Event::FundingBroadcastSafe {
2519 user_channel_id: user_id,
2524 fn internal_funding_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
2525 let mut channel_state_lock = self.channel_state.lock().unwrap();
2526 let channel_state = &mut *channel_state_lock;
2527 match channel_state.by_id.entry(msg.channel_id) {
2528 hash_map::Entry::Occupied(mut chan) => {
2529 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2530 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2532 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
2533 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
2534 log_trace!(self.logger, "Sending announcement_signatures for {} in response to funding_locked", log_bytes!(chan.get().channel_id()));
2535 // If we see locking block before receiving remote funding_locked, we broadcast our
2536 // announcement_sigs at remote funding_locked reception. If we receive remote
2537 // funding_locked before seeing locking block, we broadcast our announcement_sigs at locking
2538 // block connection. We should guanrantee to broadcast announcement_sigs to our peer whatever
2539 // the order of the events but our peer may not receive it due to disconnection. The specs
2540 // lacking an acknowledgement for announcement_sigs we may have to re-send them at peer
2541 // connection in the future if simultaneous misses by both peers due to network/hardware
2542 // failures is an issue. Note, to achieve its goal, only one of the announcement_sigs needs
2543 // to be received, from then sigs are going to be flood to the whole network.
2544 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2545 node_id: counterparty_node_id.clone(),
2546 msg: announcement_sigs,
2551 hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2555 fn internal_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
2556 let (mut dropped_htlcs, chan_option) = {
2557 let mut channel_state_lock = self.channel_state.lock().unwrap();
2558 let channel_state = &mut *channel_state_lock;
2560 match channel_state.by_id.entry(msg.channel_id.clone()) {
2561 hash_map::Entry::Occupied(mut chan_entry) => {
2562 if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
2563 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2565 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);
2566 if let Some(msg) = shutdown {
2567 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2568 node_id: counterparty_node_id.clone(),
2572 if let Some(msg) = closing_signed {
2573 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2574 node_id: counterparty_node_id.clone(),
2578 if chan_entry.get().is_shutdown() {
2579 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2580 channel_state.short_to_id.remove(&short_id);
2582 (dropped_htlcs, Some(chan_entry.remove_entry().1))
2583 } else { (dropped_htlcs, None) }
2585 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2588 for htlc_source in dropped_htlcs.drain(..) {
2589 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() });
2591 if let Some(chan) = chan_option {
2592 if let Ok(update) = self.get_channel_update(&chan) {
2593 let mut channel_state = self.channel_state.lock().unwrap();
2594 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2602 fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
2603 let (tx, chan_option) = {
2604 let mut channel_state_lock = self.channel_state.lock().unwrap();
2605 let channel_state = &mut *channel_state_lock;
2606 match channel_state.by_id.entry(msg.channel_id.clone()) {
2607 hash_map::Entry::Occupied(mut chan_entry) => {
2608 if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
2609 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2611 let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&self.fee_estimator, &msg), channel_state, chan_entry);
2612 if let Some(msg) = closing_signed {
2613 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2614 node_id: counterparty_node_id.clone(),
2619 // We're done with this channel, we've got a signed closing transaction and
2620 // will send the closing_signed back to the remote peer upon return. This
2621 // also implies there are no pending HTLCs left on the channel, so we can
2622 // fully delete it from tracking (the channel monitor is still around to
2623 // watch for old state broadcasts)!
2624 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2625 channel_state.short_to_id.remove(&short_id);
2627 (tx, Some(chan_entry.remove_entry().1))
2628 } else { (tx, None) }
2630 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2633 if let Some(broadcast_tx) = tx {
2634 log_trace!(self.logger, "Broadcast onchain {}", log_tx!(broadcast_tx));
2635 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2637 if let Some(chan) = chan_option {
2638 if let Ok(update) = self.get_channel_update(&chan) {
2639 let mut channel_state = self.channel_state.lock().unwrap();
2640 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2648 fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2649 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2650 //determine the state of the payment based on our response/if we forward anything/the time
2651 //we take to respond. We should take care to avoid allowing such an attack.
2653 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2654 //us repeatedly garbled in different ways, and compare our error messages, which are
2655 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
2656 //but we should prevent it anyway.
2658 let (pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2659 let channel_state = &mut *channel_state_lock;
2661 match channel_state.by_id.entry(msg.channel_id) {
2662 hash_map::Entry::Occupied(mut chan) => {
2663 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2664 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2667 let create_pending_htlc_status = |chan: &Channel<Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
2668 // Ensure error_code has the UPDATE flag set, since by default we send a
2669 // channel update along as part of failing the HTLC.
2670 assert!((error_code & 0x1000) != 0);
2671 // If the update_add is completely bogus, the call will Err and we will close,
2672 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2673 // want to reject the new HTLC and fail it backwards instead of forwarding.
2674 match pending_forward_info {
2675 PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
2676 let reason = if let Ok(upd) = self.get_channel_update(chan) {
2677 onion_utils::build_first_hop_failure_packet(incoming_shared_secret, error_code, &{
2678 let mut res = Vec::with_capacity(8 + 128);
2679 // TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
2680 res.extend_from_slice(&byte_utils::be16_to_array(0));
2681 res.extend_from_slice(&upd.encode_with_len()[..]);
2685 // The only case where we'd be unable to
2686 // successfully get a channel update is if the
2687 // channel isn't in the fully-funded state yet,
2688 // implying our counterparty is trying to route
2689 // payments over the channel back to themselves
2690 // (cause no one else should know the short_id
2691 // is a lightning channel yet). We should have
2692 // no problem just calling this
2693 // unknown_next_peer (0x4000|10).
2694 onion_utils::build_first_hop_failure_packet(incoming_shared_secret, 0x4000|10, &[])
2696 let msg = msgs::UpdateFailHTLC {
2697 channel_id: msg.channel_id,
2698 htlc_id: msg.htlc_id,
2701 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
2703 _ => pending_forward_info
2706 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.logger), channel_state, chan);
2708 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2713 fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2714 let mut channel_lock = self.channel_state.lock().unwrap();
2716 let channel_state = &mut *channel_lock;
2717 match channel_state.by_id.entry(msg.channel_id) {
2718 hash_map::Entry::Occupied(mut chan) => {
2719 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2720 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2722 try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2724 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2727 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2731 fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2732 let mut channel_lock = self.channel_state.lock().unwrap();
2733 let channel_state = &mut *channel_lock;
2734 match channel_state.by_id.entry(msg.channel_id) {
2735 hash_map::Entry::Occupied(mut chan) => {
2736 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2737 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2739 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::LightningError { err: msg.reason.clone() }), channel_state, chan);
2741 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2746 fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2747 let mut channel_lock = self.channel_state.lock().unwrap();
2748 let channel_state = &mut *channel_lock;
2749 match channel_state.by_id.entry(msg.channel_id) {
2750 hash_map::Entry::Occupied(mut chan) => {
2751 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2752 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2754 if (msg.failure_code & 0x8000) == 0 {
2755 let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
2756 try_chan_entry!(self, Err(chan_err), channel_state, chan);
2758 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);
2761 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2765 fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2766 let mut channel_state_lock = self.channel_state.lock().unwrap();
2767 let channel_state = &mut *channel_state_lock;
2768 match channel_state.by_id.entry(msg.channel_id) {
2769 hash_map::Entry::Occupied(mut chan) => {
2770 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2771 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2773 let (revoke_and_ack, commitment_signed, closing_signed, monitor_update) =
2774 match chan.get_mut().commitment_signed(&msg, &self.fee_estimator, &self.logger) {
2775 Err((None, e)) => try_chan_entry!(self, Err(e), channel_state, chan),
2776 Err((Some(update), e)) => {
2777 assert!(chan.get().is_awaiting_monitor_update());
2778 let _ = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), update);
2779 try_chan_entry!(self, Err(e), channel_state, chan);
2784 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2785 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some());
2786 //TODO: Rebroadcast closing_signed if present on monitor update restoration
2788 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2789 node_id: counterparty_node_id.clone(),
2790 msg: revoke_and_ack,
2792 if let Some(msg) = commitment_signed {
2793 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2794 node_id: counterparty_node_id.clone(),
2795 updates: msgs::CommitmentUpdate {
2796 update_add_htlcs: Vec::new(),
2797 update_fulfill_htlcs: Vec::new(),
2798 update_fail_htlcs: Vec::new(),
2799 update_fail_malformed_htlcs: Vec::new(),
2801 commitment_signed: msg,
2805 if let Some(msg) = closing_signed {
2806 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2807 node_id: counterparty_node_id.clone(),
2813 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2818 fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, Vec<(PendingHTLCInfo, u64)>)]) {
2819 for &mut (prev_short_channel_id, prev_funding_outpoint, ref mut pending_forwards) in per_source_pending_forwards {
2820 let mut forward_event = None;
2821 if !pending_forwards.is_empty() {
2822 let mut channel_state = self.channel_state.lock().unwrap();
2823 if channel_state.forward_htlcs.is_empty() {
2824 forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS))
2826 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2827 match channel_state.forward_htlcs.entry(match forward_info.routing {
2828 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
2829 PendingHTLCRouting::Receive { .. } => 0,
2831 hash_map::Entry::Occupied(mut entry) => {
2832 entry.get_mut().push(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_funding_outpoint,
2833 prev_htlc_id, forward_info });
2835 hash_map::Entry::Vacant(entry) => {
2836 entry.insert(vec!(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_funding_outpoint,
2837 prev_htlc_id, forward_info }));
2842 match forward_event {
2844 let mut pending_events = self.pending_events.lock().unwrap();
2845 pending_events.push(events::Event::PendingHTLCsForwardable {
2846 time_forwardable: time
2854 fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2855 let mut htlcs_to_fail = Vec::new();
2857 let mut channel_state_lock = self.channel_state.lock().unwrap();
2858 let channel_state = &mut *channel_state_lock;
2859 match channel_state.by_id.entry(msg.channel_id) {
2860 hash_map::Entry::Occupied(mut chan) => {
2861 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2862 break Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2864 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2865 let (commitment_update, pending_forwards, pending_failures, closing_signed, monitor_update, htlcs_to_fail_in) =
2866 break_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &self.fee_estimator, &self.logger), channel_state, chan);
2867 htlcs_to_fail = htlcs_to_fail_in;
2868 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2869 if was_frozen_for_monitor {
2870 assert!(commitment_update.is_none() && closing_signed.is_none() && pending_forwards.is_empty() && pending_failures.is_empty());
2871 break Err(MsgHandleErrInternal::ignore_no_close("Previous monitor update failure prevented responses to RAA".to_owned()));
2873 if let Err(e) = handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, commitment_update.is_some(), pending_forwards, pending_failures) {
2875 } else { unreachable!(); }
2878 if let Some(updates) = commitment_update {
2879 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2880 node_id: counterparty_node_id.clone(),
2884 if let Some(msg) = closing_signed {
2885 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2886 node_id: counterparty_node_id.clone(),
2890 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()))
2892 hash_map::Entry::Vacant(_) => break Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2895 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id);
2897 Ok((pending_forwards, mut pending_failures, short_channel_id, channel_outpoint)) => {
2898 for failure in pending_failures.drain(..) {
2899 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2901 self.forward_htlcs(&mut [(short_channel_id, channel_outpoint, pending_forwards)]);
2908 fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2909 let mut channel_lock = self.channel_state.lock().unwrap();
2910 let channel_state = &mut *channel_lock;
2911 match channel_state.by_id.entry(msg.channel_id) {
2912 hash_map::Entry::Occupied(mut chan) => {
2913 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2914 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2916 try_chan_entry!(self, chan.get_mut().update_fee(&self.fee_estimator, &msg), channel_state, chan);
2918 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2923 fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2924 let mut channel_state_lock = self.channel_state.lock().unwrap();
2925 let channel_state = &mut *channel_state_lock;
2927 match channel_state.by_id.entry(msg.channel_id) {
2928 hash_map::Entry::Occupied(mut chan) => {
2929 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2930 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2932 if !chan.get().is_usable() {
2933 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
2936 let our_node_id = self.get_our_node_id();
2937 let (announcement, our_bitcoin_sig) =
2938 try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2940 let were_node_one = announcement.node_id_1 == our_node_id;
2941 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
2943 let their_node_key = if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 };
2944 let their_bitcoin_key = if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 };
2945 match (self.secp_ctx.verify(&msghash, &msg.node_signature, their_node_key),
2946 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, their_bitcoin_key)) {
2948 let chan_err: ChannelError = ChannelError::Close(format!("Bad announcement_signatures. Failed to verify node_signature: {:?}. Maybe using different node_secret for transport and routing msg? UnsignedChannelAnnouncement used for verification is {:?}. their_node_key is {:?}", e, &announcement, their_node_key));
2949 try_chan_entry!(self, Err(chan_err), channel_state, chan);
2952 let chan_err: ChannelError = ChannelError::Close(format!("Bad announcement_signatures. Failed to verify bitcoin_signature: {:?}. UnsignedChannelAnnouncement used for verification is {:?}. their_bitcoin_key is ({:?})", e, &announcement, their_bitcoin_key));
2953 try_chan_entry!(self, Err(chan_err), channel_state, chan);
2959 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2961 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2962 msg: msgs::ChannelAnnouncement {
2963 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2964 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2965 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2966 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2967 contents: announcement,
2969 update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2972 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2977 fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2978 let chan_restoration_res = {
2979 let mut channel_state_lock = self.channel_state.lock().unwrap();
2980 let channel_state = &mut *channel_state_lock;
2982 match channel_state.by_id.entry(msg.channel_id) {
2983 hash_map::Entry::Occupied(mut chan) => {
2984 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2985 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2987 // Currently, we expect all holding cell update_adds to be dropped on peer
2988 // disconnect, so Channel's reestablish will never hand us any holding cell
2989 // freed HTLCs to fail backwards. If in the future we no longer drop pending
2990 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
2991 let (funding_locked, revoke_and_ack, commitment_update, monitor_update_opt, order, shutdown) =
2992 try_chan_entry!(self, chan.get_mut().channel_reestablish(msg, &self.logger), channel_state, chan);
2993 if let Some(msg) = shutdown {
2994 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2995 node_id: counterparty_node_id.clone(),
2999 handle_chan_restoration_locked!(self, channel_state_lock, channel_state, chan, revoke_and_ack, commitment_update, order, monitor_update_opt, Vec::new(), false, funding_locked)
3001 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3004 post_handle_chan_restoration!(self, chan_restoration_res, Vec::new(), Vec::new());
3008 /// Begin Update fee process. Allowed only on an outbound channel.
3009 /// If successful, will generate a UpdateHTLCs event, so you should probably poll
3010 /// PeerManager::process_events afterwards.
3011 /// Note: This API is likely to change!
3012 /// (C-not exported) Cause its doc(hidden) anyway
3014 pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u32) -> Result<(), APIError> {
3015 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3016 let counterparty_node_id;
3017 let err: Result<(), _> = loop {
3018 let mut channel_state_lock = self.channel_state.lock().unwrap();
3019 let channel_state = &mut *channel_state_lock;
3021 match channel_state.by_id.entry(channel_id) {
3022 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: format!("Failed to find corresponding channel for id {}", channel_id.to_hex())}),
3023 hash_map::Entry::Occupied(mut chan) => {
3024 if !chan.get().is_outbound() {
3025 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel".to_owned()});
3027 if chan.get().is_awaiting_monitor_update() {
3028 return Err(APIError::MonitorUpdateFailed);
3030 if !chan.get().is_live() {
3031 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected".to_owned()});
3033 counterparty_node_id = chan.get().get_counterparty_node_id();
3034 if let Some((update_fee, commitment_signed, monitor_update)) =
3035 break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw, &self.logger), channel_state, chan)
3037 if let Err(_e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3040 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3041 node_id: chan.get().get_counterparty_node_id(),
3042 updates: msgs::CommitmentUpdate {
3043 update_add_htlcs: Vec::new(),
3044 update_fulfill_htlcs: Vec::new(),
3045 update_fail_htlcs: Vec::new(),
3046 update_fail_malformed_htlcs: Vec::new(),
3047 update_fee: Some(update_fee),
3057 match handle_error!(self, err, counterparty_node_id) {
3058 Ok(_) => unreachable!(),
3059 Err(e) => { Err(APIError::APIMisuseError { err: e.err })}
3063 /// Process pending events from the `chain::Watch`.
3064 fn process_pending_monitor_events(&self) {
3065 let mut failed_channels = Vec::new();
3067 for monitor_event in self.chain_monitor.release_pending_monitor_events() {
3068 match monitor_event {
3069 MonitorEvent::HTLCEvent(htlc_update) => {
3070 if let Some(preimage) = htlc_update.payment_preimage {
3071 log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
3072 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
3074 log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
3075 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() });
3078 MonitorEvent::CommitmentTxBroadcasted(funding_outpoint) => {
3079 let mut channel_lock = self.channel_state.lock().unwrap();
3080 let channel_state = &mut *channel_lock;
3081 let by_id = &mut channel_state.by_id;
3082 let short_to_id = &mut channel_state.short_to_id;
3083 let pending_msg_events = &mut channel_state.pending_msg_events;
3084 if let Some(mut chan) = by_id.remove(&funding_outpoint.to_channel_id()) {
3085 if let Some(short_id) = chan.get_short_channel_id() {
3086 short_to_id.remove(&short_id);
3088 failed_channels.push(chan.force_shutdown(false));
3089 if let Ok(update) = self.get_channel_update(&chan) {
3090 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3100 for failure in failed_channels.drain(..) {
3101 self.finish_force_close_channel(failure);
3106 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> MessageSendEventsProvider for ChannelManager<Signer, M, T, K, F, L>
3107 where M::Target: chain::Watch<Signer>,
3108 T::Target: BroadcasterInterface,
3109 K::Target: KeysInterface<Signer = Signer>,
3110 F::Target: FeeEstimator,
3113 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
3114 //TODO: This behavior should be documented. It's non-intuitive that we query
3115 // ChannelMonitors when clearing other events.
3116 self.process_pending_monitor_events();
3118 let mut ret = Vec::new();
3119 let mut channel_state = self.channel_state.lock().unwrap();
3120 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
3125 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> EventsProvider for ChannelManager<Signer, M, T, K, F, L>
3126 where M::Target: chain::Watch<Signer>,
3127 T::Target: BroadcasterInterface,
3128 K::Target: KeysInterface<Signer = Signer>,
3129 F::Target: FeeEstimator,
3132 fn get_and_clear_pending_events(&self) -> Vec<Event> {
3133 //TODO: This behavior should be documented. It's non-intuitive that we query
3134 // ChannelMonitors when clearing other events.
3135 self.process_pending_monitor_events();
3137 let mut ret = Vec::new();
3138 let mut pending_events = self.pending_events.lock().unwrap();
3139 mem::swap(&mut ret, &mut *pending_events);
3144 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> chain::Listen for ChannelManager<Signer, M, T, K, F, L>
3146 M::Target: chain::Watch<Signer>,
3147 T::Target: BroadcasterInterface,
3148 K::Target: KeysInterface<Signer = Signer>,
3149 F::Target: FeeEstimator,
3152 fn block_connected(&self, block: &Block, height: u32) {
3153 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
3154 ChannelManager::block_connected(self, &block.header, &txdata, height);
3157 fn block_disconnected(&self, header: &BlockHeader, _height: u32) {
3158 ChannelManager::block_disconnected(self, header);
3162 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
3163 where M::Target: chain::Watch<Signer>,
3164 T::Target: BroadcasterInterface,
3165 K::Target: KeysInterface<Signer = Signer>,
3166 F::Target: FeeEstimator,
3169 /// Updates channel state based on transactions seen in a connected block.
3170 pub fn block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3171 let header_hash = header.block_hash();
3172 log_trace!(self.logger, "Block {} at height {} connected", header_hash, height);
3173 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3174 let mut failed_channels = Vec::new();
3175 let mut timed_out_htlcs = Vec::new();
3177 let mut channel_lock = self.channel_state.lock().unwrap();
3178 let channel_state = &mut *channel_lock;
3179 let short_to_id = &mut channel_state.short_to_id;
3180 let pending_msg_events = &mut channel_state.pending_msg_events;
3181 channel_state.by_id.retain(|_, channel| {
3182 let res = channel.block_connected(header, txdata, height);
3183 if let Ok((chan_res, mut timed_out_pending_htlcs)) = res {
3184 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
3185 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
3186 timed_out_htlcs.push((source, payment_hash, HTLCFailReason::Reason {
3187 failure_code: 0x1000 | 14, // expiry_too_soon, or at least it is now
3191 if let Some(funding_locked) = chan_res {
3192 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
3193 node_id: channel.get_counterparty_node_id(),
3194 msg: funding_locked,
3196 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
3197 log_trace!(self.logger, "Sending funding_locked and announcement_signatures for {}", log_bytes!(channel.channel_id()));
3198 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
3199 node_id: channel.get_counterparty_node_id(),
3200 msg: announcement_sigs,
3203 log_trace!(self.logger, "Sending funding_locked WITHOUT announcement_signatures for {}", log_bytes!(channel.channel_id()));
3205 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
3207 } else if let Err(e) = res {
3208 pending_msg_events.push(events::MessageSendEvent::HandleError {
3209 node_id: channel.get_counterparty_node_id(),
3210 action: msgs::ErrorAction::SendErrorMessage { msg: e },
3214 if let Some(funding_txo) = channel.get_funding_txo() {
3215 for &(_, tx) in txdata.iter() {
3216 for inp in tx.input.iter() {
3217 if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
3218 log_trace!(self.logger, "Detected channel-closing tx {} spending {}:{}, closing channel {}", tx.txid(), inp.previous_output.txid, inp.previous_output.vout, log_bytes!(channel.channel_id()));
3219 if let Some(short_id) = channel.get_short_channel_id() {
3220 short_to_id.remove(&short_id);
3222 // It looks like our counterparty went on-chain. We go ahead and
3223 // broadcast our latest local state as well here, just in case its
3224 // some kind of SPV attack, though we expect these to be dropped.
3225 failed_channels.push(channel.force_shutdown(true));
3226 if let Ok(update) = self.get_channel_update(&channel) {
3227 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3239 channel_state.claimable_htlcs.retain(|&(ref payment_hash, _), htlcs| {
3240 htlcs.retain(|htlc| {
3241 // If height is approaching the number of blocks we think it takes us to get
3242 // our commitment transaction confirmed before the HTLC expires, plus the
3243 // number of blocks we generally consider it to take to do a commitment update,
3244 // just give up on it and fail the HTLC.
3245 if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
3246 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
3247 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(height));
3248 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(), HTLCFailReason::Reason {
3249 failure_code: 0x4000 | 15,
3250 data: htlc_msat_height_data
3255 !htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
3258 for failure in failed_channels.drain(..) {
3259 self.finish_force_close_channel(failure);
3262 for (source, payment_hash, reason) in timed_out_htlcs.drain(..) {
3263 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, reason);
3265 self.latest_block_height.store(height as usize, Ordering::Release);
3266 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
3268 // Update last_node_announcement_serial to be the max of its current value and the
3269 // block timestamp. This should keep us close to the current time without relying on
3270 // having an explicit local time source.
3271 // Just in case we end up in a race, we loop until we either successfully update
3272 // last_node_announcement_serial or decide we don't need to.
3273 let old_serial = self.last_node_announcement_serial.load(Ordering::Acquire);
3274 if old_serial >= header.time as usize { break; }
3275 if self.last_node_announcement_serial.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
3281 /// Updates channel state based on a disconnected block.
3283 /// If necessary, the channel may be force-closed without letting the counterparty participate
3284 /// in the shutdown.
3285 pub fn block_disconnected(&self, header: &BlockHeader) {
3286 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3287 let mut failed_channels = Vec::new();
3289 let mut channel_lock = self.channel_state.lock().unwrap();
3290 let channel_state = &mut *channel_lock;
3291 let short_to_id = &mut channel_state.short_to_id;
3292 let pending_msg_events = &mut channel_state.pending_msg_events;
3293 channel_state.by_id.retain(|_, v| {
3294 if v.block_disconnected(header) {
3295 if let Some(short_id) = v.get_short_channel_id() {
3296 short_to_id.remove(&short_id);
3298 failed_channels.push(v.force_shutdown(true));
3299 if let Ok(update) = self.get_channel_update(&v) {
3300 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3310 for failure in failed_channels.drain(..) {
3311 self.finish_force_close_channel(failure);
3313 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
3314 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.block_hash();
3317 /// Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool
3318 /// indicating whether persistence is necessary. Only one listener on `wait_timeout` is
3319 /// guaranteed to be woken up.
3320 /// Note that the feature `allow_wallclock_use` must be enabled to use this function.
3321 #[cfg(any(test, feature = "allow_wallclock_use"))]
3322 pub fn wait_timeout(&self, max_wait: Duration) -> bool {
3323 self.persistence_notifier.wait_timeout(max_wait)
3326 /// Blocks until ChannelManager needs to be persisted. Only one listener on `wait` is
3327 /// guaranteed to be woken up.
3328 pub fn wait(&self) {
3329 self.persistence_notifier.wait()
3332 #[cfg(any(test, feature = "_test_utils"))]
3333 pub fn get_persistence_condvar_value(&self) -> bool {
3334 let mutcond = &self.persistence_notifier.persistence_lock;
3335 let &(ref mtx, _) = mutcond;
3336 let guard = mtx.lock().unwrap();
3341 impl<Signer: Sign, M: Deref + Sync + Send, T: Deref + Sync + Send, K: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send>
3342 ChannelMessageHandler for ChannelManager<Signer, M, T, K, F, L>
3343 where M::Target: chain::Watch<Signer>,
3344 T::Target: BroadcasterInterface,
3345 K::Target: KeysInterface<Signer = Signer>,
3346 F::Target: FeeEstimator,
3349 fn handle_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) {
3350 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3351 let _ = handle_error!(self, self.internal_open_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
3354 fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) {
3355 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3356 let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
3359 fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
3360 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3361 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
3364 fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
3365 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3366 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
3369 fn handle_funding_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingLocked) {
3370 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3371 let _ = handle_error!(self, self.internal_funding_locked(counterparty_node_id, msg), *counterparty_node_id);
3374 fn handle_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) {
3375 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3376 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, their_features, msg), *counterparty_node_id);
3379 fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
3380 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3381 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
3384 fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
3385 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3386 let _ = handle_error!(self, self.internal_update_add_htlc(counterparty_node_id, msg), *counterparty_node_id);
3389 fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
3390 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3391 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
3394 fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
3395 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3396 let _ = handle_error!(self, self.internal_update_fail_htlc(counterparty_node_id, msg), *counterparty_node_id);
3399 fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
3400 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3401 let _ = handle_error!(self, self.internal_update_fail_malformed_htlc(counterparty_node_id, msg), *counterparty_node_id);
3404 fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
3405 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3406 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
3409 fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
3410 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3411 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
3414 fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
3415 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3416 let _ = handle_error!(self, self.internal_update_fee(counterparty_node_id, msg), *counterparty_node_id);
3419 fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
3420 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3421 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
3424 fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
3425 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3426 let _ = handle_error!(self, self.internal_channel_reestablish(counterparty_node_id, msg), *counterparty_node_id);
3429 fn peer_disconnected(&self, counterparty_node_id: &PublicKey, no_connection_possible: bool) {
3430 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3431 let mut failed_channels = Vec::new();
3432 let mut failed_payments = Vec::new();
3433 let mut no_channels_remain = true;
3435 let mut channel_state_lock = self.channel_state.lock().unwrap();
3436 let channel_state = &mut *channel_state_lock;
3437 let short_to_id = &mut channel_state.short_to_id;
3438 let pending_msg_events = &mut channel_state.pending_msg_events;
3439 if no_connection_possible {
3440 log_debug!(self.logger, "Failing all channels with {} due to no_connection_possible", log_pubkey!(counterparty_node_id));
3441 channel_state.by_id.retain(|_, chan| {
3442 if chan.get_counterparty_node_id() == *counterparty_node_id {
3443 if let Some(short_id) = chan.get_short_channel_id() {
3444 short_to_id.remove(&short_id);
3446 failed_channels.push(chan.force_shutdown(true));
3447 if let Ok(update) = self.get_channel_update(&chan) {
3448 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3458 log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(counterparty_node_id));
3459 channel_state.by_id.retain(|_, chan| {
3460 if chan.get_counterparty_node_id() == *counterparty_node_id {
3461 // Note that currently on channel reestablish we assert that there are no
3462 // holding cell add-HTLCs, so if in the future we stop removing uncommitted HTLCs
3463 // on peer disconnect here, there will need to be corresponding changes in
3464 // reestablish logic.
3465 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger);
3466 chan.to_disabled_marked();
3467 if !failed_adds.is_empty() {
3468 let chan_update = self.get_channel_update(&chan).map(|u| u.encode_with_len()).unwrap(); // Cannot add/recv HTLCs before we have a short_id so unwrap is safe
3469 failed_payments.push((chan_update, failed_adds));
3471 if chan.is_shutdown() {
3472 if let Some(short_id) = chan.get_short_channel_id() {
3473 short_to_id.remove(&short_id);
3477 no_channels_remain = false;
3483 pending_msg_events.retain(|msg| {
3485 &events::MessageSendEvent::SendAcceptChannel { ref node_id, .. } => node_id != counterparty_node_id,
3486 &events::MessageSendEvent::SendOpenChannel { ref node_id, .. } => node_id != counterparty_node_id,
3487 &events::MessageSendEvent::SendFundingCreated { ref node_id, .. } => node_id != counterparty_node_id,
3488 &events::MessageSendEvent::SendFundingSigned { ref node_id, .. } => node_id != counterparty_node_id,
3489 &events::MessageSendEvent::SendFundingLocked { ref node_id, .. } => node_id != counterparty_node_id,
3490 &events::MessageSendEvent::SendAnnouncementSignatures { ref node_id, .. } => node_id != counterparty_node_id,
3491 &events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => node_id != counterparty_node_id,
3492 &events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => node_id != counterparty_node_id,
3493 &events::MessageSendEvent::SendClosingSigned { ref node_id, .. } => node_id != counterparty_node_id,
3494 &events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != counterparty_node_id,
3495 &events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != counterparty_node_id,
3496 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
3497 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
3498 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
3499 &events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != counterparty_node_id,
3500 &events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
3501 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
3502 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
3506 if no_channels_remain {
3507 self.per_peer_state.write().unwrap().remove(counterparty_node_id);
3510 for failure in failed_channels.drain(..) {
3511 self.finish_force_close_channel(failure);
3513 for (chan_update, mut htlc_sources) in failed_payments {
3514 for (htlc_source, payment_hash) in htlc_sources.drain(..) {
3515 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
3520 fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init) {
3521 log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
3523 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3526 let mut peer_state_lock = self.per_peer_state.write().unwrap();
3527 match peer_state_lock.entry(counterparty_node_id.clone()) {
3528 hash_map::Entry::Vacant(e) => {
3529 e.insert(Mutex::new(PeerState {
3530 latest_features: init_msg.features.clone(),
3533 hash_map::Entry::Occupied(e) => {
3534 e.get().lock().unwrap().latest_features = init_msg.features.clone();
3539 let mut channel_state_lock = self.channel_state.lock().unwrap();
3540 let channel_state = &mut *channel_state_lock;
3541 let pending_msg_events = &mut channel_state.pending_msg_events;
3542 channel_state.by_id.retain(|_, chan| {
3543 if chan.get_counterparty_node_id() == *counterparty_node_id {
3544 if !chan.have_received_message() {
3545 // If we created this (outbound) channel while we were disconnected from the
3546 // peer we probably failed to send the open_channel message, which is now
3547 // lost. We can't have had anything pending related to this channel, so we just
3551 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
3552 node_id: chan.get_counterparty_node_id(),
3553 msg: chan.get_channel_reestablish(&self.logger),
3559 //TODO: Also re-broadcast announcement_signatures
3562 fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
3563 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3565 if msg.channel_id == [0; 32] {
3566 for chan in self.list_channels() {
3567 if chan.remote_network_id == *counterparty_node_id {
3568 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
3569 let _ = self.force_close_channel_with_peer(&chan.channel_id, Some(counterparty_node_id));
3573 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
3574 let _ = self.force_close_channel_with_peer(&msg.channel_id, Some(counterparty_node_id));
3579 /// Used to signal to the ChannelManager persister that the manager needs to be re-persisted to
3580 /// disk/backups, through `wait_timeout` and `wait`.
3581 struct PersistenceNotifier {
3582 /// Users won't access the persistence_lock directly, but rather wait on its bool using
3583 /// `wait_timeout` and `wait`.
3584 persistence_lock: (Mutex<bool>, Condvar),
3587 impl PersistenceNotifier {
3590 persistence_lock: (Mutex::new(false), Condvar::new()),
3596 let &(ref mtx, ref cvar) = &self.persistence_lock;
3597 let mut guard = mtx.lock().unwrap();
3598 guard = cvar.wait(guard).unwrap();
3599 let result = *guard;
3607 #[cfg(any(test, feature = "allow_wallclock_use"))]
3608 fn wait_timeout(&self, max_wait: Duration) -> bool {
3609 let current_time = Instant::now();
3611 let &(ref mtx, ref cvar) = &self.persistence_lock;
3612 let mut guard = mtx.lock().unwrap();
3613 guard = cvar.wait_timeout(guard, max_wait).unwrap().0;
3614 // Due to spurious wakeups that can happen on `wait_timeout`, here we need to check if the
3615 // desired wait time has actually passed, and if not then restart the loop with a reduced wait
3616 // time. Note that this logic can be highly simplified through the use of
3617 // `Condvar::wait_while` and `Condvar::wait_timeout_while`, if and when our MSRV is raised to
3619 let elapsed = current_time.elapsed();
3620 let result = *guard;
3621 if result || elapsed >= max_wait {
3625 match max_wait.checked_sub(elapsed) {
3626 None => return result,
3632 // Signal to the ChannelManager persister that there are updates necessitating persisting to disk.
3634 let &(ref persist_mtx, ref cnd) = &self.persistence_lock;
3635 let mut persistence_lock = persist_mtx.lock().unwrap();
3636 *persistence_lock = true;
3637 mem::drop(persistence_lock);
3642 const SERIALIZATION_VERSION: u8 = 1;
3643 const MIN_SERIALIZATION_VERSION: u8 = 1;
3645 impl Writeable for PendingHTLCInfo {
3646 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3647 match &self.routing {
3648 &PendingHTLCRouting::Forward { ref onion_packet, ref short_channel_id } => {
3650 onion_packet.write(writer)?;
3651 short_channel_id.write(writer)?;
3653 &PendingHTLCRouting::Receive { ref payment_data, ref incoming_cltv_expiry } => {
3655 payment_data.write(writer)?;
3656 incoming_cltv_expiry.write(writer)?;
3659 self.incoming_shared_secret.write(writer)?;
3660 self.payment_hash.write(writer)?;
3661 self.amt_to_forward.write(writer)?;
3662 self.outgoing_cltv_value.write(writer)?;
3667 impl Readable for PendingHTLCInfo {
3668 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<PendingHTLCInfo, DecodeError> {
3669 Ok(PendingHTLCInfo {
3670 routing: match Readable::read(reader)? {
3671 0u8 => PendingHTLCRouting::Forward {
3672 onion_packet: Readable::read(reader)?,
3673 short_channel_id: Readable::read(reader)?,
3675 1u8 => PendingHTLCRouting::Receive {
3676 payment_data: Readable::read(reader)?,
3677 incoming_cltv_expiry: Readable::read(reader)?,
3679 _ => return Err(DecodeError::InvalidValue),
3681 incoming_shared_secret: Readable::read(reader)?,
3682 payment_hash: Readable::read(reader)?,
3683 amt_to_forward: Readable::read(reader)?,
3684 outgoing_cltv_value: Readable::read(reader)?,
3689 impl Writeable for HTLCFailureMsg {
3690 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3692 &HTLCFailureMsg::Relay(ref fail_msg) => {
3694 fail_msg.write(writer)?;
3696 &HTLCFailureMsg::Malformed(ref fail_msg) => {
3698 fail_msg.write(writer)?;
3705 impl Readable for HTLCFailureMsg {
3706 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3707 match <u8 as Readable>::read(reader)? {
3708 0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3709 1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3710 _ => Err(DecodeError::InvalidValue),
3715 impl Writeable for PendingHTLCStatus {
3716 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3718 &PendingHTLCStatus::Forward(ref forward_info) => {
3720 forward_info.write(writer)?;
3722 &PendingHTLCStatus::Fail(ref fail_msg) => {
3724 fail_msg.write(writer)?;
3731 impl Readable for PendingHTLCStatus {
3732 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3733 match <u8 as Readable>::read(reader)? {
3734 0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3735 1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3736 _ => Err(DecodeError::InvalidValue),
3741 impl_writeable!(HTLCPreviousHopData, 0, {
3745 incoming_packet_shared_secret
3748 impl_writeable!(ClaimableHTLC, 0, {
3755 impl Writeable for HTLCSource {
3756 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3758 &HTLCSource::PreviousHopData(ref hop_data) => {
3760 hop_data.write(writer)?;
3762 &HTLCSource::OutboundRoute { ref path, ref session_priv, ref first_hop_htlc_msat } => {
3764 path.write(writer)?;
3765 session_priv.write(writer)?;
3766 first_hop_htlc_msat.write(writer)?;
3773 impl Readable for HTLCSource {
3774 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3775 match <u8 as Readable>::read(reader)? {
3776 0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3777 1 => Ok(HTLCSource::OutboundRoute {
3778 path: Readable::read(reader)?,
3779 session_priv: Readable::read(reader)?,
3780 first_hop_htlc_msat: Readable::read(reader)?,
3782 _ => Err(DecodeError::InvalidValue),
3787 impl Writeable for HTLCFailReason {
3788 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3790 &HTLCFailReason::LightningError { ref err } => {
3794 &HTLCFailReason::Reason { ref failure_code, ref data } => {
3796 failure_code.write(writer)?;
3797 data.write(writer)?;
3804 impl Readable for HTLCFailReason {
3805 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3806 match <u8 as Readable>::read(reader)? {
3807 0 => Ok(HTLCFailReason::LightningError { err: Readable::read(reader)? }),
3808 1 => Ok(HTLCFailReason::Reason {
3809 failure_code: Readable::read(reader)?,
3810 data: Readable::read(reader)?,
3812 _ => Err(DecodeError::InvalidValue),
3817 impl Writeable for HTLCForwardInfo {
3818 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3820 &HTLCForwardInfo::AddHTLC { ref prev_short_channel_id, ref prev_funding_outpoint, ref prev_htlc_id, ref forward_info } => {
3822 prev_short_channel_id.write(writer)?;
3823 prev_funding_outpoint.write(writer)?;
3824 prev_htlc_id.write(writer)?;
3825 forward_info.write(writer)?;
3827 &HTLCForwardInfo::FailHTLC { ref htlc_id, ref err_packet } => {
3829 htlc_id.write(writer)?;
3830 err_packet.write(writer)?;
3837 impl Readable for HTLCForwardInfo {
3838 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCForwardInfo, DecodeError> {
3839 match <u8 as Readable>::read(reader)? {
3840 0 => Ok(HTLCForwardInfo::AddHTLC {
3841 prev_short_channel_id: Readable::read(reader)?,
3842 prev_funding_outpoint: Readable::read(reader)?,
3843 prev_htlc_id: Readable::read(reader)?,
3844 forward_info: Readable::read(reader)?,
3846 1 => Ok(HTLCForwardInfo::FailHTLC {
3847 htlc_id: Readable::read(reader)?,
3848 err_packet: Readable::read(reader)?,
3850 _ => Err(DecodeError::InvalidValue),
3855 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable for ChannelManager<Signer, M, T, K, F, L>
3856 where M::Target: chain::Watch<Signer>,
3857 T::Target: BroadcasterInterface,
3858 K::Target: KeysInterface<Signer = Signer>,
3859 F::Target: FeeEstimator,
3862 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3863 let _consistency_lock = self.total_consistency_lock.write().unwrap();
3865 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3866 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3868 self.genesis_hash.write(writer)?;
3869 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3870 self.last_block_hash.lock().unwrap().write(writer)?;
3872 let channel_state = self.channel_state.lock().unwrap();
3873 let mut unfunded_channels = 0;
3874 for (_, channel) in channel_state.by_id.iter() {
3875 if !channel.is_funding_initiated() {
3876 unfunded_channels += 1;
3879 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3880 for (_, channel) in channel_state.by_id.iter() {
3881 if channel.is_funding_initiated() {
3882 channel.write(writer)?;
3886 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3887 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3888 short_channel_id.write(writer)?;
3889 (pending_forwards.len() as u64).write(writer)?;
3890 for forward in pending_forwards {
3891 forward.write(writer)?;
3895 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3896 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3897 payment_hash.write(writer)?;
3898 (previous_hops.len() as u64).write(writer)?;
3899 for htlc in previous_hops.iter() {
3900 htlc.write(writer)?;
3904 let per_peer_state = self.per_peer_state.write().unwrap();
3905 (per_peer_state.len() as u64).write(writer)?;
3906 for (peer_pubkey, peer_state_mutex) in per_peer_state.iter() {
3907 peer_pubkey.write(writer)?;
3908 let peer_state = peer_state_mutex.lock().unwrap();
3909 peer_state.latest_features.write(writer)?;
3912 let events = self.pending_events.lock().unwrap();
3913 (events.len() as u64).write(writer)?;
3914 for event in events.iter() {
3915 event.write(writer)?;
3918 (self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
3924 /// Arguments for the creation of a ChannelManager that are not deserialized.
3926 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3928 /// 1) Deserialize all stored ChannelMonitors.
3929 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3930 /// ChannelManager)>::read(reader, args).
3931 /// This may result in closing some Channels if the ChannelMonitor is newer than the stored
3932 /// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3933 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3934 /// ChannelMonitor::get_outputs_to_watch() and ChannelMonitor::get_funding_txo().
3935 /// 4) Reconnect blocks on your ChannelMonitors.
3936 /// 5) Move the ChannelMonitors into your local chain::Watch.
3937 /// 6) Disconnect/connect blocks on the ChannelManager.
3938 pub struct ChannelManagerReadArgs<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
3939 where M::Target: chain::Watch<Signer>,
3940 T::Target: BroadcasterInterface,
3941 K::Target: KeysInterface<Signer = Signer>,
3942 F::Target: FeeEstimator,
3945 /// The keys provider which will give us relevant keys. Some keys will be loaded during
3946 /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
3948 pub keys_manager: K,
3950 /// The fee_estimator for use in the ChannelManager in the future.
3952 /// No calls to the FeeEstimator will be made during deserialization.
3953 pub fee_estimator: F,
3954 /// The chain::Watch for use in the ChannelManager in the future.
3956 /// No calls to the chain::Watch will be made during deserialization. It is assumed that
3957 /// you have deserialized ChannelMonitors separately and will add them to your
3958 /// chain::Watch after deserializing this ChannelManager.
3959 pub chain_monitor: M,
3961 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3962 /// used to broadcast the latest local commitment transactions of channels which must be
3963 /// force-closed during deserialization.
3964 pub tx_broadcaster: T,
3965 /// The Logger for use in the ChannelManager and which may be used to log information during
3966 /// deserialization.
3968 /// Default settings used for new channels. Any existing channels will continue to use the
3969 /// runtime settings which were stored when the ChannelManager was serialized.
3970 pub default_config: UserConfig,
3972 /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3973 /// value.get_funding_txo() should be the key).
3975 /// If a monitor is inconsistent with the channel state during deserialization the channel will
3976 /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
3977 /// is true for missing channels as well. If there is a monitor missing for which we find
3978 /// channel data Err(DecodeError::InvalidValue) will be returned.
3980 /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3983 /// (C-not exported) because we have no HashMap bindings
3984 pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<Signer>>,
3987 impl<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
3988 ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>
3989 where M::Target: chain::Watch<Signer>,
3990 T::Target: BroadcasterInterface,
3991 K::Target: KeysInterface<Signer = Signer>,
3992 F::Target: FeeEstimator,
3995 /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
3996 /// HashMap for you. This is primarily useful for C bindings where it is not practical to
3997 /// populate a HashMap directly from C.
3998 pub fn new(keys_manager: K, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, logger: L, default_config: UserConfig,
3999 mut channel_monitors: Vec<&'a mut ChannelMonitor<Signer>>) -> Self {
4001 keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, default_config,
4002 channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
4007 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
4008 // SipmleArcChannelManager type:
4009 impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4010 ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, Arc<ChannelManager<Signer, M, T, K, F, L>>)
4011 where M::Target: chain::Watch<Signer>,
4012 T::Target: BroadcasterInterface,
4013 K::Target: KeysInterface<Signer = Signer>,
4014 F::Target: FeeEstimator,
4017 fn read<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
4018 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<Signer, M, T, K, F, L>)>::read(reader, args)?;
4019 Ok((blockhash, Arc::new(chan_manager)))
4023 impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4024 ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, ChannelManager<Signer, M, T, K, F, L>)
4025 where M::Target: chain::Watch<Signer>,
4026 T::Target: BroadcasterInterface,
4027 K::Target: KeysInterface<Signer = Signer>,
4028 F::Target: FeeEstimator,
4031 fn read<R: ::std::io::Read>(reader: &mut R, mut args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
4032 let _ver: u8 = Readable::read(reader)?;
4033 let min_ver: u8 = Readable::read(reader)?;
4034 if min_ver > SERIALIZATION_VERSION {
4035 return Err(DecodeError::UnknownVersion);
4038 let genesis_hash: BlockHash = Readable::read(reader)?;
4039 let latest_block_height: u32 = Readable::read(reader)?;
4040 let last_block_hash: BlockHash = Readable::read(reader)?;
4042 let mut failed_htlcs = Vec::new();
4044 let channel_count: u64 = Readable::read(reader)?;
4045 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
4046 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
4047 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
4048 for _ in 0..channel_count {
4049 let mut channel: Channel<Signer> = Channel::read(reader, &args.keys_manager)?;
4050 if channel.last_block_connected != Default::default() && channel.last_block_connected != last_block_hash {
4051 return Err(DecodeError::InvalidValue);
4054 let funding_txo = channel.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
4055 funding_txo_set.insert(funding_txo.clone());
4056 if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
4057 if channel.get_cur_holder_commitment_transaction_number() < monitor.get_cur_holder_commitment_number() ||
4058 channel.get_revoked_counterparty_commitment_transaction_number() < monitor.get_min_seen_secret() ||
4059 channel.get_cur_counterparty_commitment_transaction_number() < monitor.get_cur_counterparty_commitment_number() ||
4060 channel.get_latest_monitor_update_id() > monitor.get_latest_update_id() {
4061 // If the channel is ahead of the monitor, return InvalidValue:
4062 return Err(DecodeError::InvalidValue);
4063 } else if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
4064 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
4065 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
4066 channel.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
4067 // But if the channel is behind of the monitor, close the channel:
4068 let (_, _, mut new_failed_htlcs) = channel.force_shutdown(true);
4069 failed_htlcs.append(&mut new_failed_htlcs);
4070 monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
4072 if let Some(short_channel_id) = channel.get_short_channel_id() {
4073 short_to_id.insert(short_channel_id, channel.channel_id());
4075 by_id.insert(channel.channel_id(), channel);
4078 return Err(DecodeError::InvalidValue);
4082 for (ref funding_txo, ref mut monitor) in args.channel_monitors.iter_mut() {
4083 if !funding_txo_set.contains(funding_txo) {
4084 monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
4088 const MAX_ALLOC_SIZE: usize = 1024 * 64;
4089 let forward_htlcs_count: u64 = Readable::read(reader)?;
4090 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
4091 for _ in 0..forward_htlcs_count {
4092 let short_channel_id = Readable::read(reader)?;
4093 let pending_forwards_count: u64 = Readable::read(reader)?;
4094 let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
4095 for _ in 0..pending_forwards_count {
4096 pending_forwards.push(Readable::read(reader)?);
4098 forward_htlcs.insert(short_channel_id, pending_forwards);
4101 let claimable_htlcs_count: u64 = Readable::read(reader)?;
4102 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
4103 for _ in 0..claimable_htlcs_count {
4104 let payment_hash = Readable::read(reader)?;
4105 let previous_hops_len: u64 = Readable::read(reader)?;
4106 let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
4107 for _ in 0..previous_hops_len {
4108 previous_hops.push(Readable::read(reader)?);
4110 claimable_htlcs.insert(payment_hash, previous_hops);
4113 let peer_count: u64 = Readable::read(reader)?;
4114 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState>)>()));
4115 for _ in 0..peer_count {
4116 let peer_pubkey = Readable::read(reader)?;
4117 let peer_state = PeerState {
4118 latest_features: Readable::read(reader)?,
4120 per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
4123 let event_count: u64 = Readable::read(reader)?;
4124 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>()));
4125 for _ in 0..event_count {
4126 match MaybeReadable::read(reader)? {
4127 Some(event) => pending_events_read.push(event),
4132 let last_node_announcement_serial: u32 = Readable::read(reader)?;
4134 let mut secp_ctx = Secp256k1::new();
4135 secp_ctx.seeded_randomize(&args.keys_manager.get_secure_random_bytes());
4137 let channel_manager = ChannelManager {
4139 fee_estimator: args.fee_estimator,
4140 chain_monitor: args.chain_monitor,
4141 tx_broadcaster: args.tx_broadcaster,
4143 latest_block_height: AtomicUsize::new(latest_block_height as usize),
4144 last_block_hash: Mutex::new(last_block_hash),
4147 channel_state: Mutex::new(ChannelHolder {
4152 pending_msg_events: Vec::new(),
4154 our_network_key: args.keys_manager.get_node_secret(),
4156 last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
4158 per_peer_state: RwLock::new(per_peer_state),
4160 pending_events: Mutex::new(pending_events_read),
4161 total_consistency_lock: RwLock::new(()),
4162 persistence_notifier: PersistenceNotifier::new(),
4164 keys_manager: args.keys_manager,
4165 logger: args.logger,
4166 default_configuration: args.default_config,
4169 for htlc_source in failed_htlcs.drain(..) {
4170 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() });
4173 //TODO: Broadcast channel update for closed channels, but only after we've made a
4174 //connection or two.
4176 Ok((last_block_hash.clone(), channel_manager))
4182 use ln::channelmanager::PersistenceNotifier;
4184 use std::sync::atomic::{AtomicBool, Ordering};
4186 use std::time::Duration;
4189 fn test_wait_timeout() {
4190 let persistence_notifier = Arc::new(PersistenceNotifier::new());
4191 let thread_notifier = Arc::clone(&persistence_notifier);
4193 let exit_thread = Arc::new(AtomicBool::new(false));
4194 let exit_thread_clone = exit_thread.clone();
4195 thread::spawn(move || {
4197 let &(ref persist_mtx, ref cnd) = &thread_notifier.persistence_lock;
4198 let mut persistence_lock = persist_mtx.lock().unwrap();
4199 *persistence_lock = true;
4202 if exit_thread_clone.load(Ordering::SeqCst) {
4208 // Check that we can block indefinitely until updates are available.
4209 let _ = persistence_notifier.wait();
4211 // Check that the PersistenceNotifier will return after the given duration if updates are
4214 if persistence_notifier.wait_timeout(Duration::from_millis(100)) {
4219 exit_thread.store(true, Ordering::SeqCst);
4221 // Check that the PersistenceNotifier will return after the given duration even if no updates
4224 if !persistence_notifier.wait_timeout(Duration::from_millis(100)) {