Skip to content

Commit b5de93b

Browse files
committed
Drop duplicative current-local-tx storage in channel.
We now have current-local-tx broadcast ability in channel monitors directly (for ChannelManager deserialization), so we can just use that instead of always having the Channel store signed ready-to-go copies of the latest local commitment transaction. This is further kinda nice since ChannelMonitor is live and can, eg broadcast HTLC-Success transactions immediately as they will be generated at broadcast time instead of in advance. Finally, this lets us clean up a tiny bit in Channel.
1 parent 4ebe64f commit b5de93b

File tree

4 files changed

+91
-108
lines changed

4 files changed

+91
-108
lines changed

lightning/src/ln/channel.rs

Lines changed: 10 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use bitcoin::blockdata::transaction::{TxIn, TxOut, Transaction, SigHashType};
44
use bitcoin::blockdata::opcodes;
55
use bitcoin::util::hash::BitcoinHash;
66
use bitcoin::util::bip143;
7-
use bitcoin::consensus::encode::{self, Encodable, Decodable};
7+
use bitcoin::consensus::encode;
88

99
use bitcoin_hashes::{Hash, HashEngine};
1010
use bitcoin_hashes::sha256::Hash as Sha256;
@@ -25,7 +25,7 @@ use chain::chaininterface::{FeeEstimator,ConfirmationTarget};
2525
use chain::transaction::OutPoint;
2626
use chain::keysinterface::{ChannelKeys, KeysInterface};
2727
use util::transaction_utils;
28-
use util::ser::{Readable, ReadableArgs, Writeable, Writer, WriterWriteAdaptor};
28+
use util::ser::{Readable, ReadableArgs, Writeable, Writer};
2929
use util::logger::{Logger, LogHolder};
3030
use util::errors::APIError;
3131
use util::config::{UserConfig,ChannelConfig};
@@ -297,12 +297,6 @@ pub(super) struct Channel<ChanSigner: ChannelKeys> {
297297
/// Max to_local and to_remote outputs in a remote-generated commitment transaction
298298
max_commitment_tx_output_remote: ::std::sync::Mutex<(u64, u64)>,
299299

300-
#[cfg(test)]
301-
// Used in ChannelManager's tests to send a revoked transaction
302-
pub last_local_commitment_txn: Vec<Transaction>,
303-
#[cfg(not(test))]
304-
last_local_commitment_txn: Vec<Transaction>,
305-
306300
last_sent_closing_fee: Option<(u64, u64, Signature)>, // (feerate, fee, our_sig)
307301

308302
/// The hash of the block in which the funding transaction reached our CONF_TARGET. We use this
@@ -498,8 +492,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
498492
#[cfg(debug_assertions)]
499493
max_commitment_tx_output_remote: ::std::sync::Mutex::new((channel_value_satoshis * 1000 - push_msat, push_msat)),
500494

501-
last_local_commitment_txn: Vec::new(),
502-
503495
last_sent_closing_fee: None,
504496

505497
funding_tx_confirmed_in: None,
@@ -716,8 +708,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
716708
#[cfg(debug_assertions)]
717709
max_commitment_tx_output_remote: ::std::sync::Mutex::new((msg.push_msat, msg.funding_satoshis * 1000 - msg.push_msat)),
718710

719-
last_local_commitment_txn: Vec::new(),
720-
721711
last_sent_closing_fee: None,
722712

723713
funding_tx_confirmed_in: None,
@@ -1185,8 +1175,10 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
11851175
Ok((htlc_redeemscript, self.secp_ctx.sign(&sighash, &our_htlc_key), is_local_tx))
11861176
}
11871177

