Fix max fee_satoshis constant to be 21 million, not 2.1 million.
[rust-lightning] / lightning / src / ln / channel.rs
index 394016a126724bcbe8b675ed0f6cb5c0567d4ded..407c9adbce55d8aa094736e545a2f81c5e1b448e 100644 (file)
@@ -25,12 +25,12 @@ 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, PreCalculatedTxCreationKeys};
+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, Writeable, Writer};
@@ -262,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<ChanSigner: ChannelKeys> {
        config: ChannelConfig,
 
@@ -990,7 +993,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        txouts.push((TxOut {
                                script_pubkey: chan_utils::get_revokeable_redeemscript(&keys.revocation_key,
                                                                                       if local { self.counterparty_selected_contest_delay } else { self.holder_selected_contest_delay },
-                                                                                      &keys.delayed_payment_key).to_v0_p2wsh(),
+                                                                                      &keys.broadcaster_delayed_payment_key).to_v0_p2wsh(),
                                value: value_to_a as u64
                        }, None));
                }
@@ -1153,7 +1156,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        /// @local is used only to convert relevant internal structures which refer to remote vs local
        /// to decide value of outputs and direction of HTLCs.
        fn build_htlc_transaction(&self, prev_hash: &Txid, htlc: &HTLCOutputInCommitment, local: bool, keys: &TxCreationKeys, feerate_per_kw: u32) -> Transaction {
-               chan_utils::build_htlc_transaction(prev_hash, feerate_per_kw, if local { self.counterparty_selected_contest_delay } else { self.holder_selected_contest_delay }, htlc, &keys.delayed_payment_key, &keys.revocation_key)
+               chan_utils::build_htlc_transaction(prev_hash, feerate_per_kw, if local { self.counterparty_selected_contest_delay } else { self.holder_selected_contest_delay }, htlc, &keys.broadcaster_delayed_payment_key, &keys.revocation_key)
        }
 
        /// Per HTLC, only one get_update_fail_htlc or get_update_fulfill_htlc call may be made.
@@ -1471,7 +1474,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                Ok(())
        }
 
-       fn funding_created_signature<L: Deref>(&mut self, sig: &Signature, logger: &L) -> Result<(Transaction, LocalCommitmentTransaction, Signature), ChannelError> where L::Target: Logger {
+       fn funding_created_signature<L: Deref>(&mut self, sig: &Signature, logger: &L) -> Result<(Transaction, HolderCommitmentTransaction, Signature), ChannelError> where L::Target: Logger {
                let funding_script = self.get_funding_redeemscript();
 
                let keys = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number)?;
@@ -1482,12 +1485,12 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                log_trace!(logger, "Checking funding_created tx signature {} by key {} against tx {} (sighash {}) with redeemscript {}", log_bytes!(sig.serialize_compact()[..]), log_bytes!(self.counterparty_funding_pubkey().serialize()), encode::serialize_hex(&initial_commitment_tx), log_bytes!(sighash[..]), encode::serialize_hex(&funding_script));
                secp_check!(self.secp_ctx.verify(&sighash, &sig, self.counterparty_funding_pubkey()), "Invalid funding_created signature from peer".to_owned());
 
-               let tx = LocalCommitmentTransaction::new_missing_local_sig(initial_commitment_tx, sig.clone(), &self.holder_keys.pubkeys().funding_pubkey, self.counterparty_funding_pubkey(), keys, self.feerate_per_kw, Vec::new());
+               let tx = HolderCommitmentTransaction::new_missing_holder_sig(initial_commitment_tx, sig.clone(), &self.holder_keys.pubkeys().funding_pubkey, self.counterparty_funding_pubkey(), keys, self.feerate_per_kw, Vec::new());
 
                let counterparty_keys = self.build_remote_transaction_keys()?;
                let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, false, self.feerate_per_kw, logger).0;
                let pre_remote_keys = PreCalculatedTxCreationKeys::new(counterparty_keys);
-               let counterparty_signature = self.holder_keys.sign_remote_commitment(self.feerate_per_kw, &counterparty_initial_commitment_tx, &pre_remote_keys, &Vec::new(), &self.secp_ctx)
+               let counterparty_signature = self.holder_keys.sign_counterparty_commitment(self.feerate_per_kw, &counterparty_initial_commitment_tx, &pre_remote_keys, &Vec::new(), &self.secp_ctx)
                                .map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed".to_owned()))?.0;
 
                // We sign "counterparty" commitment transaction, allowing them to broadcast the tx if they wish.
@@ -1540,7 +1543,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                                                                              self.get_commitment_transaction_number_obscure_factor(),
                                                                              initial_commitment_tx.clone());
 
