Skip to content

Commit ec051e2

Browse files
committed
WIP, Implement funding_tx_constructed()
1 parent 1ef4df0 commit ec051e2

File tree

2 files changed

+180
-40
lines changed

2 files changed

+180
-40
lines changed

lightning/src/ln/channel.rs

Lines changed: 179 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1546,22 +1546,55 @@ impl<SP: Deref> Channel<SP> where
15461546
where
15471547
L::Target: Logger
15481548
{
1549-
if let ChannelPhase::UnfundedV2(chan) = &mut self.phase {
1550-
let logger = WithChannelContext::from(logger, &chan.context, None);
1551-
chan.funding_tx_constructed(signing_session, &&logger)
1552-
} else {
1553-
Err(ChannelError::Warn("Got a tx_complete message with no interactive transaction construction expected or in-progress".to_owned()))
1554-
}
1549+
let phase = core::mem::replace(&mut self.phase, ChannelPhase::Undefined);
1550+
let result = match phase {
1551+
ChannelPhase::UnfundedV2(mut chan) => {
1552+
let logger = WithChannelContext::from(logger, &chan.context, None);
1553+
match chan.funding_tx_constructed(signing_session, &&logger) {
1554+
Ok((commitment_signed, event)) => {
1555+
// TODO: Transition to Funded ? Which chan? // self.phase = ChannelPhase::Funded(chan);
1556+
self.phase = ChannelPhase::UnfundedV2(chan);
1557+
Ok((commitment_signed, event))
1558+
},
1559+
Err(e) => {
1560+
// revert
1561+
self.phase = ChannelPhase::UnfundedV2(chan);
1562+
Err(e)
1563+
},
1564+
}
1565+
}
1566+
#[cfg(splicing)]
1567+
ChannelPhase::RefundingV2(chan) => {
1568+
let logger = WithChannelContext::from(logger, &chan.pre_funded.context, None);
1569+
match chan.funding_tx_constructed(signing_session, &&logger) {
1570+
Ok((signing_session, holder_commitment_point, commitment_signed, event)) => {
1571+
let _res = self.phase_from_splice_to_funded(signing_session, holder_commitment_point)?;
1572+
Ok((commitment_signed, event))
1573+
},
1574+
Err((chan, e)) => {
1575+
// revert
1576+
self.phase = ChannelPhase::RefundingV2(chan);
1577+
Err(e)
1578+
},
1579+
}
1580+
}
1581+
_ => {
1582+
self.phase = phase;
1583+
Err(ChannelError::Warn("Got a tx_complete message with no interactive transaction construction expected or in-progress".to_owned()))
1584+
}
1585+
};
1586+
1587+
debug_assert!(!matches!(self.phase, ChannelPhase::Undefined));
1588+
result
15551589
}
15561590