1178+
#[cfg(test)]
11881179
/// Signs a transaction created by build_htlc_transaction. If the transaction is an
11891180
/// HTLC-Success transaction (ie htlc.offered is false), preimage must be set!
1181+
/// TODO: Make this a chan_utils, use it in channelmonitor and tests, cause its unused now
11901182
fn sign_htlc_transaction(&self, tx: &mut Transaction, their_sig: &Signature, preimage: &Option<PaymentPreimage>, htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Result<Signature, ChannelError> {
11911183
if tx.input.len() != 1 {
11921184
panic!("Tried to sign HTLC transaction that had input count != 1!");
@@ -1556,7 +1548,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
15561548
// Now that we're past error-generating stuff, update our local state:
15571549

15581550
self.channel_monitor.provide_latest_remote_commitment_tx_info(&remote_initial_commitment_tx, Vec::new(), self.cur_remote_commitment_transaction_number, self.their_cur_commitment_point.unwrap());
1559-
self.last_local_commitment_txn = vec![local_initial_commitment_tx.clone()];
15601551
self.channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx, local_keys, self.feerate_per_kw, Vec::new());
15611552
self.channel_state = ChannelState::FundingSent as u32;
15621553
self.channel_id = funding_txo.to_channel_id();
@@ -1594,8 +1585,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
15941585
secp_check!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid funding_signed signature from peer");
15951586

15961587
self.sign_commitment_transaction(&mut local_initial_commitment_tx, &msg.signature);
1597-
self.channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx.clone(), local_keys, self.feerate_per_kw, Vec::new());
1598-
self.last_local_commitment_txn = vec![local_initial_commitment_tx];
1588+
self.channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx, local_keys, self.feerate_per_kw, Vec::new());
15991589
self.channel_state = ChannelState::FundingSent as u32 | (self.channel_state & (ChannelState::MonitorUpdateFailed as u32));
16001590
self.cur_local_commitment_transaction_number -= 1;
16011591

@@ -1859,25 +1849,17 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
18591849
return Err(ChannelError::Close("Got wrong number of HTLC signatures from remote"));
18601850
}
18611851

1862-
let mut new_local_commitment_txn = Vec::with_capacity(local_commitment_tx.1 + 1);
18631852
self.sign_commitment_transaction(&mut local_commitment_tx.0, &msg.signature);
1864-
new_local_commitment_txn.push(local_commitment_tx.0.clone());
18651853

18661854
let mut htlcs_and_sigs = Vec::with_capacity(local_commitment_tx.2.len());
18671855
for (idx, (htlc, source)) in local_commitment_tx.2.drain(..).enumerate() {
18681856
if let Some(_) = htlc.transaction_output_index {
1869-
let mut htlc_tx = self.build_htlc_transaction(&local_commitment_txid, &htlc, true, &local_keys, feerate_per_kw);
1857+
let htlc_tx = self.build_htlc_transaction(&local_commitment_txid, &htlc, true, &local_keys, feerate_per_kw);
18701858
let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &local_keys);
18711859
log_trace!(self, "Checking HTLC tx signature {} by key {} against tx {} with redeemscript {}", log_bytes!(msg.htlc_signatures[idx].serialize_compact()[..]), log_bytes!(local_keys.b_htlc_key.serialize()), encode::serialize_hex(&htlc_tx), encode::serialize_hex(&htlc_redeemscript));
18721860
let htlc_sighash = hash_to_message!(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]);
18731861
secp_check!(self.secp_ctx.verify(&htlc_sighash, &msg.htlc_signatures[idx], &local_keys.b_htlc_key), "Invalid HTLC tx signature from peer");
1874-
let htlc_sig = if htlc.offered {
1875-
let htlc_sig = self.sign_htlc_transaction(&mut htlc_tx, &msg.htlc_signatures[idx], &None, &htlc, &local_keys)?;
1876-
new_local_commitment_txn.push(htlc_tx);
1877-
htlc_sig
1878-
} else {
1879-
self.create_htlc_tx_signature(&htlc_tx, &htlc, &local_keys)?.1
1880-
};
1862+
let htlc_sig = self.create_htlc_tx_signature(&htlc_tx, &htlc, &local_keys)?.1;
18811863
htlcs_and_sigs.push((htlc, Some((msg.htlc_signatures[idx], htlc_sig)), source));
18821864
} else {
18831865
htlcs_and_sigs.push((htlc, None, source));
@@ -1923,7 +1905,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
19231905
}
19241906

19251907
self.cur_local_commitment_transaction_number -= 1;
1926-
self.last_local_commitment_txn = new_local_commitment_txn;
19271908
// Note that if we need_our_commitment & !AwaitingRemoteRevoke we'll call
19281909
// send_commitment_no_status_check() next which will reset this to RAAFirst.
19291910
self.resend_order = RAACommitmentOrder::CommitmentFirst;
@@ -2881,11 +2862,11 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
28812862
}
28822863

