Skip to content

Commit 04a58fe

Browse files
committed
Handle initial commitment_signed for V2 channels
1 parent 856b531 commit 04a58fe

File tree

3 files changed

+377
-150
lines changed

3 files changed

+377
-150
lines changed

lightning/src/ln/channel.rs

Lines changed: 225 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,9 @@ use bitcoin::locktime::absolute::LockTime;
2929
use crate::ln::types::{ChannelId, PaymentPreimage, PaymentHash};
3030
use crate::ln::features::{ChannelTypeFeatures, InitFeatures};
3131
use crate::ln::interactivetxs::{
32-
AbortReason, estimate_input_weight, get_output_weight, HandleTxCompleteResult,
33-
InteractiveTxConstructor, InteractiveTxMessageSend, InteractiveTxMessageSendResult,
34-
OutputOwned, TX_COMMON_FIELDS_WEIGHT,
32+
AbortReason, ConstructedTransaction, estimate_input_weight, get_output_weight,
33+
HandleTxCompleteResult, InteractiveTxConstructor, InteractiveTxMessageSend,
34+
InteractiveTxMessageSendResult, OutputOwned, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
3535
};
3636
use crate::ln::msgs;
3737
use crate::ln::msgs::DecodeError;
@@ -64,7 +64,6 @@ use crate::sync::Mutex;
6464
use crate::sign::type_resolver::ChannelSignerType;
6565

6666
use super::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint, RevocationBasepoint};
67-
use super::interactivetxs::SharedOwnedOutput;
6867

