Skip to content

Commit f54fb2d

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 910cdc8 commit f54fb2d

File tree

5 files changed

+98
-71
lines changed

5 files changed

+98
-71
lines changed

lightning/src/ln/channel.rs

Lines changed: 33 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2276,6 +2276,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
22762276
context: self.context,
22772277
interactive_tx_signing_session: Some(signing_session),
22782278
holder_commitment_point,
2279+
is_v2_established: true,
22792280
};
22802281
Ok((funded_chan, commitment_signed, funding_ready_for_sig_event))
22812282
},
@@ -4652,6 +4653,9 @@ pub(super) struct FundedChannel<SP: Deref> where SP::Target: SignerProvider {
46524653
pub context: ChannelContext<SP>,
46534654
pub interactive_tx_signing_session: Option<InteractiveTxSigningSession>,
46544655
holder_commitment_point: HolderCommitmentPoint,
4656+
/// Indicates whether this funded channel had been established with V2 channel
4657+
/// establishment (i.e. is a dual-funded channel).
4658+
is_v2_established: bool,
46554659
}
46564660

46574661
#[cfg(any(test, fuzzing))]
@@ -6132,10 +6136,10 @@ impl<SP: Deref> FundedChannel<SP> where
61326136
}
61336137
}
61346138

6135-
pub fn tx_signatures<L: Deref>(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<(Option<msgs::TxSignatures>, Option<Transaction>), ChannelError>
6139+
pub fn tx_signatures<L: Deref>(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<Option<msgs::TxSignatures>, ChannelError>
61366140
where L::Target: Logger
61376141
{
6138-
if !matches!(self.context.channel_state, ChannelState::FundingNegotiated) {
6142+
if !matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(_)) {
61396143
return Err(ChannelError::close("Received tx_signatures in strange state!".to_owned()));
61406144
}
61416145

@@ -6169,25 +6173,22 @@ impl<SP: Deref> FundedChannel<SP> where
61696173
// for spending. Doesn't seem to be anything in rust-bitcoin.
61706174
}
61716175

6172-
let (tx_signatures_opt, funding_tx_opt) = signing_session.received_tx_signatures(msg.clone())
6176+
let (holder_tx_signatures_opt, funding_tx_opt) = signing_session.received_tx_signatures(msg.clone())
61736177
.map_err(|_| ChannelError::Warn("Witness count did not match contributed input count".to_string()))?;
6174-
if funding_tx_opt.is_some() {
6175-
self.context.channel_state = ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::new());
6176-
}
6177-
self.context.funding_transaction = funding_tx_opt.clone();
6178-
6179-
self.context.next_funding_txid = None;
6180-
6181-
// Clear out the signing session
6182-
self.interactive_tx_signing_session = None;
6183-
6184-
if tx_signatures_opt.is_some() && self.context.channel_state.is_monitor_update_in_progress() {
6178+
if holder_tx_signatures_opt.is_some() && self.is_awaiting_initial_mon_persist() {
61856179
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress. Setting monitor_pending_tx_signatures.");
6186-
self.context.monitor_pending_tx_signatures = tx_signatures_opt;
6187-
return Ok((None, None));
6180+
self.context.monitor_pending_tx_signatures = holder_tx_signatures_opt;
6181+
return Ok(None);
6182+
}
6183+
if funding_tx_opt.is_some() {
6184+
// We have a finalized funding transaction, so we can set the funding transaction and reset the
6185+
// signing session fields.
6186+
self.context.funding_transaction = funding_tx_opt;
6187+
self.context.next_funding_txid = None;
6188+
self.interactive_tx_signing_session = None;
61886189
}
61896190

6190-
Ok((tx_signatures_opt, funding_tx_opt))
6191+
Ok(holder_tx_signatures_opt)
61916192
} else {
61926193
Err(ChannelError::Close((
61936194
"Unexpected tx_signatures. No funding transaction awaiting signatures".to_string(),
@@ -6404,12 +6405,12 @@ impl<SP: Deref> FundedChannel<SP> where
64046405
assert!(self.context.channel_state.is_monitor_update_in_progress());
64056406
self.context.channel_state.clear_monitor_update_in_progress();
64066407

6407-
// If we're past (or at) the AwaitingChannelReady stage on an outbound channel, try to
6408-
// (re-)broadcast the funding transaction as we may have declined to broadcast it when we
6408+
// If we're past (or at) the AwaitingChannelReady stage on an outbound (or V2-established) channel,
6409+
// try to (re-)broadcast the funding transaction as we may have declined to broadcast it when we
64096410
// first received the funding_signed.
64106411
let mut funding_broadcastable = None;
64116412
if let Some(funding_transaction) = &self.context.funding_transaction {
6412-
if self.context.is_outbound() &&
6413+
if (self.context.is_outbound() || self.is_v2_established()) &&
64136414
(matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(flags) if !flags.is_set(AwaitingChannelReadyFlags::WAITING_FOR_BATCH)) ||
64146415
matches!(self.context.channel_state, ChannelState::ChannelReady(_)))
64156416
{
@@ -8937,6 +8938,10 @@ impl<SP: Deref> FundedChannel<SP> where
89378938
false
89388939
}
89398940
}
8941+
8942+
pub fn is_v2_established(&self) -> bool {
8943+
self.is_v2_established
8944+
}
89408945
}
89418946

89428947
/// A not-yet-funded outbound (from holder) channel using V1 channel establishment.
@@ -9204,6 +9209,7 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
92049209
funding: self.funding,
92059210
context: self.context,
92069211
interactive_tx_signing_session: None,
9212+
is_v2_established: false,
92079213
holder_commitment_point,
92089214
};
92099215

@@ -9471,6 +9477,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
94719477
funding: self.funding,
94729478
context: self.context,
94739479
interactive_tx_signing_session: None,
9480+
is_v2_established: false,
94749481
holder_commitment_point,
94759482
};
94769483
let need_channel_ready = channel.check_get_channel_ready(0, logger).is_some()
@@ -10282,7 +10289,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
1028210289
let mut _val: u64 = Readable::read(reader)?;
1028310290
}
1028410291

10285-
let channel_id = Readable::read(reader)?;
10292+
let channel_id: ChannelId = Readable::read(reader)?;
1028610293
let channel_state = ChannelState::from_u32(Readable::read(reader)?).map_err(|_| DecodeError::InvalidValue)?;
1028710294
let channel_value_satoshis = Readable::read(reader)?;
1028810295

@@ -10718,6 +10725,10 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
1071810725
}
1071910726
},
1072010727
};
10728+
let is_v2_established = channel_id.is_v2_channel_id(
10729+
&channel_parameters.holder_pubkeys.revocation_basepoint,
10730+
&channel_parameters.counterparty_parameters.as_ref()
10731+
.expect("Persisted channel must have counterparty parameters").pubkeys.revocation_basepoint);
1072110732

1072210733
Ok(FundedChannel {
1072310734
funding: FundingScope {
@@ -10860,6 +10871,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
1086010871
is_holder_quiescence_initiator: None,
1086110872
},
1086210873
interactive_tx_signing_session: None,
10874+
is_v2_established,
1086310875
holder_commitment_point,
1086410876
})
1086510877
}

lightning/src/ln/channelmanager.rs

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

lightning/src/ln/dual_funding_tests.rs

Lines changed: 34 additions & 43 deletions
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::{Weight, 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

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)