-                               channel_monitor.provide_latest_remote_commitment_tx_info(&counterparty_initial_commitment_tx, Vec::new(), self.cur_counterparty_commitment_transaction_number, self.counterparty_cur_commitment_point.unwrap(), logger);
+                               channel_monitor.provide_latest_counterparty_commitment_tx_info(&counterparty_initial_commitment_tx, Vec::new(), self.cur_counterparty_commitment_transaction_number, self.counterparty_cur_commitment_point.unwrap(), logger);
                                channel_monitor
                        } }
                }
@@ -1595,7 +1598,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                let funding_txo_script = funding_redeemscript.to_v0_p2wsh();
                macro_rules! create_monitor {
                        () => { {
-                               let commitment_tx = LocalCommitmentTransaction::new_missing_local_sig(initial_commitment_tx.clone(), msg.signature.clone(), &self.holder_keys.pubkeys().funding_pubkey, counterparty_funding_pubkey, holder_keys.clone(), self.feerate_per_kw, Vec::new());
+                               let commitment_tx = HolderCommitmentTransaction::new_missing_holder_sig(initial_commitment_tx.clone(), msg.signature.clone(), &self.holder_keys.pubkeys().funding_pubkey, counterparty_funding_pubkey, holder_keys.clone(), self.feerate_per_kw, Vec::new());
                                let mut channel_monitor = ChannelMonitor::new(self.holder_keys.clone(),
                                                                              &self.shutdown_pubkey, self.holder_selected_contest_delay,
                                                                              &self.destination_script, (funding_txo.clone(), funding_txo_script.clone()),
@@ -1604,7 +1607,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                                                                              self.get_commitment_transaction_number_obscure_factor(),
                                                                              commitment_tx);
 
-                               channel_monitor.provide_latest_remote_commitment_tx_info(&counterparty_initial_commitment_tx, Vec::new(), self.cur_counterparty_commitment_transaction_number, self.counterparty_cur_commitment_point.unwrap(), logger);
+                               channel_monitor.provide_latest_counterparty_commitment_tx_info(&counterparty_initial_commitment_tx, Vec::new(), self.cur_counterparty_commitment_transaction_number, self.counterparty_cur_commitment_point.unwrap(), logger);
 
                                channel_monitor
                        } }
@@ -2045,8 +2048,8 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                self.latest_monitor_update_id += 1;
                let mut monitor_update = ChannelMonitorUpdate {
                        update_id: self.latest_monitor_update_id,
-                       updates: vec![ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo {
-                               commitment_tx: LocalCommitmentTransaction::new_missing_local_sig(commitment_tx.0, msg.signature.clone(), &self.holder_keys.pubkeys().funding_pubkey, &counterparty_funding_pubkey, keys, self.feerate_per_kw, htlcs_without_source),
+                       updates: vec![ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo {
+                               commitment_tx: HolderCommitmentTransaction::new_missing_holder_sig(commitment_tx.0, msg.signature.clone(), &self.holder_keys.pubkeys().funding_pubkey, &counterparty_funding_pubkey, keys, self.feerate_per_kw, htlcs_without_source),
                                htlc_outputs: htlcs_and_sigs
                        }]
                };
@@ -3004,7 +3007,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                if !self.pending_inbound_htlcs.is_empty() || !self.pending_outbound_htlcs.is_empty() {
                        return Err(ChannelError::Close("Remote end sent us a closing_signed while there were still pending HTLCs".to_owned()));
                }
-               if msg.fee_satoshis > 21000000 * 10000000 { //this is required to stop potential overflow in build_closing_transaction
+               if msg.fee_satoshis > 21_000_000 * 1_0000_0000 { //this is required to stop potential overflow in build_closing_transaction
                        return Err(ChannelError::Close("Remote tried to send us a closing tx with > 21 million BTC fee".to_owned()));
                }
 
@@ -3122,6 +3125,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        }
 
        /// Allowed in any state (including after shutdown)
+       #[cfg(test)]
        pub fn get_holder_htlc_minimum_msat(&self) -> u64 {
                self.holder_htlc_minimum_msat
        }
@@ -3140,7 +3144,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
 
        /// Allowed in any state (including after shutdown)
        pub fn get_counterparty_htlc_minimum_msat(&self) -> u64 {
-               self.holder_htlc_minimum_msat
+               self.counterparty_htlc_minimum_msat
        }
 
        pub fn get_value_satoshis(&self) -> u64 {
@@ -3164,7 +3168,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                self.cur_counterparty_commitment_transaction_number + 1 - if self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32) != 0 { 1 } else { 0 }
        }
 
-       pub fn get_revoked_remote_commitment_transaction_number(&self) -> u64 {
+       pub fn get_revoked_counterparty_commitment_transaction_number(&self) -> u64 {
                self.cur_counterparty_commitment_transaction_number + 2
        }
 
@@ -3311,7 +3315,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        ///
        /// May return some HTLCs (and their payment_hash) which have timed out and should be failed
        /// back.
-       pub fn block_connected(&mut self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[usize]) -> Result<(Option<msgs::FundingLocked>, Vec<(HTLCSource, PaymentHash)>), msgs::ErrorMessage> {
+       pub fn block_connected(&mut self, header: &BlockHeader, txdata: &TransactionData, height: u32) -> Result<(Option<msgs::FundingLocked>, Vec<(HTLCSource, PaymentHash)>), msgs::ErrorMessage> {
                let mut timed_out_htlcs = Vec::new();
                self.holding_cell_htlc_updates.retain(|htlc_update| {
                        match htlc_update {
@@ -3331,7 +3335,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        }
                }
                if non_shutdown_state & !(ChannelState::TheirFundingLocked as u32) == ChannelState::FundingSent as u32 {
-                       for (ref tx, index_in_block) in txn_matched.iter().zip(indexes_of_txn_matched) {
+                       for &(index_in_block, tx) in txdata.iter() {
                                if tx.txid() == self.funding_txo.unwrap().txid {
                                        let txo_idx = self.funding_txo.unwrap().index as usize;
                                        if txo_idx >= tx.output.len() || tx.output[txo_idx].script_pubkey != self.get_funding_redeemscript().to_v0_p2wsh() ||
@@ -3362,14 +3366,14 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                                                                }
                                                        }
                                                }
-                                               if height > 0xff_ff_ff || (*index_in_block) > 0xff_ff_ff {
+                                               if height > 0xff_ff_ff || (index_in_block) > 0xff_ff_ff {
                                                        panic!("Block was bogus - either height 16 million or had > 16 million transactions");
                                                }
                                                assert!(txo_idx <= 0xffff); // txo_idx is a (u16 as usize), so this is just listed here for completeness
                                                self.funding_tx_confirmations = 1;
-                                               self.short_channel_id = Some(((height as u64)          << (5*8)) |
-                                                                            ((*index_in_block as u64) << (2*8)) |
-                                                                            ((txo_idx as u64)         << (0*8)));
+                                               self.short_channel_id = Some(((height as u64)         << (5*8)) |
+                                                                            ((index_in_block as u64) << (2*8)) |
+                                                                            ((txo_idx as u64)        << (0*8)));
                                        }
                                }
                        }
@@ -3517,7 +3521,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                let counterparty_keys = self.build_remote_transaction_keys()?;
                let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, false, self.feerate_per_kw, logger).0;
                let pre_remote_keys = PreCalculatedTxCreationKeys::new(counterparty_keys);
-               Ok(self.holder_keys.sign_remote_commitment(self.feerate_per_kw, &counterparty_initial_commitment_tx, &pre_remote_keys, &Vec::new(), &self.secp_ctx)
+               Ok(self.holder_keys.sign_counterparty_commitment(self.feerate_per_kw, &counterparty_initial_commitment_tx, &pre_remote_keys, &Vec::new(), &self.secp_ctx)
                                .map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed".to_owned()))?.0)
        }
 
@@ -3838,7 +3842,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                self.latest_monitor_update_id += 1;
                let monitor_update = ChannelMonitorUpdate {
                        update_id: self.latest_monitor_update_id,
-                       updates: vec![ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo {
+                       updates: vec![ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo {
                                unsigned_commitment_tx: counterparty_commitment_tx.clone(),
                                htlc_outputs: htlcs.clone(),
                                commitment_number: self.cur_counterparty_commitment_transaction_number,
@@ -3870,7 +3874,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        }
 
                        let pre_remote_keys = PreCalculatedTxCreationKeys::new(counterparty_keys);
-                       let res = self.holder_keys.sign_remote_commitment(feerate_per_kw, &counterparty_commitment_tx.0, &pre_remote_keys, &htlcs, &self.secp_ctx)
+                       let res = self.holder_keys.sign_counterparty_commitment(feerate_per_kw, &counterparty_commitment_tx.0, &pre_remote_keys, &htlcs, &self.secp_ctx)
                                .map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed".to_owned()))?;
                        signature = res.0;
                        htlc_signatures = res.1;
@@ -3883,7 +3887,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
 
                        for (ref htlc_sig, ref htlc) in htlc_signatures.iter().zip(htlcs) {
                                log_trace!(logger, "Signed remote HTLC tx {} with redeemscript {} with pubkey {} -> {}",
-                                       encode::serialize_hex(&chan_utils::build_htlc_transaction(&counterparty_commitment_tx.0.txid(), feerate_per_kw, self.holder_selected_contest_delay, htlc, &counterparty_keys.delayed_payment_key, &counterparty_keys.revocation_key)),
+                                       encode::serialize_hex(&chan_utils::build_htlc_transaction(&counterparty_commitment_tx.0.txid(), feerate_per_kw, self.holder_selected_contest_delay, htlc, &counterparty_keys.broadcaster_delayed_payment_key, &counterparty_keys.revocation_key)),
                                        encode::serialize_hex(&chan_utils::get_htlc_redeemscript(&htlc, counterparty_keys)),
                                        log_bytes!(counterparty_keys.broadcaster_htlc_key.serialize()),
                                        log_bytes!(htlc_sig.serialize_compact()[..]));
@@ -4464,7 +4468,7 @@ mod tests {
        use ln::features::InitFeatures;
        use ln::msgs::{OptionalField, DataLossProtect};
        use ln::chan_utils;
-       use ln::chan_utils::{LocalCommitmentTransaction, ChannelPublicKeys};
+       use ln::chan_utils::{HolderCommitmentTransaction, ChannelPublicKeys};
        use chain::chaininterface::{FeeEstimator,ConfirmationTarget};
        use chain::keysinterface::{InMemoryChannelKeys, KeysInterface};
        use chain::transaction::OutPoint;
@@ -4676,7 +4680,7 @@ mod tests {
 
                let mut unsigned_tx: (Transaction, Vec<HTLCOutputInCommitment>);
 
-               let mut localtx;
+               let mut holdertx;
                macro_rules! test_commitment {
                        ( $counterparty_sig_hex: expr, $sig_hex: expr, $tx_hex: expr, {
                                $( { $htlc_idx: expr, $counterparty_htlc_sig_hex: expr, $htlc_sig_hex: expr, $htlc_tx_hex: expr } ), *
@@ -4701,15 +4705,15 @@ mod tests {
                                })*
                                assert_eq!(unsigned_tx.1.len(), per_htlc.len());
 
-                               localtx = LocalCommitmentTransaction::new_missing_local_sig(unsigned_tx.0.clone(), counterparty_signature.clone(), &chan_keys.pubkeys().funding_pubkey, chan.counterparty_funding_pubkey(), keys.clone(), chan.feerate_per_kw, per_htlc);
-                               let local_sig = chan_keys.sign_local_commitment(&localtx, &chan.secp_ctx).unwrap();
-                               assert_eq!(Signature::from_der(&hex::decode($sig_hex).unwrap()[..]).unwrap(), local_sig);
+                               holdertx = HolderCommitmentTransaction::new_missing_holder_sig(unsigned_tx.0.clone(), counterparty_signature.clone(), &chan_keys.pubkeys().funding_pubkey, chan.counterparty_funding_pubkey(), keys.clone(), chan.feerate_per_kw, per_htlc);
+                               let holder_sig = chan_keys.sign_holder_commitment(&holdertx, &chan.secp_ctx).unwrap();
+                               assert_eq!(Signature::from_der(&hex::decode($sig_hex).unwrap()[..]).unwrap(), holder_sig);
 
-                               assert_eq!(serialize(&localtx.add_local_sig(&redeemscript, local_sig))[..],
+                               assert_eq!(serialize(&holdertx.add_holder_sig(&redeemscript, holder_sig))[..],
                                                hex::decode($tx_hex).unwrap()[..]);
 
-                               let htlc_sigs = chan_keys.sign_local_commitment_htlc_transactions(&localtx, &chan.secp_ctx).unwrap();
-                               let mut htlc_sig_iter = localtx.per_htlc.iter().zip(htlc_sigs.iter().enumerate());
+                               let htlc_sigs = chan_keys.sign_holder_commitment_htlc_transactions(&holdertx, &chan.secp_ctx).unwrap();
+                               let mut htlc_sig_iter = holdertx.per_htlc.iter().zip(htlc_sigs.iter().enumerate());
 
                                $({
                                        let remote_signature = Signature::from_der(&hex::decode($counterparty_htlc_sig_hex).unwrap()[..]).unwrap();
@@ -4738,7 +4742,7 @@ mod tests {
 
                                        let signature = Signature::from_der(&hex::decode($htlc_sig_hex).unwrap()[..]).unwrap();
                                        assert_eq!(Some(signature), *(htlc_sig.1).1);
-                                       assert_eq!(serialize(&localtx.get_signed_htlc_tx((htlc_sig.1).0, &(htlc_sig.1).1.unwrap(), &preimage, chan.counterparty_selected_contest_delay))[..],
+                                       assert_eq!(serialize(&holdertx.get_signed_htlc_tx((htlc_sig.1).0, &(htlc_sig.1).1.unwrap(), &preimage, chan.counterparty_selected_contest_delay))[..],
                                                        hex::decode($htlc_tx_hex).unwrap()[..]);
                                })*
                                loop {