28832864
/// May only be called after funding has been initiated (ie is_funding_initiated() is true)
2884-
pub fn channel_monitor(&self) -> ChannelMonitor {
2865+
pub fn channel_monitor(&self) -> &ChannelMonitor {
28852866
if self.channel_state < ChannelState::FundingCreated as u32 {
28862867
panic!("Can't get a channel monitor until funding has been created");
28872868
}
2888-
self.channel_monitor.clone()
2869+
&self.channel_monitor
28892870
}
28902871

28912872
/// Guaranteed to be Some after both FundingLocked messages have been exchanged (and, thus,
@@ -3681,9 +3662,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
36813662

36823663
self.channel_state = ChannelState::ShutdownComplete as u32;
36833664
self.channel_update_count += 1;
3684-
let mut res = Vec::new();
3685-
mem::swap(&mut res, &mut self.last_local_commitment_txn);
3686-
(res, dropped_outbound_htlcs)
3665+
(self.channel_monitor.get_latest_local_commitment_txn(), dropped_outbound_htlcs)
36873666
}
36883667
}
36893668

@@ -3873,16 +3852,6 @@ impl<ChanSigner: ChannelKeys + Writeable> Writeable for Channel<ChanSigner> {
38733852
self.channel_update_count.write(writer)?;
38743853
self.feerate_per_kw.write(writer)?;
38753854

3876-
(self.last_local_commitment_txn.len() as u64).write(writer)?;
3877-
for tx in self.last_local_commitment_txn.iter() {
3878-
if let Err(e) = tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
3879-
match e {
3880-
encode::Error::Io(e) => return Err(e),
3881-
_ => panic!("last_local_commitment_txn must have been well-formed!"),
3882-
}
3883-
}
3884-
}
3885-
38863855
match self.last_sent_closing_fee {
38873856
Some((feerate, fee, sig)) => {
38883857
1u8.write(writer)?;
@@ -4041,15 +4010,6 @@ impl<R : ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>> ReadableArgs<R,
40414010
let channel_update_count = Readable::read(reader)?;
40424011
let feerate_per_kw = Readable::read(reader)?;
40434012

4044-
let last_local_commitment_txn_count: u64 = Readable::read(reader)?;
4045-
let mut last_local_commitment_txn = Vec::with_capacity(cmp::min(last_local_commitment_txn_count as usize, OUR_MAX_HTLCS as usize*2 + 1));
4046-
for _ in 0..last_local_commitment_txn_count {
4047-
last_local_commitment_txn.push(match Transaction::consensus_decode(reader.by_ref()) {
4048-
Ok(tx) => tx,
4049-
Err(_) => return Err(DecodeError::InvalidValue),
4050-
});
4051-
}
4052-
40534013
let last_sent_closing_fee = match <u8 as Readable<R>>::read(reader)? {
40544014
0 => None,
40554015
1 => Some((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?)),
@@ -4132,8 +4092,6 @@ impl<R : ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>> ReadableArgs<R,
41324092
#[cfg(debug_assertions)]
41334093
max_commitment_tx_output_remote: ::std::sync::Mutex::new((0, 0)),
41344094

4135-
last_local_commitment_txn,
4136-
41374095
last_sent_closing_fee,
41384096

41394097
funding_tx_confirmed_in,

lightning/src/ln/channelmanager.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1791,7 +1791,7 @@ impl<'a, ChanSigner: ChannelKeys> ChannelManager<'a, ChanSigner> {
17911791
let pending_msg_events = channel_state.pending_msg_events;
17921792
channel_state.by_id.retain(|_, channel| {
17931793
if channel.is_awaiting_monitor_update() {
1794-
let chan_monitor = channel.channel_monitor();
1794+
let chan_monitor = channel.channel_monitor().clone();
17951795
if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
17961796
match e {
17971797
ChannelMonitorUpdateErr::PermanentFailure => {

lightning/src/ln/channelmonitor.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2316,6 +2316,7 @@ impl ChannelMonitor {
23162316
/// out-of-band the other node operator to coordinate with him if option is available to you.
23172317
/// In any-case, choice is up to the user.
23182318
pub fn get_latest_local_commitment_txn(&self) -> Vec<Transaction> {
2319+
log_trace!(self, "Getting signed latest local commitment transaction!");
23192320
if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
23202321
let mut res = vec![local_tx.tx.clone()];
23212322
match self.key_storage {

0 commit comments

Comments
 (0)