15571591
/// Transition the channel from Funded to SplicingChannel.
15581592
/// Done in one go, as the existing ('pre') channel is put in the new channel (alongside a new one).
15591593
#[cfg(splicing)]
1560-
fn phase_to_splice(&mut self, post_funding: FundingScope, dual_funding_context: DualFundingChannelContext, pending_splice_post: PendingSplicePost) -> Result<(), ChannelError>
1561-
{
1594+
fn phase_from_funded_to_splice(&mut self, post_funding: FundingScope, dual_funding_context: DualFundingChannelContext, unfunded_context: UnfundedChannelContext, pending_splice_post: PendingSplicePost) -> Result<(), ChannelError> {
15621595
let phase = core::mem::replace(&mut self.phase, ChannelPhase::Undefined);
15631596
let result = if let ChannelPhase::Funded(prev_chan) = phase {
1564-
self.phase = ChannelPhase::RefundingV2(SplicingChannel::new(prev_chan, post_funding, dual_funding_context, pending_splice_post));
1597+
self.phase = ChannelPhase::RefundingV2(SplicingChannel::new(prev_chan, post_funding, dual_funding_context, unfunded_context, pending_splice_post));
15651598
Ok(())
15661599
} else {
15671600
// revert phase
@@ -1572,6 +1605,30 @@ impl<SP: Deref> Channel<SP> where
15721605
result
15731606
}
15741607

1608+
/// Transition the channel from SplicingChannel to Funded, after negotiating new funded.
1609+
#[cfg(splicing)]
1610+
fn phase_from_splice_to_funded(&mut self, signing_session: InteractiveTxSigningSession, holder_commitment_point: HolderCommitmentPoint) -> Result<(), ChannelError> {
1611+
let phase = core::mem::replace(&mut self.phase, ChannelPhase::Undefined);
1612+
let result = if let ChannelPhase::RefundingV2(chan) = phase {
1613+
self.phase = ChannelPhase::Funded(FundedChannel {
1614+
funding: chan.post_funding,
1615+
context: chan.pre_funded.context,
1616+
interactive_tx_signing_session: Some(signing_session),
1617+
holder_commitment_point,
1618+
is_v2_established: true,
1619+
pending_splice_pre: None,
1620+
pending_splice_post: None,
1621+
});
1622+
Ok(())
1623+
} else {
1624+
// revert phase
1625+
self.phase = phase;
1626+
Err(ChannelError::Warn("Cannot transition away from splicing, not in splicing phase".to_owned()))
1627+
};
1628+
debug_assert!(!matches!(self.phase, ChannelPhase::Undefined));
1629+
result
1630+
}
1631+
15751632
#[cfg(splicing)]
15761633
pub fn splice_init<ES: Deref, L: Deref>(
15771634
&mut self, msg: &msgs::SpliceInit, our_funding_contribution: i64,
@@ -1583,10 +1640,10 @@ impl<SP: Deref> Channel<SP> where
15831640
{
15841641
// Explicit check for Funded, not as_funded; RefundingV2 not allowed
15851642
if let ChannelPhase::Funded(prev_chan) = &mut self.phase {
1586-
let (pending_splice_post, post_funding, dual_funding_context) =
1643+
let (pending_splice_post, post_funding, dual_funding_context, unfunded_context) =
15871644
prev_chan.splice_init(msg, our_funding_contribution)?;
15881645

1589-
let _res = self.phase_to_splice(post_funding, dual_funding_context, pending_splice_post)?;
1646+
let _res = self.phase_from_funded_to_splice(post_funding, dual_funding_context, unfunded_context, pending_splice_post)?;
15901647

15911648
if let ChannelPhase::RefundingV2(chan) = &mut self.phase {
15921649
let splice_ack_msg = chan.splice_init(msg, our_funding_contribution, signer_provider, entropy_source, our_node_id, logger)?;
@@ -1610,10 +1667,10 @@ impl<SP: Deref> Channel<SP> where
16101667
{
16111668
// Explicit check for Funded, not as_funded; RefundingV2 not allowed
16121669
if let ChannelPhase::Funded(prev_chan) = &mut self.phase {
1613-
let (pending_splice_post, post_funding, dual_funding_context, our_funding_contribution) =
1670+
let (pending_splice_post, post_funding, dual_funding_context, unfunded_context, our_funding_contribution) =
16141671
prev_chan.splice_ack(msg)?;
16151672

1616-
let _res = self.phase_to_splice(post_funding, dual_funding_context, pending_splice_post)?;
1673+
let _res = self.phase_from_funded_to_splice(post_funding, dual_funding_context, unfunded_context, pending_splice_post)?;
16171674

16181675
if let ChannelPhase::RefundingV2(chan) = &mut self.phase {
16191676
let tx_msg_opt = chan.splice_ack(msg, our_funding_contribution, signer_provider, entropy_source, our_node_id, logger)?;
@@ -1740,9 +1797,9 @@ pub(super) struct SplicingChannel<SP: Deref> where SP::Target: SignerProvider {
17401797
/// TODO: replace it with its fields; done with trait?
17411798
pub pre_funded: FundedChannel<SP>,
17421799

1743-
// Fields for PendingV2Channel follow, except ChannelContext
1800+
// Fields from PendingV2Channel follow, except ChannelContext, which is reused from above
17441801
pub post_funding: FundingScope,
1745-
// pub unfunded_context: Option<UnfundedChannelContext>,
1802+
pub unfunded_context: UnfundedChannelContext,
17461803
/// Used when negotiating the splice transaction
17471804
pub dual_funding_context: DualFundingChannelContext,
17481805
/// The current interactive transaction construction session under negotiation.
@@ -1755,18 +1812,18 @@ pub(super) struct SplicingChannel<SP: Deref> where SP::Target: SignerProvider {
17551812

17561813
#[cfg(splicing)]
17571814
impl<SP: Deref> SplicingChannel<SP> where SP::Target: SignerProvider {
1758-
fn new(pre_funded: FundedChannel<SP>, post_funding: FundingScope, dual_funding_context: DualFundingChannelContext, pending_splice_post: PendingSplicePost) -> Self {
1815+
fn new(pre_funded: FundedChannel<SP>, post_funding: FundingScope, dual_funding_context: DualFundingChannelContext, unfunded_context: UnfundedChannelContext, pending_splice_post: PendingSplicePost) -> Self {
17591816
Self {
17601817
pre_funded,
17611818
post_funding,
17621819
dual_funding_context,
1820+
unfunded_context,
17631821
interactive_tx_constructor: None,
17641822
pending_splice_post,
17651823
}
17661824
}
17671825

17681826
/// Handle splice_init
1769-
#[cfg(splicing)]
17701827
pub fn splice_init<ES: Deref, L: Deref>(
17711828
&mut self, _msg: &msgs::SpliceInit, our_funding_contribution: i64,
17721829
signer_provider: &SP, entropy_source: &ES, holder_node_id: &PublicKey, logger: &L,
@@ -1788,7 +1845,6 @@ impl<SP: Deref> SplicingChannel<SP> where SP::Target: SignerProvider {
17881845
}
17891846

17901847
/// Handle splice_ack
1791-
#[cfg(splicing)]
17921848
pub fn splice_ack<ES: Deref, L: Deref>(
17931849
&mut self, msg: &msgs::SpliceAck, our_funding_contribution: i64,
17941850
signer_provider: &SP, entropy_source: &ES, holder_node_id: &PublicKey, logger: &L,
@@ -1824,7 +1880,6 @@ impl<SP: Deref> SplicingChannel<SP> where SP::Target: SignerProvider {
18241880
}
18251881

18261882
/// Splice process starting; update state, log, etc.
1827-
#[cfg(splicing)]
18281883
pub(crate) fn splice_start<L: Deref>(&mut self, is_outgoing: bool, logger: &L) where L::Target: Logger {
18291884
// Set state, by this point splice_init/splice_ack handshake is complete
18301885
// TODO(splicing)
@@ -1997,15 +2052,99 @@ impl<SP: Deref> SplicingChannel<SP> where SP::Target: SignerProvider {
19972052
HandleTxCompleteResult(Ok(tx_complete))
19982053
}
19992054

2000-
// TODO implement and use
2001-
// pub fn funding_tx_constructed<L: Deref>(
2002-
// self, signing_session: InteractiveTxSigningSession, logger: &L
2003-
// ) -> Result<(msgs::CommitmentSigned, Option<Event>), ChannelError> where L::Target: Logger {
2004-
// match self.post_pending.funding_tx_constructed(signing_session, logger) {
2005-
// Ok((_chan, msg, event)) => Ok((msg, event)),
2006-
// Err((_chan, err)) => Err(err),
2007-
// }
2008-
// }
2055+
/// Copied from PendingV2Channel::funding_tx_constructed
2056+
/// TODO avoid code duplication with traits
2057+
fn funding_tx_constructed<L: Deref>(
2058+
mut self, mut signing_session: InteractiveTxSigningSession, logger: &L
2059+
) -> Result<(InteractiveTxSigningSession, HolderCommitmentPoint, msgs::CommitmentSigned, Option<Event>), (SplicingChannel<SP>, ChannelError)>
2060+
where
2061+
L::Target: Logger
2062+
{
2063+
let our_funding_satoshis = self.dual_funding_context.our_funding_satoshis;
2064+
let transaction_number = self.unfunded_context.transaction_number();
2065+
2066+
let mut output_index = None;
2067+
let expected_spk = self.pre_funded.funding.get_funding_redeemscript().to_p2wsh();
2068+
for (idx, outp) in signing_session.unsigned_tx.outputs().enumerate() {
2069+
if outp.script_pubkey() == &expected_spk && outp.value() == self.post_funding.get_value_satoshis() {
2070+
if output_index.is_some() {
2071+
return Err(ChannelError::Close((
2072+
"Multiple outputs matched the expected script and value".to_owned(),
2073+
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
2074+
))).map_err(|e| (self, e));
2075+
}
2076+
output_index = Some(idx as u16);
2077+
}
2078+
}
2079+
let outpoint = if let Some(output_index) = output_index {
2080+
OutPoint { txid: signing_session.unsigned_tx.compute_txid(), index: output_index }
2081+
} else {
2082+
return Err(ChannelError::Close((
2083+
"No output matched the funding script_pubkey".to_owned(),
2084+
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
2085+
))).map_err(|e| (self, e));
2086+
};
2087+
self.pre_funded.funding.channel_transaction_parameters.funding_outpoint = Some(outpoint);
2088+
// self.pre_funded.context.holder_signer.as_mut_ecdsa().provide_channel_parameters(&self.pre_funded.funding.channel_transaction_parameters);
2089+
2090+
self.pre_funded.context.assert_no_commitment_advancement(transaction_number, "initial commitment_signed");
2091+
let commitment_signed = self.pre_funded.context.get_initial_commitment_signed(&self.post_funding, logger);
2092+
let commitment_signed = match commitment_signed {
2093+
Ok(commitment_signed) => {
2094+
self.pre_funded.funding.funding_transaction = Some(signing_session.unsigned_tx.build_unsigned_tx());
2095+
commitment_signed
2096+
},
2097+
Err(err) => {
2098+
self.pre_funded.funding.channel_transaction_parameters.funding_outpoint = None;
2099+
return Err(ChannelError::Close((err.to_string(), ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) })))
2100+
.map_err(|e| (self, e));
2101+
},
2102+
};
2103+
2104+
let funding_ready_for_sig_event = None;
2105+
if signing_session.local_inputs_count() == 0 {
2106+
debug_assert_eq!(our_funding_satoshis, 0);
2107+
if signing_session.provide_holder_witnesses(self.pre_funded.context.channel_id, Vec::new()).is_err() {
2108+
debug_assert!(
2109+
false,
2110+
"Zero inputs were provided & zero witnesses were provided, but a count mismatch was somehow found",
2111+
);
2112+
}
2113+
} else {
2114+
// TODO(dual_funding): Send event for signing if we've contributed funds.
2115+
// Inform the user that SIGHASH_ALL must be used for all signatures when contributing
2116+
// inputs/signatures.
2117+
// Also warn the user that we don't do anything to prevent the counterparty from
2118+
// providing non-standard witnesses which will prevent the funding transaction from
2119+
// confirming. This warning must appear in doc comments wherever the user is contributing
2120+
// funds, whether they are initiator or acceptor.
2121+
//
2122+
// The following warning can be used when the APIs allowing contributing inputs become available:
2123+
// <div class="warning">
2124+
// WARNING: LDK makes no attempt to prevent the counterparty from using non-standard inputs which
2125+
// will prevent the funding transaction from being relayed on the bitcoin network and hence being
2126+
// confirmed.
2127+
// </div>
2128+
}
2129+
2130+
self.pre_funded.context.channel_state = ChannelState::FundingNegotiated;
2131+
2132+
// Clear the interactive transaction constructor
2133+
self.interactive_tx_constructor.take();
2134+
2135+
match self.unfunded_context.holder_commitment_point {
2136+
Some(holder_commitment_point) => {
2137+
Ok((signing_session, holder_commitment_point, commitment_signed, funding_ready_for_sig_event))
2138+
},
2139+
None => {
2140+
let err = ChannelError::close(format!(
2141+
"Expected to have holder commitment points available upon finishing interactive tx construction for channel {}",
2142+
self.pre_funded.context.channel_id(),
2143+
));
2144+
Err((self, err))
2145+
},
2146+
}
2147+
}
20092148
}
20102149

20112150
/// Contains all state common to unfunded inbound/outbound channels.
@@ -9213,7 +9352,7 @@ impl<SP: Deref> FundedChannel<SP> where
92139352
#[cfg(splicing)]
92149353
fn splice_init(
92159354
&mut self, msg: &msgs::SpliceInit, our_funding_contribution: i64,
9216-
) -> Result<(PendingSplicePost, FundingScope, DualFundingChannelContext), ChannelError>
9355+
) -> Result<(PendingSplicePost, FundingScope, DualFundingChannelContext, UnfundedChannelContext), ChannelError>
92179356
{
92189357
let _res = self.splice_init_checks(msg)?;
92199358

@@ -9264,12 +9403,12 @@ impl<SP: Deref> FundedChannel<SP> where
92649403
funding_feerate_sat_per_1000_weight: msg.funding_feerate_per_kw,
92659404
our_funding_inputs: Vec::new(),
92669405
};
9267-
// let unfunded_context = UnfundedChannelContext {
9268-
// unfunded_channel_age_ticks: 0,
9269-
// holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
9270-
// };
9406+
let unfunded_context = UnfundedChannelContext {
9407+
unfunded_channel_age_ticks: 0,
9408+
holder_commitment_point: HolderCommitmentPoint::new(&self.context.holder_signer, &self.context.secp_ctx),
9409+
};
92719410

9272-
Ok((pending_splice_post, post_funding, dual_funding_context))
9411+
Ok((pending_splice_post, post_funding, dual_funding_context, unfunded_context))
92739412
}
92749413

92759414
/// Get the splice_ack message that can be sent in response to splice initiation.
@@ -9301,7 +9440,7 @@ impl<SP: Deref> FundedChannel<SP> where
93019440
#[cfg(splicing)]
93029441
fn splice_ack(
93039442
&mut self, msg: &msgs::SpliceAck,
9304-
) -> Result<(PendingSplicePost, FundingScope, DualFundingChannelContext, i64), ChannelError>
9443+
) -> Result<(PendingSplicePost, FundingScope, DualFundingChannelContext, UnfundedChannelContext, i64), ChannelError>
93059444
{
93069445
let pending_splice = self.splice_ack_checks()?;
93079446

@@ -9352,12 +9491,12 @@ impl<SP: Deref> FundedChannel<SP> where
93529491
funding_feerate_sat_per_1000_weight: pending_splice.funding_feerate_per_kw,
93539492
our_funding_inputs: pending_splice.our_funding_inputs.clone(),
93549493
};
9355-
// let unfunded_context = UnfundedChannelContext {
9356-
// unfunded_channel_age_ticks: 0,
9357-
// holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
9358-
// };
9494+
let unfunded_context = UnfundedChannelContext {
9495+
unfunded_channel_age_ticks: 0,
9496+
holder_commitment_point: HolderCommitmentPoint::new(&self.context.holder_signer, &self.context.secp_ctx),
9497+
};
93599498

9360-
Ok((pending_splice_post, post_funding, dual_funding_context, pending_splice.our_funding_contribution))
9499+
Ok((pending_splice_post, post_funding, dual_funding_context, unfunded_context, pending_splice.our_funding_contribution))
93619500
}
93629501

93639502
// Send stuff to our remote peers:

lightning/src/ln/channelmanager.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8549,6 +8549,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
85498549
peer_state.pending_msg_events.push(msg_send_event);
85508550
};
85518551
if let Some(signing_session) = signing_session_opt {
8552+
panic!("TODO Fix commitment handling, execution should get to here");
85528553
let (commitment_signed, funding_ready_for_sig_event_opt) = chan_entry
85538554
.get_mut()
85548555
.funding_tx_constructed(signing_session, &self.logger)

0 commit comments

Comments
 (0)