6968
#[cfg(test)]
7069
pub struct ChannelValueStat {
@@ -1465,7 +1464,7 @@ pub(super) trait InteractivelyFunded<SP: Deref> where SP::Target: SignerProvider
14651464
script_pubkey: self.context().get_funding_redeemscript().to_p2wsh(),
14661465
};
14671466
funding_outputs.push(
1468-
if self.dual_funding_context().their_funding_satoshis > 0 {
1467+
if self.dual_funding_context().their_funding_satoshis.unwrap_or(0) > 0 {
14691468
OutputOwned::Shared(SharedOwnedOutput::new(tx_out, self.dual_funding_context().our_funding_satoshis))
14701469
} else {
14711470
OutputOwned::SharedControlFullyOwned(tx_out)
@@ -3829,7 +3828,7 @@ pub(super) struct DualFundingChannelContext {
38293828
/// The amount in satoshis we will be contributing to the channel.
38303829
pub our_funding_satoshis: u64,
38313830
/// The amount in satoshis our counterparty will be contributing to the channel.
3832-
pub their_funding_satoshis: u64,
3831+
pub their_funding_satoshis: Option<u64>,
38333832
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
38343833
/// to the current block height to align incentives against fee-sniping.
38353834
pub funding_tx_locktime: LockTime,
@@ -4620,6 +4619,102 @@ impl<SP: Deref> Channel<SP> where
46204619
Ok(())
46214620
}
46224621

4622+
pub fn commitment_signed_initial_v2<L: Deref>(
4623+
&mut self, msg: &msgs::CommitmentSigned, best_block: BestBlock, signer_provider: &SP, logger: &L
4624+
) -> Result<ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>, ChannelError>
4625+
where L::Target: Logger
4626+
{
4627+
if !matches!(self.context.channel_state, ChannelState::FundingNegotiated) {
4628+
return Err(ChannelError::Close(
4629+
(
4630+
"Received initial commitment_signed before funding transaction constructed!".to_owned(),
4631+
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
4632+
)));
4633+
}
4634+
if self.context.commitment_secrets.get_min_seen_secret() != (1 << 48) ||
4635+
self.context.cur_counterparty_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER ||
4636+
self.context.holder_commitment_point.transaction_number() != INITIAL_COMMITMENT_NUMBER {
4637+
panic!("Should not have advanced channel commitment tx numbers prior to funding_created");
4638+
}
4639+
4640+
let funding_script = self.context.get_funding_redeemscript();
4641+
4642+
let counterparty_keys = self.context.build_remote_transaction_keys();
4643+
let counterparty_initial_commitment_tx = self.context.build_commitment_transaction(self.context.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, false, logger).tx;
4644+
let counterparty_trusted_tx = counterparty_initial_commitment_tx.trust();
4645+
let counterparty_initial_bitcoin_tx = counterparty_trusted_tx.built_transaction();
4646+
4647+
log_trace!(logger, "Initial counterparty tx for channel {} is: txid {} tx {}",
4648+
&self.context.channel_id(), counterparty_initial_bitcoin_tx.txid, encode::serialize_hex(&counterparty_initial_bitcoin_tx.transaction));
4649+
4650+
let holder_signer = self.context.build_holder_transaction_keys();
4651+
let initial_commitment_tx = self.context.build_commitment_transaction(
4652+
self.context.holder_commitment_point.transaction_number(), &holder_signer, true, false, logger
4653+
).tx;
4654+
{
4655+
let trusted_tx = initial_commitment_tx.trust();
4656+
let initial_commitment_bitcoin_tx = trusted_tx.built_transaction();
4657+
let sighash = initial_commitment_bitcoin_tx.get_sighash_all(&funding_script, self.context.channel_value_satoshis);
4658+
// They sign our commitment transaction, allowing us to broadcast the tx if we wish.
4659+
if self.context.secp_ctx.verify_ecdsa(&sighash, &msg.signature, &self.context.get_counterparty_pubkeys().funding_pubkey).is_err() {
4660+
return Err(ChannelError::Close(
4661+
(
4662+
"Invalid funding_signed signature from peer".to_owned(),
4663+
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
4664+
)));
4665+
}
4666+
}
4667+
4668+
let holder_commitment_tx = HolderCommitmentTransaction::new(
4669+
initial_commitment_tx,
4670+
msg.signature,
4671+
Vec::new(),
4672+
&self.context.get_holder_pubkeys().funding_pubkey,
4673+
self.context.counterparty_funding_pubkey()
4674+
);
4675+
4676+
self.context.holder_signer.as_ref().validate_holder_commitment(&holder_commitment_tx, Vec::new())
4677+
.map_err(|_| ChannelError::Close(
4678+
(
4679+
"Failed to validate our commitment".to_owned(),
4680+
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
4681+
)))?;
4682+
4683+
let funding_redeemscript = self.context.get_funding_redeemscript();
4684+
let funding_txo = self.context.get_funding_txo().unwrap();
4685+
let funding_txo_script = funding_redeemscript.to_p2wsh();
4686+
let obscure_factor = get_commitment_transaction_number_obscure_factor(&self.context.get_holder_pubkeys().payment_point, &self.context.get_counterparty_pubkeys().payment_point, self.context.is_outbound());
4687+
let shutdown_script = self.context.shutdown_scriptpubkey.clone().map(|script| script.into_inner());
4688+
let mut monitor_signer = signer_provider.derive_channel_signer(self.context.channel_value_satoshis, self.context.channel_keys_id);
4689+
monitor_signer.provide_channel_parameters(&self.context.channel_transaction_parameters);
4690+
let channel_monitor = ChannelMonitor::new(self.context.secp_ctx.clone(), monitor_signer,
4691+
shutdown_script, self.context.get_holder_selected_contest_delay(),
4692+
&self.context.destination_script, (funding_txo, funding_txo_script),
4693+
&self.context.channel_transaction_parameters,
4694+
funding_redeemscript.clone(), self.context.channel_value_satoshis,
4695+
obscure_factor,
4696+
holder_commitment_tx, best_block, self.context.counterparty_node_id, self.context.channel_id());
4697+
4698+
channel_monitor.provide_initial_counterparty_commitment_tx(
4699+
counterparty_initial_bitcoin_tx.txid, Vec::new(),
4700+
self.context.cur_counterparty_commitment_transaction_number,
4701+
self.context.counterparty_cur_commitment_point.unwrap(),
4702+
counterparty_initial_commitment_tx.feerate_per_kw(),
4703+
counterparty_initial_commitment_tx.to_broadcaster_value_sat(),
4704+
counterparty_initial_commitment_tx.to_countersignatory_value_sat(), logger);
4705+
4706+
assert!(!self.context.channel_state.is_monitor_update_in_progress()); // We have no had any monitor(s) yet to fail update!
4707+
self.context.holder_commitment_point.advance(&self.context.holder_signer, &self.context.secp_ctx, logger);
4708+
self.context.cur_counterparty_commitment_transaction_number -= 1;
4709+
4710+
log_info!(logger, "Received initial commitment_signed from peer for channel {}", &self.context.channel_id());
4711+
4712+
let need_channel_ready = self.check_get_channel_ready(0, logger).is_some();
4713+
self.monitor_updating_paused(false, false, need_channel_ready, Vec::new(), Vec::new(), Vec::new());
4714+
4715+
Ok(channel_monitor)
4716+
}
4717+
46234718
pub fn commitment_signed<L: Deref>(&mut self, msg: &msgs::CommitmentSigned, logger: &L) -> Result<Option<ChannelMonitorUpdate>, ChannelError>
46244719
where L::Target: Logger
46254720
{
@@ -7856,7 +7951,8 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
78567951
&mut self, msg: &msgs::AcceptChannel, default_limits: &ChannelHandshakeLimits,
78577952
their_features: &InitFeatures
78587953
) -> Result<(), ChannelError> {
7859-
self.context.do_accept_channel_checks(default_limits, their_features, &msg.common_fields, msg.channel_reserve_satoshis)
7954+
self.context.do_accept_channel_checks(
7955+
default_limits, their_features, &msg.common_fields, msg.channel_reserve_satoshis)
78607956
}
78617957

78627958
/// Handles a funding_signed message from the remote end.
@@ -8308,7 +8404,7 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
83088404
unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 },
83098405
dual_funding_context: DualFundingChannelContext {
83108406
our_funding_satoshis: funding_satoshis,
8311-
their_funding_satoshis: 0,
8407+
their_funding_satoshis: None,
83128408
funding_tx_locktime,
83138409
funding_feerate_sat_per_1000_weight,
83148410
our_funding_inputs: funding_inputs,
@@ -8378,6 +8474,27 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
83788474
require_confirmed_inputs: None,
83798475
}
83808476
}
8477+
8478+
pub fn funding_tx_constructed<L: Deref>(
8479+
mut self, transaction: ConstructedTransaction, logger: &L
8480+
) -> Result<(Channel<SP>, msgs::CommitmentSigned), (Self, ChannelError)>
8481+
where
8482+
L::Target: Logger
8483+
{
8484+
let res = get_initial_commitment_signed(&mut self.context, transaction, logger);
8485+
let commitment_signed = match res {
8486+
Ok(commitment_signed) => commitment_signed,
8487+
Err(err) => return Err((self, err)),
8488+
};
8489+
8490+
let channel = Channel {
8491+
context: self.context,
8492+
dual_funding_channel_context: Some(self.dual_funding_context),
8493+
interactive_tx_constructor: self.interactive_tx_constructor,
8494+
};
8495+
8496+
Ok((channel, commitment_signed))
8497+
}
83818498
}
83828499

