Skip to content

Commit 39d99ed

Browse files
committed
Remove unnecessary funding tx clone & remote tx_sigs received check
We actually don't need to check if the counterparty had already sent their `tx_signatures` in `InteractiveTxSigningSession::received_tx_signatures`. Further, we can get rid of the clone of `funding_tx_opt` in `Channel::tx_signatures` when setting the `Context::funding_transaction` as we don't actually need to propagate it through to `ChannelManager::internal_tx_complete` as we can use `ChannelContext::unbroadcasted_funding()` which clones the `ChannelContext::funding_transaction` anyway.
1 parent 92ff728 commit 39d99ed

File tree

5 files changed

+98
-61
lines changed

5 files changed

+98
-61
lines changed

lightning/src/ln/channel.rs

Lines changed: 33 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2186,6 +2186,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
21862186
context: self.context,
21872187
interactive_tx_signing_session: Some(signing_session),
21882188
holder_commitment_point,
2189+
is_v2_established: true,
21892190
};
21902191
Ok((funded_chan, commitment_signed, funding_ready_for_sig_event))
21912192
},
@@ -4540,6 +4541,9 @@ pub(super) struct FundedChannel<SP: Deref> where SP::Target: SignerProvider {
45404541
pub context: ChannelContext<SP>,
45414542
pub interactive_tx_signing_session: Option<InteractiveTxSigningSession>,
45424543
holder_commitment_point: HolderCommitmentPoint,
4544+
/// Indicates whether this funded channel had been established with V2 channel
4545+
/// establishment (i.e. is a dual-funded channel).
4546+
is_v2_established: bool,
45434547
}
45444548

45454549
#[cfg(any(test, fuzzing))]
@@ -5994,10 +5998,10 @@ impl<SP: Deref> FundedChannel<SP> where
59945998
}
59955999
}
59966000

5997-
pub fn tx_signatures<L: Deref>(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<(Option<msgs::TxSignatures>, Option<Transaction>), ChannelError>
6001+
pub fn tx_signatures<L: Deref>(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<Option<msgs::TxSignatures>, ChannelError>
59986002
where L::Target: Logger
59996003
{
6000-
if !matches!(self.context.channel_state, ChannelState::FundingNegotiated) {
6004+
if !matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(_)) {
60016005
return Err(ChannelError::close("Received tx_signatures in strange state!".to_owned()));
60026006
}
60036007

@@ -6031,25 +6035,23 @@ impl<SP: Deref> FundedChannel<SP> where
60316035
// for spending. Doesn't seem to be anything in rust-bitcoin.
60326036
}
60336037

6034-
let (tx_signatures_opt, funding_tx_opt) = signing_session.received_tx_signatures(msg.clone())
6038+
let (holder_tx_signatures_opt, funding_tx_opt) = signing_session.received_tx_signatures(msg.clone())
60356039
.map_err(|_| ChannelError::Warn("Witness count did not match contributed input count".to_string()))?;
6040+
if holder_tx_signatures_opt.is_some() && self.is_awaiting_initial_mon_persist() {
6041+
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress. Setting monitor_pending_tx_signatures.");
6042+
self.context.monitor_pending_tx_signatures = holder_tx_signatures_opt;
6043+
return Ok(None);
6044+
}
60366045
if funding_tx_opt.is_some() {
6046+
// We have a persisted channel monitor and and a finalized funding transaction, so we can move
6047+
// the channel state forward, set the funding transaction and reset the signing session fields.
6048+
self.context.funding_transaction = funding_tx_opt;
6049+
self.context.next_funding_txid = None;
6050+
self.interactive_tx_signing_session = None;
60376051
self.context.channel_state = ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::new());
60386052
}
6039-
self.context.funding_transaction = funding_tx_opt.clone();
6040-
6041-
self.context.next_funding_txid = None;
6042-
6043-
// Clear out the signing session
6044-
self.interactive_tx_signing_session = None;
6045-
6046-
if tx_signatures_opt.is_some() && self.context.channel_state.is_monitor_update_in_progress() {
6047-
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress. Setting monitor_pending_tx_signatures.");
6048-
self.context.monitor_pending_tx_signatures = tx_signatures_opt;
6049-
return Ok((None, None));
6050-
}
60516053

6052-
Ok((tx_signatures_opt, funding_tx_opt))
6054+
Ok(holder_tx_signatures_opt)
60536055
} else {
60546056
Err(ChannelError::Close((
60556057
"Unexpected tx_signatures. No funding transaction awaiting signatures".to_string(),
@@ -6252,12 +6254,12 @@ impl<SP: Deref> FundedChannel<SP> where
62526254
assert!(self.context.channel_state.is_monitor_update_in_progress());
62536255
self.context.channel_state.clear_monitor_update_in_progress();
62546256

6255-
// If we're past (or at) the AwaitingChannelReady stage on an outbound channel, try to
6256-
// (re-)broadcast the funding transaction as we may have declined to broadcast it when we
6257+
// If we're past (or at) the AwaitingChannelReady stage on an outbound (or V2-established) channel,
6258+
// try to (re-)broadcast the funding transaction as we may have declined to broadcast it when we
62576259
// first received the funding_signed.
62586260
let mut funding_broadcastable = None;
62596261
if let Some(funding_transaction) = &self.context.funding_transaction {
6260-
if self.context.is_outbound() &&
6262+
if (self.context.is_outbound() || self.is_v2_established()) &&
62616263
(matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(flags) if !flags.is_set(AwaitingChannelReadyFlags::WAITING_FOR_BATCH)) ||
62626264
matches!(self.context.channel_state, ChannelState::ChannelReady(_)))
62636265
{
@@ -8549,6 +8551,10 @@ impl<SP: Deref> FundedChannel<SP> where
85498551
})
85508552
.chain(self.context.pending_outbound_htlcs.iter().map(|htlc| (&htlc.source, &htlc.payment_hash)))
85518553
}
8554+
8555+
pub fn is_v2_established(&self) -> bool {
8556+
self.is_v2_established
8557+
}
85528558
}
85538559

85548560
/// A not-yet-funded outbound (from holder) channel using V1 channel establishment.
@@ -8812,6 +8818,7 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
88128818
let mut channel = FundedChannel {
88138819
context: self.context,
88148820
interactive_tx_signing_session: None,
8821+
is_v2_established: false,
88158822
holder_commitment_point,
88168823
};
88178824

@@ -9077,6 +9084,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
90779084
let mut channel = FundedChannel {
90789085
context: self.context,
90799086
interactive_tx_signing_session: None,
9087+
is_v2_established: false,
90809088
holder_commitment_point,
90819089
};
90829090
let need_channel_ready = channel.check_get_channel_ready(0, logger).is_some()
@@ -9885,7 +9893,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
98859893
let mut _val: u64 = Readable::read(reader)?;
98869894
}
98879895

