X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fln%2Fchannel.rs;h=c34fc6a38c28e5ae89a5cd98e094ee7a5348781a;hb=8e7b29160ba19b971d25b66938693cecacc5993c;hp=35e688a0d765db059182575134bd39d21f85b86f;hpb=29199fae4634425eb4307651b3b21d93580c8f42;p=rust-lightning diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index 35e688a0..c34fc6a3 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -1,41 +1,48 @@ +// 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::block::BlockHeader; use bitcoin::blockdata::script::{Script,Builder}; use bitcoin::blockdata::transaction::{TxIn, TxOut, Transaction, SigHashType}; use bitcoin::blockdata::opcodes; -use bitcoin::util::hash::BitcoinHash; use bitcoin::util::bip143; use bitcoin::consensus::encode; -use bitcoin_hashes::{Hash, HashEngine}; -use bitcoin_hashes::sha256::Hash as Sha256; -use bitcoin_hashes::hash160::Hash as Hash160; -use bitcoin_hashes::sha256d::Hash as Sha256dHash; +use bitcoin::hashes::{Hash, HashEngine}; +use bitcoin::hashes::sha256::Hash as Sha256; +use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash}; -use secp256k1::key::{PublicKey,SecretKey}; -use secp256k1::{Secp256k1,Signature}; -use secp256k1; +use bitcoin::secp256k1::key::{PublicKey,SecretKey}; +use bitcoin::secp256k1::{Secp256k1,Signature}; +use bitcoin::secp256k1; use ln::features::{ChannelFeatures, InitFeatures}; use ln::msgs; use ln::msgs::{DecodeError, OptionalField, DataLossProtect}; -use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER}; use ln::channelmanager::{PendingHTLCStatus, HTLCSource, HTLCFailReason, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT}; -use ln::chan_utils::{CounterpartyCommitmentSecrets, LocalCommitmentTransaction, TxCreationKeys, HTLCOutputInCommitment, HTLC_SUCCESS_TX_WEIGHT, HTLC_TIMEOUT_TX_WEIGHT, make_funding_redeemscript, ChannelPublicKeys}; +use ln::chan_utils::{CounterpartyCommitmentSecrets, HolderCommitmentTransaction, TxCreationKeys, HTLCOutputInCommitment, HTLC_SUCCESS_TX_WEIGHT, HTLC_TIMEOUT_TX_WEIGHT, make_funding_redeemscript, ChannelPublicKeys, PreCalculatedTxCreationKeys}; use ln::chan_utils; use chain::chaininterface::{FeeEstimator,ConfirmationTarget}; -use chain::transaction::OutPoint; +use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER}; +use chain::transaction::{OutPoint, TransactionData}; use chain::keysinterface::{ChannelKeys, KeysInterface}; use util::transaction_utils; -use util::ser::{Readable, ReadableArgs, Writeable, Writer}; -use util::logger::{Logger, LogHolder}; +use util::ser::{Readable, Writeable, Writer}; +use util::logger::Logger; use util::errors::APIError; use util::config::{UserConfig,ChannelConfig}; use std; use std::default::Default; use std::{cmp,mem,fmt}; -use std::sync::{Arc}; use std::ops::Deref; +use bitcoin::hashes::hex::ToHex; #[cfg(test)] pub struct ChannelValueStat { @@ -45,7 +52,8 @@ pub struct ChannelValueStat { pub pending_outbound_htlcs_amount_msat: u64, pub pending_inbound_htlcs_amount_msat: u64, pub holding_cell_outbound_amount_msat: u64, - pub their_max_htlc_value_in_flight_msat: u64, // outgoing + pub counterparty_max_htlc_value_in_flight_msat: u64, // outgoing + pub counterparty_dust_limit_msat: u64, } enum InboundHTLCRemovalReason { @@ -55,19 +63,43 @@ enum InboundHTLCRemovalReason { } enum InboundHTLCState { - /// Added by remote, to be included in next local commitment tx. + /// 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'ed it), but - /// the remote side hasn't yet revoked their previous state, which we need them to do before we - /// accept this HTLC. Implies AwaitingRemoteRevoke. - /// We also have not yet included 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. + /// 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'ed it), but - /// the remote side hasn't yet revoked their previous state, which we need them to do before we - /// accept this HTLC. Implies AwaitingRemoteRevoke. - /// We have included this HTLC in our latest commitment_signed and are now just waiting on a - /// revoke_and_ack. + /// 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 @@ -161,9 +193,9 @@ enum HTLCUpdateAwaitingACK { /// 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), + OurInitSent = 1 << 0, /// Implies we have received their open_channel/accept_channel message - TheirInitSent = (1 << 1), + 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. @@ -174,35 +206,35 @@ enum ChannelState { 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), + 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), + 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), + 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), + 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), + 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), + 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. /// TODO: Investigate some kind of timeout mechanism by which point the remote end must provide /// us their shutdown. - LocalShutdownSent = (1 << 11), + 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, @@ -230,6 +262,9 @@ enum UpdateStatus { // 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 { config: ChannelConfig, @@ -244,9 +279,9 @@ pub(super) struct Channel { latest_monitor_update_id: u64, #[cfg(not(test))] - local_keys: ChanSigner, + holder_keys: ChanSigner, #[cfg(test)] - pub(super) local_keys: ChanSigner, + pub(super) holder_keys: ChanSigner, shutdown_pubkey: PublicKey, destination_script: Script, @@ -254,8 +289,8 @@ pub(super) struct Channel { // 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_local_commitment_transaction_number: u64, - cur_remote_commitment_transaction_number: u64, + 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, @@ -287,25 +322,25 @@ pub(super) struct Channel { // revoke_and_ack is received and new commitment_signed is generated to be // sent to the funder. Otherwise, the pending value is removed when receiving // commitment_signed. - pending_update_fee: Option, + pending_update_fee: Option, // update_fee() during ChannelState::AwaitingRemoteRevoke is hold in // holdina_cell_update_fee then moved to pending_udpate_fee when revoke_and_ack // is received. holding_cell_update_fee is updated when there are additional // update_fee() during ChannelState::AwaitingRemoteRevoke. - holding_cell_update_fee: Option, - next_local_htlc_id: u64, - next_remote_htlc_id: u64, + holding_cell_update_fee: Option, + next_holder_htlc_id: u64, + next_counterparty_htlc_id: u64, update_time_counter: u32, - feerate_per_kw: u64, + feerate_per_kw: u32, #[cfg(debug_assertions)] /// Max to_local and to_remote outputs in a locally-generated commitment transaction - max_commitment_tx_output_local: ::std::sync::Mutex<(u64, u64)>, + holder_max_commitment_tx_output: ::std::sync::Mutex<(u64, u64)>, #[cfg(debug_assertions)] /// Max to_local and to_remote outputs in a remote-generated commitment transaction - max_commitment_tx_output_remote: ::std::sync::Mutex<(u64, u64)>, + counterparty_max_commitment_tx_output: ::std::sync::Mutex<(u64, u64)>, - last_sent_closing_fee: Option<(u64, u64, Signature)>, // (feerate, fee, our_sig) + last_sent_closing_fee: Option<(u32, u64, Signature)>, // (feerate, fee, holder_sig) funding_txo: Option, @@ -313,54 +348,49 @@ pub(super) struct Channel { /// to detect unconfirmation after a serialize-unserialize roundtrip where we may not see a full /// series of block_connected/block_disconnected calls. Obviously this is not a guarantee as we /// could miss the funding_tx_confirmed_in block as well, but it serves as a useful fallback. - funding_tx_confirmed_in: Option, + funding_tx_confirmed_in: Option, short_channel_id: Option, /// Used to deduplicate block_connected callbacks, also used to verify consistency during /// ChannelManager deserialization (hence pub(super)) - pub(super) last_block_connected: Sha256dHash, + pub(super) last_block_connected: BlockHash, funding_tx_confirmations: u64, - their_dust_limit_satoshis: u64, + counterparty_dust_limit_satoshis: u64, #[cfg(test)] - pub(super) our_dust_limit_satoshis: u64, + pub(super) holder_dust_limit_satoshis: u64, #[cfg(not(test))] - our_dust_limit_satoshis: u64, + holder_dust_limit_satoshis: u64, #[cfg(test)] - pub(super) their_max_htlc_value_in_flight_msat: u64, + pub(super) counterparty_max_htlc_value_in_flight_msat: u64, #[cfg(not(test))] - their_max_htlc_value_in_flight_msat: u64, - //get_our_max_htlc_value_in_flight_msat(): u64, - /// minimum channel reserve for **self** to maintain - set by them. - their_channel_reserve_satoshis: u64, - //get_our_channel_reserve_satoshis(): u64, - their_htlc_minimum_msat: u64, - our_htlc_minimum_msat: u64, - their_to_self_delay: u16, - our_to_self_delay: u16, + 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: u64, + // get_holder_selected_channel_reserve_satoshis(channel_value_sats: u64): u64 + counterparty_htlc_minimum_msat: u64, + holder_htlc_minimum_msat: u64, + counterparty_selected_contest_delay: u16, + holder_selected_contest_delay: u16, #[cfg(test)] - pub their_max_accepted_htlcs: u16, + pub counterparty_max_accepted_htlcs: u16, #[cfg(not(test))] - their_max_accepted_htlcs: u16, - //implied by OUR_MAX_HTLCS: our_max_accepted_htlcs: u16, + counterparty_max_accepted_htlcs: u16, + //implied by OUR_MAX_HTLCS: max_accepted_htlcs: u16, minimum_depth: u32, - their_pubkeys: Option, + counterparty_pubkeys: Option, - their_cur_commitment_point: Option, + counterparty_cur_commitment_point: Option, - their_prev_commitment_point: Option, - their_node_id: PublicKey, + counterparty_prev_commitment_point: Option, + counterparty_node_id: PublicKey, - their_shutdown_scriptpubkey: Option