83838500
// A not-yet-funded inbound (from counterparty) channel using V2 channel establishment.
@@ -8464,7 +8581,7 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
84648581
unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 },
84658582
dual_funding_context: DualFundingChannelContext {
84668583
our_funding_satoshis: funding_satoshis,
8467-
their_funding_satoshis: msg.common_fields.funding_satoshis,
8584+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
84688585
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
84698586
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
84708587
our_funding_inputs: funding_inputs,
@@ -8543,6 +8660,27 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
85438660
pub fn get_accept_channel_v2_message(&self) -> msgs::AcceptChannelV2 {
85448661
self.generate_accept_channel_v2_message()
85458662
}
8663+
8664+
pub fn funding_tx_constructed<L: Deref>(
8665+
mut self, transaction: ConstructedTransaction, logger: &L
8666+
) -> Result<(Channel<SP>, msgs::CommitmentSigned), (Self, ChannelError)>
8667+
where
8668+
L::Target: Logger
8669+
{
8670+
let res = get_initial_commitment_signed(&mut self.context, transaction, logger);
8671+
let commitment_signed = match res {
8672+
Ok(commitment_signed) => commitment_signed,
8673+
Err(err) => return Err((self, err)),
8674+
};
8675+
8676+
let channel = Channel {
8677+
context: self.context,
8678+
dual_funding_channel_context: Some(self.dual_funding_context),
8679+
interactive_tx_constructor: self.interactive_tx_constructor,
8680+
};
8681+
8682+
Ok((channel, commitment_signed))
8683+
}
85468684
}
85478685

85488686
// Unfunded channel utilities
@@ -8570,6 +8708,84 @@ fn get_initial_channel_type(config: &UserConfig, their_features: &InitFeatures)
85708708
ret
85718709
}
85728710

