// This file is Copyright its original authors, visible in version control // history. // // This file is licensed under the Apache License, Version 2.0 or the MIT license // , at your option. // You may not use this file except in accordance with one or both of these // licenses. use bitcoin::blockdata::script::{Script,Builder}; use bitcoin::blockdata::transaction::{Transaction, SigHashType}; use bitcoin::util::bip143; use bitcoin::consensus::encode; use bitcoin::hashes::Hash; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::sha256d::Hash as Sha256d; use bitcoin::hash_types::{Txid, BlockHash}; use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE; use bitcoin::secp256k1::key::{PublicKey,SecretKey}; use bitcoin::secp256k1::{Secp256k1,Signature}; use bitcoin::secp256k1; use ln::{PaymentPreimage, PaymentHash}; use ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures}; use ln::msgs; use ln::msgs::{DecodeError, OptionalField, DataLossProtect}; use ln::script::{self, ShutdownScript}; use ln::channelmanager::{CounterpartyForwardingInfo, PendingHTLCStatus, HTLCSource, HTLCFailReason, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, MAX_LOCAL_BREAKDOWN_TIMEOUT}; use ln::chan_utils::{CounterpartyCommitmentSecrets, TxCreationKeys, HTLCOutputInCommitment, HTLC_SUCCESS_TX_WEIGHT, HTLC_TIMEOUT_TX_WEIGHT, make_funding_redeemscript, ChannelPublicKeys, CommitmentTransaction, HolderCommitmentTransaction, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, MAX_HTLCS, get_commitment_transaction_number_obscure_factor, ClosingTransaction}; use ln::chan_utils; use chain::BestBlock; use chain::chaininterface::{FeeEstimator,ConfirmationTarget}; use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER}; use chain::transaction::{OutPoint, TransactionData}; use chain::keysinterface::{Sign, KeysInterface}; use util::ser::{Readable, ReadableArgs, Writeable, Writer, VecWriter}; use util::logger::Logger; use util::errors::APIError; use util::config::{UserConfig,ChannelConfig}; use util::scid_utils::scid_from_parts; use io; use prelude::*; use core::{cmp,mem,fmt}; use core::ops::Deref; #[cfg(any(test, feature = "fuzztarget", debug_assertions))] use sync::Mutex; use bitcoin::hashes::hex::ToHex; #[cfg(test)] pub struct ChannelValueStat { pub value_to_self_msat: u64, pub channel_value_msat: u64, pub channel_reserve_msat: u64, pub pending_outbound_htlcs_amount_msat: u64, pub pending_inbound_htlcs_amount_msat: u64, pub holding_cell_outbound_amount_msat: u64, pub counterparty_max_htlc_value_in_flight_msat: u64, // outgoing pub counterparty_dust_limit_msat: u64, } #[derive(Clone, Copy, PartialEq)] enum FeeUpdateState { // Inbound states mirroring InboundHTLCState RemoteAnnounced, AwaitingRemoteRevokeToAnnounce, // Note that we do not have a AwaitingAnnouncedRemoteRevoke variant here as it is universally // handled the same as `Committed`, with the only exception in `InboundHTLCState` being the // distinction of when we allow ourselves to forward the HTLC. Because we aren't "forwarding" // the fee update anywhere, we can simply consider the fee update `Committed` immediately // instead of setting it to AwaitingAnnouncedRemoteRevoke. // Outbound state can only be `LocalAnnounced` or `Committed` Outbound, } enum InboundHTLCRemovalReason { FailRelay(msgs::OnionErrorPacket), FailMalformed(([u8; 32], u16)), Fulfill(PaymentPreimage), } enum InboundHTLCState { /// Offered by remote, to be included in next local commitment tx. I.e., the remote sent an /// update_add_htlc message for this HTLC. RemoteAnnounced(PendingHTLCStatus), /// Included in a received commitment_signed message (implying we've /// revoke_and_ack'd it), but the remote hasn't yet revoked their previous /// state (see the example below). We have not yet included this HTLC in a /// commitment_signed message because we are waiting on the remote's /// aforementioned state revocation. One reason this missing remote RAA /// (revoke_and_ack) blocks us from constructing a commitment_signed message /// is because every time we create a new "state", i.e. every time we sign a /// new commitment tx (see [BOLT #2]), we need a new per_commitment_point, /// which are provided one-at-a-time in each RAA. E.g., the last RAA they /// sent provided the per_commitment_point for our current commitment tx. /// The other reason we should not send a commitment_signed without their RAA /// is because their RAA serves to ACK our previous commitment_signed. /// /// Here's an example of how an HTLC could come to be in this state: /// remote --> update_add_htlc(prev_htlc) --> local /// remote --> commitment_signed(prev_htlc) --> local /// remote <-- revoke_and_ack <-- local /// remote <-- commitment_signed(prev_htlc) <-- local /// [note that here, the remote does not respond with a RAA] /// remote --> update_add_htlc(this_htlc) --> local /// remote --> commitment_signed(prev_htlc, this_htlc) --> local /// Now `this_htlc` will be assigned this state. It's unable to be officially /// accepted, i.e. included in a commitment_signed, because we're missing the /// RAA that provides our next per_commitment_point. The per_commitment_point /// is used to derive commitment keys, which are used to construct the /// signatures in a commitment_signed message. /// Implies AwaitingRemoteRevoke. /// /// [BOLT #2]: https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md AwaitingRemoteRevokeToAnnounce(PendingHTLCStatus), /// Included in a received commitment_signed message (implying we've revoke_and_ack'd it). /// We have also included this HTLC in our latest commitment_signed and are now just waiting /// on the remote's revoke_and_ack to make this HTLC an irrevocable part of the state of the /// channel (before it can then get forwarded and/or removed). /// Implies AwaitingRemoteRevoke. AwaitingAnnouncedRemoteRevoke(PendingHTLCStatus), Committed, /// Removed by us and a new commitment_signed was sent (if we were AwaitingRemoteRevoke when we /// created it we would have put it in the holding cell instead). When they next revoke_and_ack /// we'll drop it. /// Note that we have to keep an eye on the HTLC until we've received a broadcastable /// commitment transaction without it as otherwise we'll have to force-close the channel to /// claim it before the timeout (obviously doesn't apply to revoked HTLCs that we can't claim /// anyway). That said, ChannelMonitor does this for us (see /// ChannelMonitor::should_broadcast_holder_commitment_txn) so we actually remove the HTLC from /// our own local state before then, once we're sure that the next commitment_signed and /// ChannelMonitor::provide_latest_local_commitment_tx will not include this HTLC. LocalRemoved(InboundHTLCRemovalReason), } struct InboundHTLCOutput { htlc_id: u64, amount_msat: u64, cltv_expiry: u32, payment_hash: PaymentHash, state: InboundHTLCState, } enum OutboundHTLCState { /// Added by us and included in a commitment_signed (if we were AwaitingRemoteRevoke when we /// created it we would have put it in the holding cell instead). When they next revoke_and_ack /// we will promote to Committed (note that they may not accept it until the next time we /// revoke, but we don't really care about that: /// * they've revoked, so worst case we can announce an old state and get our (option on) /// money back (though we won't), and, /// * we'll send them a revoke when they send a commitment_signed, and since only they're /// allowed to remove it, the "can only be removed once committed on both sides" requirement /// doesn't matter to us and it's up to them to enforce it, worst-case they jump ahead but /// we'll never get out of sync). /// Note that we Box the OnionPacket as it's rather large and we don't want to blow up /// OutboundHTLCOutput's size just for a temporary bit LocalAnnounced(Box), Committed, /// Remote removed this (outbound) HTLC. We're waiting on their commitment_signed to finalize /// the change (though they'll need to revoke before we fail the payment). RemoteRemoved(Option), /// Remote removed this and sent a commitment_signed (implying we've revoke_and_ack'ed it), but /// the remote side hasn't yet revoked their previous state, which we need them to do before we /// can do any backwards failing. Implies AwaitingRemoteRevoke. /// We also have not yet removed this HTLC in a commitment_signed message, and are waiting on a /// remote revoke_and_ack on a previous state before we can do so. AwaitingRemoteRevokeToRemove(Option), /// Remote removed this and sent a commitment_signed (implying we've revoke_and_ack'ed it), but /// the remote side hasn't yet revoked their previous state, which we need them to do before we /// can do any backwards failing. Implies AwaitingRemoteRevoke. /// We have removed this HTLC in our latest commitment_signed and are now just waiting on a /// revoke_and_ack to drop completely. AwaitingRemovedRemoteRevoke(Option), } struct OutboundHTLCOutput { htlc_id: u64, amount_msat: u64, cltv_expiry: u32, payment_hash: PaymentHash, state: OutboundHTLCState, source: HTLCSource, } /// See AwaitingRemoteRevoke ChannelState for more info enum HTLCUpdateAwaitingACK { AddHTLC { // TODO: Time out if we're getting close to cltv_expiry // always outbound amount_msat: u64, cltv_expiry: u32, payment_hash: PaymentHash, source: HTLCSource, onion_routing_packet: msgs::OnionPacket, }, ClaimHTLC { payment_preimage: PaymentPreimage, htlc_id: u64, }, FailHTLC { htlc_id: u64, err_packet: msgs::OnionErrorPacket, }, } /// There are a few "states" and then a number of flags which can be applied: /// We first move through init with OurInitSent -> TheirInitSent -> FundingCreated -> FundingSent. /// TheirFundingLocked and OurFundingLocked then get set on FundingSent, and when both are set we /// move on to ChannelFunded. /// Note that PeerDisconnected can be set on both ChannelFunded and FundingSent. /// ChannelFunded can then get all remaining flags set on it, until we finish shutdown, then we /// move on to ShutdownComplete, at which point most calls into this channel are disallowed. enum ChannelState { /// Implies we have (or are prepared to) send our open_channel/accept_channel message OurInitSent = 1 << 0, /// Implies we have received their open_channel/accept_channel message TheirInitSent = 1 << 1, /// We have sent funding_created and are awaiting a funding_signed to advance to FundingSent. /// Note that this is nonsense for an inbound channel as we immediately generate funding_signed /// upon receipt of funding_created, so simply skip this state. FundingCreated = 4, /// Set when we have received/sent funding_created and funding_signed and are thus now waiting /// on the funding transaction to confirm. The FundingLocked flags are set to indicate when we /// and our counterparty consider the funding transaction confirmed. FundingSent = 8, /// Flag which can be set on FundingSent to indicate they sent us a funding_locked message. /// Once both TheirFundingLocked and OurFundingLocked are set, state moves on to ChannelFunded. TheirFundingLocked = 1 << 4, /// Flag which can be set on FundingSent to indicate we sent them a funding_locked message. /// Once both TheirFundingLocked and OurFundingLocked are set, state moves on to ChannelFunded. OurFundingLocked = 1 << 5, ChannelFunded = 64, /// Flag which is set on ChannelFunded and FundingSent indicating remote side is considered /// "disconnected" and no updates are allowed until after we've done a channel_reestablish /// dance. PeerDisconnected = 1 << 7, /// Flag which is set on ChannelFunded, FundingCreated, and FundingSent indicating the user has /// told us they failed to update our ChannelMonitor somewhere and we should pause sending any /// outbound messages until they've managed to do so. MonitorUpdateFailed = 1 << 8, /// Flag which implies that we have sent a commitment_signed but are awaiting the responding /// revoke_and_ack message. During this time period, we can't generate new commitment_signed /// messages as then we will be unable to determine which HTLCs they included in their /// revoke_and_ack implicit ACK, so instead we have to hold them away temporarily to be sent /// later. /// Flag is set on ChannelFunded. AwaitingRemoteRevoke = 1 << 9, /// Flag which is set on ChannelFunded or FundingSent after receiving a shutdown message from /// the remote end. If set, they may not add any new HTLCs to the channel, and we are expected /// to respond with our own shutdown message when possible. RemoteShutdownSent = 1 << 10, /// Flag which is set on ChannelFunded or FundingSent after sending a shutdown message. At this /// point, we may not add any new HTLCs to the channel. LocalShutdownSent = 1 << 11, /// We've successfully negotiated a closing_signed dance. At this point ChannelManager is about /// to drop us, but we store this anyway. ShutdownComplete = 4096, } const BOTH_SIDES_SHUTDOWN_MASK: u32 = ChannelState::LocalShutdownSent as u32 | ChannelState::RemoteShutdownSent as u32; const MULTI_STATE_FLAGS: u32 = BOTH_SIDES_SHUTDOWN_MASK | ChannelState::PeerDisconnected as u32 | ChannelState::MonitorUpdateFailed as u32; pub const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1; /// The "channel disabled" bit in channel_update must be set based on whether we are connected to /// our counterparty or not. However, we don't want to announce updates right away to avoid /// spamming the network with updates if the connection is flapping. Instead, we "stage" updates to /// our channel_update message and track the current state here. /// See implementation at [`super::channelmanager::ChannelManager::timer_tick_occurred`]. #[derive(Clone, Copy, PartialEq)] pub(super) enum ChannelUpdateStatus { /// We've announced the channel as enabled and are connected to our peer. Enabled, /// Our channel is no longer live, but we haven't announced the channel as disabled yet. DisabledStaged, /// Our channel is live again, but we haven't announced the channel as enabled yet. EnabledStaged, /// We've announced the channel as disabled. Disabled, } /// An enum indicating whether the local or remote side offered a given HTLC. enum HTLCInitiator { LocalOffered, RemoteOffered, } /// An enum gathering stats on pending HTLCs, either inbound or outbound side. struct HTLCStats { pending_htlcs: u32, pending_htlcs_value_msat: u64, on_counterparty_tx_dust_exposure_msat: u64, on_holder_tx_dust_exposure_msat: u64, } /// Used when calculating whether we or the remote can afford an additional HTLC. struct HTLCCandidate { amount_msat: u64, origin: HTLCInitiator, } impl HTLCCandidate { fn new(amount_msat: u64, origin: HTLCInitiator) -> Self { Self { amount_msat, origin, } } } /// A return value enum for get_update_fulfill_htlc. See UpdateFulfillCommitFetch variants for /// description enum UpdateFulfillFetch { NewClaim { monitor_update: ChannelMonitorUpdate, htlc_value_msat: u64, msg: Option, }, DuplicateClaim {}, } /// The return type of get_update_fulfill_htlc_and_commit. pub enum UpdateFulfillCommitFetch { /// Indicates the HTLC fulfill is new, and either generated an update_fulfill message, placed /// it in the holding cell, or re-generated the update_fulfill message after the same claim was /// previously placed in the holding cell (and has since been removed). NewClaim { /// The ChannelMonitorUpdate which places the new payment preimage in the channel monitor monitor_update: ChannelMonitorUpdate, /// The value of the HTLC which was claimed, in msat. htlc_value_msat: u64, /// The update_fulfill message and commitment_signed message (if the claim was not placed /// in the holding cell). msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)>, }, /// Indicates the HTLC fulfill is duplicative and already existed either in the holding cell /// or has been forgotten (presumably previously claimed). DuplicateClaim {}, } /// The return value of `revoke_and_ack` on success, primarily updates to other channels or HTLC /// state. pub(super) struct RAAUpdates { pub commitment_update: Option, pub accepted_htlcs: Vec<(PendingHTLCInfo, u64)>, pub failed_htlcs: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>, pub finalized_claimed_htlcs: Vec, pub monitor_update: ChannelMonitorUpdate, pub holding_cell_failed_htlcs: Vec<(HTLCSource, PaymentHash)>, } /// The return value of `monitor_updating_restored` pub(super) struct MonitorRestoreUpdates { pub raa: Option, pub commitment_update: Option, pub order: RAACommitmentOrder, pub accepted_htlcs: Vec<(PendingHTLCInfo, u64)>, pub failed_htlcs: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>, pub finalized_claimed_htlcs: Vec, pub funding_broadcastable: Option, pub funding_locked: Option, } /// If the majority of the channels funds are to the fundee and the initiator holds only just /// enough funds to cover their reserve value, channels are at risk of getting "stuck". Because the /// initiator controls the feerate, if they then go to increase the channel fee, they may have no /// balance but the fundee is unable to send a payment as the increase in fee more than drains /// their reserve value. Thus, neither side can send a new HTLC and the channel becomes useless. /// Thus, before sending an HTLC when we are the initiator, we check that the feerate can increase /// by this multiple without hitting this case, before sending. /// This multiple is effectively the maximum feerate "jump" we expect until more HTLCs flow over /// the channel. Sadly, there isn't really a good number for this - if we expect to have no new /// HTLCs for days we may need this to suffice for feerate increases across days, but that may /// leave the channel less usable as we hold a bigger reserve. #[cfg(fuzzing)] pub const FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE: u64 = 2; #[cfg(not(fuzzing))] const FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE: u64 = 2; // TODO: We should refactor this to be an Inbound/OutboundChannel until initial setup handshaking // has been completed, and then turn into a Channel to get compiler-time enforcement of things like // calling channel_id() before we're set up or things like get_outbound_funding_signed on an // inbound channel. // // Holder designates channel data owned for the benefice of the user client. // Counterparty designates channel data owned by the another channel participant entity. pub(super) struct Channel { #[cfg(any(test, feature = "_test_utils"))] pub(crate) config: ChannelConfig, #[cfg(not(any(test, feature = "_test_utils")))] config: ChannelConfig, user_id: u64, channel_id: [u8; 32], channel_state: u32, secp_ctx: Secp256k1, channel_value_satoshis: u64, latest_monitor_update_id: u64, holder_signer: Signer, shutdown_scriptpubkey: Option, destination_script: Script, // Our commitment numbers start at 2^48-1 and count down, whereas the ones used in transaction // generation start at 0 and count up...this simplifies some parts of implementation at the // cost of others, but should really just be changed. cur_holder_commitment_transaction_number: u64, cur_counterparty_commitment_transaction_number: u64, value_to_self_msat: u64, // Excluding all pending_htlcs, excluding fees pending_inbound_htlcs: Vec, pending_outbound_htlcs: Vec, holding_cell_htlc_updates: Vec, /// When resending CS/RAA messages on channel monitor restoration or on reconnect, we always /// need to ensure we resend them in the order we originally generated them. Note that because /// there can only ever be one in-flight CS and/or one in-flight RAA at any time, it is /// sufficient to simply set this to the opposite of any message we are generating as we /// generate it. ie when we generate a CS, we set this to RAAFirst as, if there is a pending /// in-flight RAA to resend, it will have been the first thing we generated, and thus we should /// send it first. resend_order: RAACommitmentOrder, monitor_pending_funding_locked: bool, monitor_pending_revoke_and_ack: bool, monitor_pending_commitment_signed: bool, monitor_pending_forwards: Vec<(PendingHTLCInfo, u64)>, monitor_pending_failures: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>, monitor_pending_finalized_fulfills: Vec, // pending_update_fee is filled when sending and receiving update_fee. // // Because it follows the same commitment flow as HTLCs, `FeeUpdateState` is either `Outbound` // or matches a subset of the `InboundHTLCOutput` variants. It is then updated/used when // generating new commitment transactions with exactly the same criteria as inbound/outbound // HTLCs with similar state. pending_update_fee: Option<(u32, FeeUpdateState)>, // If a `send_update_fee()` call is made with ChannelState::AwaitingRemoteRevoke set, we place // it here instead of `pending_update_fee` in the same way as we place outbound HTLC updates in // `holding_cell_htlc_updates` instead of `pending_outbound_htlcs`. It is released into // `pending_update_fee` with the same criteria as outbound HTLC updates but can be updated by // further `send_update_fee` calls, dropping the previous holding cell update entirely. holding_cell_update_fee: Option, next_holder_htlc_id: u64, next_counterparty_htlc_id: u64, update_time_counter: u32, feerate_per_kw: u32, #[cfg(debug_assertions)] /// Max to_local and to_remote outputs in a locally-generated commitment transaction holder_max_commitment_tx_output: Mutex<(u64, u64)>, #[cfg(debug_assertions)] /// Max to_local and to_remote outputs in a remote-generated commitment transaction counterparty_max_commitment_tx_output: Mutex<(u64, u64)>, last_sent_closing_fee: Option<(u64, Signature)>, // (fee, holder_sig) target_closing_feerate_sats_per_kw: Option, /// If our counterparty sent us a closing_signed while we were waiting for a `ChannelMonitor` /// update, we need to delay processing it until later. We do that here by simply storing the /// closing_signed message and handling it in `maybe_propose_closing_signed`. pending_counterparty_closing_signed: Option, /// The minimum and maximum absolute fee, in satoshis, we are willing to place on the closing /// transaction. These are set once we reach `closing_negotiation_ready`. #[cfg(test)] pub(crate) closing_fee_limits: Option<(u64, u64)>, #[cfg(not(test))] closing_fee_limits: Option<(u64, u64)>, /// The hash of the block in which the funding transaction was included. funding_tx_confirmed_in: Option, funding_tx_confirmation_height: u32, short_channel_id: Option, counterparty_dust_limit_satoshis: u64, #[cfg(test)] pub(super) holder_dust_limit_satoshis: u64, #[cfg(not(test))] holder_dust_limit_satoshis: u64, #[cfg(test)] pub(super) counterparty_max_htlc_value_in_flight_msat: u64, #[cfg(not(test))] counterparty_max_htlc_value_in_flight_msat: u64, //get_holder_max_htlc_value_in_flight_msat(): u64, /// minimum channel reserve for self to maintain - set by them. counterparty_selected_channel_reserve_satoshis: Option, // get_holder_selected_channel_reserve_satoshis(channel_value_sats: u64): u64 counterparty_htlc_minimum_msat: u64, holder_htlc_minimum_msat: u64, #[cfg(test)] pub counterparty_max_accepted_htlcs: u16, #[cfg(not(test))] counterparty_max_accepted_htlcs: u16, //implied by OUR_MAX_HTLCS: max_accepted_htlcs: u16, minimum_depth: Option, counterparty_forwarding_info: Option, pub(crate) channel_transaction_parameters: ChannelTransactionParameters, funding_transaction: Option, counterparty_cur_commitment_point: Option, counterparty_prev_commitment_point: Option, counterparty_node_id: PublicKey, counterparty_shutdown_scriptpubkey: Option