Skip to content

Commit 6da9ef4

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 `FundedChannel::tx_signatures` when setting the `ChannelContext::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 eb18913 commit 6da9ef4

File tree

5 files changed

+100
-68
lines changed

5 files changed

+100
-68
lines changed

lightning/src/ln/channel.rs

+33-18
Original file line numberDiff line numberDiff line change
@@ -2280,6 +2280,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
22802280
context: self.context,
22812281
interactive_tx_signing_session: Some(signing_session),
22822282
holder_commitment_point,
2283+
is_v2_established: true,
22832284
};
22842285
Ok((funded_chan, commitment_signed, funding_ready_for_sig_event))
22852286
},
@@ -4645,6 +4646,9 @@ pub(super) struct FundedChannel<SP: Deref> where SP::Target: SignerProvider {
46454646
pub context: ChannelContext<SP>,
46464647
pub interactive_tx_signing_session: Option<InteractiveTxSigningSession>,
46474648
holder_commitment_point: HolderCommitmentPoint,
4649+
/// Indicates whether this funded channel had been established with V2 channel
4650+
/// establishment (i.e. is a dual-funded channel).
4651+
is_v2_established: bool,
46484652
}
46494653

46504654
#[cfg(any(test, fuzzing))]
@@ -6125,10 +6129,10 @@ impl<SP: Deref> FundedChannel<SP> where
61256129
}
61266130
}
61276131

6128-
pub fn tx_signatures<L: Deref>(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<(Option<msgs::TxSignatures>, Option<Transaction>), ChannelError>
6132+
pub fn tx_signatures<L: Deref>(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<Option<msgs::TxSignatures>, ChannelError>
61296133
where L::Target: Logger
61306134
{
6131-
if !matches!(self.context.channel_state, ChannelState::FundingNegotiated) {
6135+
if !matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(_)) {
61326136
return Err(ChannelError::close("Received tx_signatures in strange state!".to_owned()));
61336137
}
61346138

@@ -6162,25 +6166,25 @@ impl<SP: Deref> FundedChannel<SP> where
61626166
// for spending. Doesn't seem to be anything in rust-bitcoin.
61636167
}
61646168

6165-
let (tx_signatures_opt, funding_tx_opt) = signing_session.received_tx_signatures(msg.clone())
6169+
let (holder_tx_signatures_opt, funding_tx_opt) = signing_session.received_tx_signatures(msg.clone())
61666170
.map_err(|_| ChannelError::Warn("Witness count did not match contributed input count".to_string()))?;
6167-
if funding_tx_opt.is_some() {
6168-
self.context.channel_state = ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::new());
6169-
}
6170-
self.context.funding_transaction = funding_tx_opt.clone();
61716171

6172-
self.context.next_funding_txid = None;
61736172

6174-
// Clear out the signing session
6175-
self.interactive_tx_signing_session = None;
6173+
if funding_tx_opt.is_some() {
6174+
// We have a finalized funding transaction, so we can set the funding transaction and reset the
6175+
// signing session fields.
6176+
self.context.funding_transaction = funding_tx_opt;
6177+
self.context.next_funding_txid = None;
6178+
self.interactive_tx_signing_session = None;
6179+
}
61766180

6177-
if tx_signatures_opt.is_some() && self.context.channel_state.is_monitor_update_in_progress() {
6181+
if holder_tx_signatures_opt.is_some() && self.is_awaiting_initial_mon_persist() {
61786182
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress. Setting monitor_pending_tx_signatures.");
6179-
self.context.monitor_pending_tx_signatures = tx_signatures_opt;
6180-
return Ok((None, None));
6183+
self.context.monitor_pending_tx_signatures = holder_tx_signatures_opt;
6184+
return Ok(None);
61816185
}
61826186

6183-
Ok((tx_signatures_opt, funding_tx_opt))
6187+
Ok(holder_tx_signatures_opt)
61846188
} else {
61856189
Err(ChannelError::Close((
61866190
"Unexpected tx_signatures. No funding transaction awaiting signatures".to_string(),
@@ -6397,12 +6401,12 @@ impl<SP: Deref> FundedChannel<SP> where
63976401
assert!(self.context.channel_state.is_monitor_update_in_progress());
63986402
self.context.channel_state.clear_monitor_update_in_progress();
63996403

6400-
// If we're past (or at) the AwaitingChannelReady stage on an outbound channel, try to
6401-
// (re-)broadcast the funding transaction as we may have declined to broadcast it when we
6404+
// If we're past (or at) the AwaitingChannelReady stage on an outbound (or V2-established) channel,
6405+
// try to (re-)broadcast the funding transaction as we may have declined to broadcast it when we
64026406
// first received the funding_signed.
64036407
let mut funding_broadcastable = None;
64046408
if let Some(funding_transaction) = &self.context.funding_transaction {
6405-
if self.context.is_outbound() &&
6409+
if (self.context.is_outbound() || self.is_v2_established()) &&
64066410
(matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(flags) if !flags.is_set(AwaitingChannelReadyFlags::WAITING_FOR_BATCH)) ||
64076411
matches!(self.context.channel_state, ChannelState::ChannelReady(_)))
64086412
{
@@ -8918,6 +8922,10 @@ impl<SP: Deref> FundedChannel<SP> where
89188922
false
89198923
}
89208924
}
8925+
8926+
pub fn is_v2_established(&self) -> bool {
8927+
self.is_v2_established
8928+
}
89218929
}
89228930

89238931
/// A not-yet-funded outbound (from holder) channel using V1 channel establishment.
@@ -9185,6 +9193,7 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
91859193
funding: self.funding,
91869194
context: self.context,
91879195
interactive_tx_signing_session: None,
9196+
is_v2_established: false,
91889197
holder_commitment_point,
91899198
};
91909199

@@ -9452,6 +9461,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
94529461
funding: self.funding,
94539462
context: self.context,
94549463
interactive_tx_signing_session: None,
9464+
is_v2_established: false,
94559465
holder_commitment_point,
94569466
};
94579467
let need_channel_ready = channel.check_get_channel_ready(0, logger).is_some()
@@ -10263,7 +10273,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
1026310273
let mut _val: u64 = Readable::read(reader)?;
1026410274
}
1026510275

10266-
let channel_id = Readable::read(reader)?;
10276+
let channel_id: ChannelId = Readable::read(reader)?;
1026710277
let channel_state = ChannelState::from_u32(Readable::read(reader)?).map_err(|_| DecodeError::InvalidValue)?;
1026810278
let channel_value_satoshis = Readable::read(reader)?;
1026910279

@@ -10699,6 +10709,10 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
1069910709
}
1070010710
},
1070110711
};
10712+
let is_v2_established = channel_id.is_v2_channel_id(
10713+
&channel_parameters.holder_pubkeys.revocation_basepoint,
10714+
&channel_parameters.counterparty_parameters.as_ref()
10715+
.expect("Persisted channel must have counterparty parameters").pubkeys.revocation_basepoint);
1070210716

1070310717
Ok(FundedChannel {
1070410718
funding: FundingScope {
@@ -10841,6 +10855,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
1084110855
is_holder_quiescence_initiator: None,
1084210856
},
1084310857
interactive_tx_signing_session: None,
10858+
is_v2_established,
1084410859
holder_commitment_point,
1084510860
})
1084610861
}

lightning/src/ln/channelmanager.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -8524,14 +8524,14 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
85248524
match chan_entry.get_mut().as_funded_mut() {
85258525
Some(chan) => {
85268526
let logger = WithChannelContext::from(&self.logger, &chan.context, None);
8527-
let (tx_signatures_opt, funding_tx_opt) = try_channel_entry!(self, peer_state, chan.tx_signatures(msg, &&logger), chan_entry);
8527+
let tx_signatures_opt = try_channel_entry!(self, peer_state, chan.tx_signatures(msg, &&logger), chan_entry);
85288528
if let Some(tx_signatures) = tx_signatures_opt {
85298529
peer_state.pending_msg_events.push(events::MessageSendEvent::SendTxSignatures {
85308530
node_id: *counterparty_node_id,
85318531
msg: tx_signatures,
85328532
});
85338533
}
8534-
if let Some(ref funding_tx) = funding_tx_opt {
8534+
if let Some(ref funding_tx) = chan.context.unbroadcasted_funding() {
85358535
self.tx_broadcaster.broadcast_transactions(&[funding_tx]);
85368536
{
85378537
let mut pending_events = self.pending_events.lock().unwrap();

lightning/src/ln/dual_funding_tests.rs

+34-43
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,13 @@ use {
2020
crate::ln::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint, RevocationBasepoint},
2121
crate::ln::functional_test_utils::*,
2222
crate::ln::msgs::ChannelMessageHandler,
23-
crate::ln::msgs::{CommitmentSigned, TxAddInput, TxAddOutput, TxComplete},
23+
crate::ln::msgs::{CommitmentSigned, TxAddInput, TxAddOutput, TxComplete, TxSignatures},
2424
crate::ln::types::ChannelId,
2525
crate::prelude::*,
2626
crate::sign::ChannelSigner as _,
2727
crate::util::ser::TransactionU16LenLimited,
2828
crate::util::test_utils,
29+
bitcoin::Witness,
2930
};
3031

3132
// Dual-funding: V2 Channel Establishment Tests
@@ -36,9 +37,7 @@ struct V2ChannelEstablishmentTestSession {
3637

3738
// TODO(dual_funding): Use real node and API for creating V2 channels as initiator when available,
3839
// instead of manually constructing messages.
39-
fn do_test_v2_channel_establishment(
40-
session: V2ChannelEstablishmentTestSession, test_async_persist: bool,
41-
) {
40+
fn do_test_v2_channel_establishment(session: V2ChannelEstablishmentTestSession) {
4241
let chanmon_cfgs = create_chanmon_cfgs(2);
4342
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4443
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
@@ -196,37 +195,23 @@ fn do_test_v2_channel_establishment(
196195
partial_signature_with_nonce: None,
197196
};
198197

199-
if test_async_persist {
200-
chanmon_cfgs[1]
201-
.persister
202-
.set_update_ret(crate::chain::ChannelMonitorUpdateStatus::InProgress);
203-
}
198+
chanmon_cfgs[1].persister.set_update_ret(crate::chain::ChannelMonitorUpdateStatus::InProgress);
204199

205200
// Handle the initial commitment_signed exchange. Order is not important here.
206201
nodes[1]
207202
.node
208203
.handle_commitment_signed(nodes[0].node.get_our_node_id(), &msg_commitment_signed_from_0);
209204
check_added_monitors(&nodes[1], 1);
210205

211-
if test_async_persist {
212-
let events = nodes[1].node.get_and_clear_pending_events();
213-
assert!(events.is_empty());
206+
// The funding transaction should not have been broadcast before persisting initial monitor has
207+
// been completed.
208+
assert_eq!(nodes[1].tx_broadcaster.txn_broadcast().len(), 0);
209+
assert_eq!(nodes[1].node.get_and_clear_pending_events().len(), 0);
214210

215-
chanmon_cfgs[1]
216-
.persister
217-
.set_update_ret(crate::chain::ChannelMonitorUpdateStatus::Completed);
218-
let (latest_update, _) = *nodes[1]
219-
.chain_monitor
220-
.latest_monitor_update_id
221-
.lock()
222-
.unwrap()
223-
.get(&channel_id)
224-
.unwrap();
225-
nodes[1]
226-
.chain_monitor
227-
.chain_monitor
228-
.force_channel_monitor_updated(channel_id, latest_update);
229-
}
211+
// Complete the persistence of the monitor.
212+
let events = nodes[1].node.get_and_clear_pending_events();
213+
assert!(events.is_empty());
214+
nodes[1].chain_monitor.complete_sole_pending_chan_update(&channel_id);
230215

231216
let events = nodes[1].node.get_and_clear_pending_events();
232217
assert_eq!(events.len(), 1);
@@ -242,24 +227,30 @@ fn do_test_v2_channel_establishment(
242227
);
243228

244229
assert_eq!(tx_signatures_msg.channel_id, channel_id);
230+
231+
let mut witness = Witness::new();
232+
witness.push([0x0]);
233+
// Receive tx_signatures from channel initiator.
234+
nodes[1].node.handle_tx_signatures(
235+
nodes[0].node.get_our_node_id(),
236+
&TxSignatures {
237+
channel_id,
238+
tx_hash: funding_outpoint.unwrap().txid,
239+
witnesses: vec![witness],
240+
shared_input_signature: None,
241+
},
242+
);
243+
244+
// For an inbound channel V2 channel the transaction should be broadcast once receiving a
245+
// tx_signature and applying local tx_signatures:
246+
let broadcasted_txs = nodes[1].tx_broadcaster.txn_broadcast();
247+
assert_eq!(broadcasted_txs.len(), 1);
245248
}
246249

247250
#[test]
248251
fn test_v2_channel_establishment() {
249-
// Only initiator contributes, no persist pending
250-
do_test_v2_channel_establishment(
251-
V2ChannelEstablishmentTestSession {
252-
funding_input_sats: 100_000,
253-
initiator_input_value_satoshis: 150_000,
254-
},
255-
false,
256-
);
257-
// Only initiator contributes, persist pending
258-
do_test_v2_channel_establishment(
259-
V2ChannelEstablishmentTestSession {
260-
funding_input_sats: 100_000,
261-
initiator_input_value_satoshis: 150_000,
262-
},
263-
true,
264-
);
252+
do_test_v2_channel_establishment(V2ChannelEstablishmentTestSession {
253+
funding_input_sats: 100_00,
254+
initiator_input_value_satoshis: 150_000,
255+
});
265256
}

lightning/src/ln/interactivetxs.rs

+12-5
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

+19
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,11 @@ impl ChannelId {
9999
let our_revocation_point_bytes = our_revocation_basepoint.0.serialize();
100100
Self(Sha256::hash(&[[0u8; 33], our_revocation_point_bytes].concat()).to_byte_array())
101101
}
102+
103+
/// Indicates whether this is a V2 channel ID for the given local and remote revocation basepoints.
104+
pub fn is_v2_channel_id(&self, ours: &RevocationBasepoint, theirs: &RevocationBasepoint) -> bool {
105+
*self == Self::v2_from_revocation_basepoints(ours, theirs)
106+
}
102107
}
103108

104109
impl Writeable for ChannelId {
@@ -213,4 +218,18 @@ mod tests {
213218

214219
assert_eq!(ChannelId::v2_from_revocation_basepoints(&ours, &theirs), expected_id);
215220
}
221+
222+
#[test]
223+
fn test_is_v2_channel_id() {
224+
let our_pk = "0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c";
225+
let ours = RevocationBasepoint(PublicKey::from_str(&our_pk).unwrap());
226+
let their_pk = "02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619";
227+
let theirs = RevocationBasepoint(PublicKey::from_str(&their_pk).unwrap());
228+
229+
let channel_id = ChannelId::v2_from_revocation_basepoints(&ours, &theirs);
230+
assert!(channel_id.is_v2_channel_id(&ours, &theirs));
231+
232+
let channel_id = ChannelId::v1_from_funding_txid(&[2; 32], 1);
233+
assert!(!channel_id.is_v2_channel_id(&ours, &theirs))
234+
}
216235
}

0 commit comments

Comments
 (0)