9888-
let channel_id = Readable::read(reader)?;
9896+
let channel_id: ChannelId = Readable::read(reader)?;
98899897
let channel_state = ChannelState::from_u32(Readable::read(reader)?).map_err(|_| DecodeError::InvalidValue)?;
98909898
let channel_value_satoshis = Readable::read(reader)?;
98919899

@@ -10321,6 +10329,10 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
1032110329
}
1032210330
},
1032310331
};
10332+
let is_v2_established = channel_id.is_v2_channel_id(
10333+
&channel_parameters.holder_pubkeys.revocation_basepoint,
10334+
&channel_parameters.counterparty_parameters.as_ref()
10335+
.expect("Persisted channel must have counterparty parameters").pubkeys.revocation_basepoint);
1032410336

1032510337
Ok(FundedChannel {
1032610338
context: ChannelContext {
@@ -10458,6 +10470,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
1045810470
next_funding_txid: None,
1045910471
},
1046010472
interactive_tx_signing_session: None,
10473+
is_v2_established,
1046110474
holder_commitment_point,
1046210475
})
1046310476
}

lightning/src/ln/channelmanager.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8362,14 +8362,14 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
83628362
match chan_entry.get_mut().as_funded_mut() {
83638363
Some(chan) => {
83648364
let logger = WithChannelContext::from(&self.logger, &chan.context, None);
8365-
let (tx_signatures_opt, funding_tx_opt) = try_channel_entry!(self, peer_state, chan.tx_signatures(msg, &&logger), chan_entry);
8365+
let tx_signatures_opt = try_channel_entry!(self, peer_state, chan.tx_signatures(msg, &&logger), chan_entry);
83668366
if let Some(tx_signatures) = tx_signatures_opt {
83678367
peer_state.pending_msg_events.push(events::MessageSendEvent::SendTxSignatures {
83688368
node_id: *counterparty_node_id,
83698369
msg: tx_signatures,
83708370
});
83718371
}
8372-
if let Some(ref funding_tx) = funding_tx_opt {
8372+
if let Some(ref funding_tx) = chan.context.unbroadcasted_funding() {
83738373
self.tx_broadcaster.broadcast_transactions(&[funding_tx]);
83748374
{
83758375
let mut pending_events = self.pending_events.lock().unwrap();

lightning/src/ln/dual_funding_tests.rs

Lines changed: 34 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use {
2323
crate::ln::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint, RevocationBasepoint},
2424
crate::ln::functional_test_utils::*,
2525
crate::ln::msgs::ChannelMessageHandler,
26-
crate::ln::msgs::{CommitmentSigned, TxAddInput, TxAddOutput, TxComplete},
26+
crate::ln::msgs::{CommitmentSigned, TxAddInput, TxAddOutput, TxComplete, TxSignatures},
2727
crate::ln::types::ChannelId,
2828
crate::prelude::*,
2929
crate::sign::{ChannelSigner as _, P2WPKH_WITNESS_WEIGHT},
@@ -41,9 +41,9 @@ struct V2ChannelEstablishmentTestSession {
4141
#[cfg(dual_funding)]
4242
// TODO(dual_funding): Use real node and API for creating V2 channels as initiator when available,
4343
// instead of manually constructing messages.
44-
fn do_test_v2_channel_establishment(
45-
session: V2ChannelEstablishmentTestSession, test_async_persist: bool,
46-
) {
44+
fn do_test_v2_channel_establishment(session: V2ChannelEstablishmentTestSession) {
45+
use bitcoin::Witness;
46+
4747
let chanmon_cfgs = create_chanmon_cfgs(2);
4848
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4949
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
@@ -210,34 +210,23 @@ fn do_test_v2_channel_establishment(
210210
partial_signature_with_nonce: None,
211211
};
212212

213-
if test_async_persist {
214-
chanmon_cfgs[1]
215-
.persister
216-
.set_update_ret(crate::chain::ChannelMonitorUpdateStatus::InProgress);
217-
}
213+
chanmon_cfgs[1].persister.set_update_ret(crate::chain::ChannelMonitorUpdateStatus::InProgress);
218214

219215
// Handle the initial commitment_signed exchange. Order is not important here.
220216
nodes[1]
221217
.node
222218
.handle_commitment_signed(nodes[0].node.get_our_node_id(), &msg_commitment_signed_from_0);
223219
check_added_monitors(&nodes[1], 1);
224220

225-
if test_async_persist {
226-
let events = nodes[1].node.get_and_clear_pending_events();
227-
assert!(events.is_empty());
221+
// The funding transaction should not have been broadcast before persisting initial monitor has
222+
// been completed.
223+
assert_eq!(nodes[1].tx_broadcaster.txn_broadcast().len(), 0);
224+
assert_eq!(nodes[1].node.get_and_clear_pending_events().len(), 0);
228225

229-
chanmon_cfgs[1]
230-
.persister
231-
.set_update_ret(crate::chain::ChannelMonitorUpdateStatus::Completed);
232-
let (outpoint, latest_update, _) = *nodes[1]
233-
.chain_monitor
234-
.latest_monitor_update_id
235-
.lock()
236-
.unwrap()
237-
.get(&channel_id)
238-
.unwrap();
239-
nodes[1].chain_monitor.chain_monitor.force_channel_monitor_updated(outpoint, latest_update);
240-
}
226+
// Complete the persistence of the monitor.
227+
let events = nodes[1].node.get_and_clear_pending_events();
228+
assert!(events.is_empty());
229+
nodes[1].chain_monitor.complete_sole_pending_chan_update(&channel_id);
241230

242231
let events = nodes[1].node.get_and_clear_pending_events();
243232
assert_eq!(events.len(), 1);
@@ -253,19 +242,30 @@ fn do_test_v2_channel_establishment(
253242
);
254243

255244
assert_eq!(tx_signatures_msg.channel_id, channel_id);
245+
246+
let mut witness = Witness::new();
247+
witness.push([0x0]);
248+
// Receive tx_signatures from channel initiator.
249+
nodes[1].node.handle_tx_signatures(
250+
nodes[0].node.get_our_node_id(),
251+
&TxSignatures {
252+
channel_id,
253+
tx_hash: funding_outpoint.unwrap().txid,
254+
witnesses: vec![witness],
255+
shared_input_signature: None,
256+
},
257+
);
258+
259+
// For an inbound channel V2 channel the transaction should be broadcast once receiving a
260+
// tx_signature and applying local tx_signatures:
261+
let broadcasted_txs = nodes[1].tx_broadcaster.txn_broadcast();
262+
assert_eq!(broadcasted_txs.len(), 1);
256263
}
257264

258265
#[test]
259266
#[cfg(dual_funding)]
260267
fn test_v2_channel_establishment() {
261-
// Only initiator contributes, no persist pending
262-
do_test_v2_channel_establishment(
263-
V2ChannelEstablishmentTestSession { initiator_input_value_satoshis: 100_000 },
264-
false,
265-
);
266-
// Only initiator contributes, persist pending
267-
do_test_v2_channel_establishment(
268-
V2ChannelEstablishmentTestSession { initiator_input_value_satoshis: 100_000 },
269-
true,
270-
);
268+
do_test_v2_channel_establishment(V2ChannelEstablishmentTestSession {
269+
initiator_input_value_satoshis: 100_000,
270+
});
271271
}

lightning/src/ln/interactivetxs.rs

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -316,14 +316,18 @@ impl InteractiveTxSigningSession {
316316

317317
/// Handles a `tx_signatures` message received from the counterparty.
318318
///
319+
/// If the holder is required to send their `tx_signatures` message and these signatures have
320+
/// already been provided to the signing session, then this return value will be `Some`, otherwise
321+
/// None.
322+
///
323+
/// If the holder has already provided their `tx_signatures` to the signing session, a funding
324+
/// transaction will be finalized and returned as Some, otherwise None.
325+
///
319326
/// Returns an error if the witness count does not equal the counterparty's input count in the
320327
/// unsigned transaction.
321328
pub fn received_tx_signatures(
322329
&mut self, tx_signatures: TxSignatures,
323330
) -> Result<(Option<TxSignatures>, Option<Transaction>), ()> {
324-
if self.counterparty_sent_tx_signatures {
325-
return Ok((None, None));
326-
};
327331
if self.remote_inputs_count() != tx_signatures.witnesses.len() {
328332
return Err(());
329333
}
@@ -336,13 +340,16 @@ impl InteractiveTxSigningSession {
336340
None
337341
};
338342

339-
let funding_tx = if self.holder_tx_signatures.is_some() {
343+
// Check if the holder has provided its signatures and if so,
344+
// return the finalized funding transaction.
345+
let funding_tx_opt = if self.holder_tx_signatures.is_some() {
340346
Some(self.finalize_funding_tx())
341347
} else {
348+
// This means we're still waiting for the holder to provide their signatures.
342349
None
343350
};
344351

345-
Ok((holder_tx_signatures, funding_tx))
352+
Ok((holder_tx_signatures, funding_tx_opt))
346353
}
347354

348355
/// Provides the holder witnesses for the unsigned transaction.

lightning/src/ln/types.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,11 @@ impl ChannelId {
101101
pub fn temporary_v2_from_revocation_basepoint(our_revocation_basepoint: &RevocationBasepoint) -> Self {
102102
Self(Sha256::hash(&[[0u8; 33], our_revocation_basepoint.0.serialize()].concat()).to_byte_array())
103103
}
104+
105+
/// Indicates whether this is a V2 channel ID for the given local and remote revocation basepoints.
106+
pub fn is_v2_channel_id(&self, ours: &RevocationBasepoint, theirs: &RevocationBasepoint) -> bool {
107+
*self == Self::v2_from_revocation_basepoints(ours, theirs)
108+
}
104109
}
105110

106111
impl Writeable for ChannelId {
@@ -211,4 +216,16 @@ mod tests {
211216

212217
assert_eq!(ChannelId::v2_from_revocation_basepoints(&ours, &theirs), expected_id);
213218
}
219+
220+
#[test]
221+
fn test_is_v2_channel_id() {
222+
let ours = RevocationBasepoint(PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap());
223+
let theirs = RevocationBasepoint(PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap());
224+
225+
let channel_id = ChannelId::v2_from_revocation_basepoints(&ours, &theirs);
226+
assert!(channel_id.is_v2_channel_id(&ours, &theirs));
227+
228+
let channel_id = ChannelId::v1_from_funding_txid(&[2; 32], 1);
229+
assert!(!channel_id.is_v2_channel_id(&ours, &theirs))
230+
}
214231
}

0 commit comments

Comments
 (0)