8711+
fn get_initial_counterparty_commitment_signature<SP:Deref, L: Deref>(
8712+
context: &mut ChannelContext<SP>, logger: &L
8713+
) -> Result<Signature, ChannelError>
8714+
where
8715+
SP::Target: SignerProvider,
8716+
L::Target: Logger
8717+
{
8718+
let counterparty_keys = context.build_remote_transaction_keys();
8719+
let counterparty_initial_commitment_tx = context.build_commitment_transaction(
8720+
context.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, false, logger).tx;
8721+
match context.holder_signer {
8722+
// TODO (taproot|arik): move match into calling method for Taproot
8723+
ChannelSignerType::Ecdsa(ref ecdsa) => {
8724+
Ok(ecdsa.sign_counterparty_commitment(&counterparty_initial_commitment_tx, Vec::new(), Vec::new(), &context.secp_ctx)
8725+
.map_err(|_| ChannelError::Close(
8726+
(
8727+
"Failed to get signatures for new commitment_signed".to_owned(),
8728+
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
8729+
)))?.0)
8730+
},
8731+
// TODO (taproot|arik)
8732+
#[cfg(taproot)]
8733+
_ => todo!(),
8734+
}
8735+
}
8736+
8737+
fn get_initial_commitment_signed<SP:Deref, L: Deref>(
8738+
context: &mut ChannelContext<SP>, transaction: ConstructedTransaction, logger: &L
8739+
) -> Result<msgs::CommitmentSigned, ChannelError>
8740+
where
8741+
SP::Target: SignerProvider,
8742+
L::Target: Logger
8743+
{
8744+
if !matches!(
8745+
context.channel_state, ChannelState::NegotiatingFunding(flags)
8746+
if flags == (NegotiatingFundingFlags::OUR_INIT_SENT | NegotiatingFundingFlags::THEIR_INIT_SENT)) {
8747+
panic!("Tried to get a funding_created messsage at a time other than immediately after initial handshake completion (or tried to get funding_created twice)");
8748+
}
8749+
if context.commitment_secrets.get_min_seen_secret() != (1 << 48) ||
8750+
context.cur_counterparty_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER ||
8751+
context.holder_commitment_point.transaction_number() != INITIAL_COMMITMENT_NUMBER {
8752+
panic!("Should not have advanced channel commitment tx numbers prior to initial commitment_signed");
8753+
}
8754+
8755+
let funding_redeemscript = context.get_funding_redeemscript().to_p2wsh();
8756+
let funding_outpoint_index = transaction.outputs().enumerate().find_map(
8757+
|(idx, output)| {
8758+
if output.tx_out().script_pubkey == funding_redeemscript { Some(idx as u16) } else { None }
8759+
}).expect("funding transaction contains funding output");
8760+
let funding_txo = OutPoint { txid: transaction.txid(), index: funding_outpoint_index };
8761+
context.channel_transaction_parameters.funding_outpoint = Some(funding_txo);
8762+
context.holder_signer.as_mut().provide_channel_parameters(&context.channel_transaction_parameters);
8763+
8764+
let signature = match get_initial_counterparty_commitment_signature(context, logger) {
8765+
Ok(res) => res,
8766+
Err(e) => {
8767+
log_error!(logger, "Got bad signatures: {:?}!", e);
8768+
context.channel_transaction_parameters.funding_outpoint = None;
8769+
return Err(e);
8770+
}
8771+
};
8772+
8773+
if context.signer_pending_funding {
8774+
log_trace!(logger, "Counterparty commitment signature ready for funding_created message: clearing signer_pending_funding");
8775+
context.signer_pending_funding = false;
8776+
}
8777+
8778+
log_info!(logger, "Generated commitment_signed for peer for channel {}", &context.channel_id());
8779+
8780+
Ok(msgs::CommitmentSigned {
8781+
channel_id: context.channel_id,
8782+
htlc_signatures: vec![],
8783+
signature,
8784+
#[cfg(taproot)]
8785+
partial_signature_with_nonce: None,
8786+
})
8787+
}
8788+
85738789
const SERIALIZATION_VERSION: u8 = 4;
85748790
const MIN_SERIALIZATION_VERSION: u8 = 3;
85758791

0 commit comments

Comments
 (0)