Skip to content

Commit 3afdfce

Browse files
committed
Add begin_interactive_funding_tx_construction()
This method is needed by both V2 channel open and splicing. Auxiliary changes: - In `DualFundingChannelContext` add a new field for the counterparty contribution, `their_funding_satoshis`. - New method `calculate_change_output_value()` for determining if a change output is needed, and with what value. - In `interactivetxs.rs` adjust the visibility of `SharedOwnedOutput` and `OutputOwned` structs (were not used before).
1 parent 5bc9ffa commit 3afdfce

File tree

2 files changed

+299
-17
lines changed

2 files changed

+299
-17
lines changed

lightning/src/ln/channel.rs

Lines changed: 146 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
use bitcoin::amount::Amount;
1111
use bitcoin::constants::ChainHash;
1212
use bitcoin::script::{Script, ScriptBuf, Builder, WScriptHash};
13-
use bitcoin::transaction::{Transaction, TxIn};
13+
use bitcoin::transaction::{Transaction, TxIn, TxOut};
1414
use bitcoin::sighash;
1515
use bitcoin::sighash::EcdsaSighashType;
1616
use bitcoin::consensus::encode;
@@ -31,9 +31,9 @@ use crate::ln::types::ChannelId;
3131
use crate::types::payment::{PaymentPreimage, PaymentHash};
3232
use crate::types::features::{ChannelTypeFeatures, InitFeatures};
3333
use crate::ln::interactivetxs::{
34-
get_output_weight, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
35-
InteractiveTxConstructorArgs, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
36-
TX_COMMON_FIELDS_WEIGHT,
34+
get_output_weight, calculate_change_output_value, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
35+
InteractiveTxConstructorArgs, InteractiveTxMessageSend, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
36+
OutputOwned, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
3737
};
3838
use crate::ln::msgs;
3939
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError};
@@ -2213,6 +2213,107 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
22132213
}
22142214

22152215
impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2216+
/// Prepare and start interactive transaction negotiation.
2217+
/// `change_destination_opt` - Optional destination for optional change; if None, default destination address is used.
2218+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2219+
fn begin_interactive_funding_tx_construction<ES: Deref>(
2220+
&mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2221+
change_destination_opt: Option<ScriptBuf>,
2222+
) -> Result<Option<InteractiveTxMessageSend>, APIError>
2223+
where ES::Target: EntropySource
2224+
{
2225+
let mut funding_inputs = Vec::new();
2226+
mem::swap(&mut self.dual_funding_context.our_funding_inputs, &mut funding_inputs);
2227+
2228+
let funding_inputs_prev_outputs = DualFundingChannelContext::txouts_from_input_prev_txs(&funding_inputs)
2229+
.map_err(|err| APIError::APIMisuseError { err: err.to_string() })?;
2230+
2231+
let total_input_satoshis: u64 = funding_inputs_prev_outputs.iter().map(|txout| txout.value.to_sat()).sum();
2232+
if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2233+
return Err(APIError::APIMisuseError {
2234+
err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2235+
total_input_satoshis) });
2236+
}
2237+
2238+
// Add output for funding tx
2239+
let mut funding_outputs = Vec::new();
2240+
let funding_output_value_satoshis = self.funding.get_value_satoshis();
2241+
let funding_output_script_pubkey = self.funding.get_funding_redeemscript().to_p2wsh();
2242+
let expected_remote_shared_funding_output = if self.funding.is_outbound() {
2243+
let tx_out = TxOut {
2244+
value: Amount::from_sat(funding_output_value_satoshis),
2245+
script_pubkey: funding_output_script_pubkey,
2246+
};
2247+
funding_outputs.push(
2248+
if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2249+
OutputOwned::SharedControlFullyOwned(tx_out)
2250+
} else {
2251+
OutputOwned::Shared(SharedOwnedOutput::new(
2252+
tx_out, self.dual_funding_context.our_funding_satoshis
2253+
))
2254+
}
2255+
);
2256+
None
2257+
} else {
2258+
Some((funding_output_script_pubkey, funding_output_value_satoshis))
2259+
};
2260+
2261+
// Optionally add change output
2262+
let change_value_opt = calculate_change_output_value(
2263+
self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2264+
&funding_inputs_prev_outputs, &funding_outputs,
2265+
self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2266+
self.context.holder_dust_limit_satoshis,
2267+
).map_err(|err| APIError::APIMisuseError {
2268+
err: format!("Insufficient inputs, cannot cover intended contribution of {} and fees; {}",
2269+
self.dual_funding_context.our_funding_satoshis, err
2270+
),
2271+
})?;
2272+
if let Some(change_value) = change_value_opt {
2273+
let change_script = match change_destination_opt {
2274+
Some(script) => script,
2275+
None => {
2276+
signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2277+
|err| APIError::APIMisuseError {
2278+
err: format!("Failed to get change script as new destination script, {:?}", err),
2279+
})?
2280+
}
2281+
};
2282+
let mut change_output = TxOut {
2283+
value: Amount::from_sat(change_value),
2284+
script_pubkey: change_script,
2285+
};
2286+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2287+
let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2288+
let change_value_decreased_with_fee = change_value.saturating_sub(change_output_fee);
2289+
// Check dust limit again
2290+
if change_value_decreased_with_fee > self.context.holder_dust_limit_satoshis {
2291+
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
2292+
funding_outputs.push(OutputOwned::Single(change_output));
2293+
}
2294+
}
2295+
2296+
let constructor_args = InteractiveTxConstructorArgs {
2297+
entropy_source,
2298+
holder_node_id,
2299+
counterparty_node_id: self.context.counterparty_node_id,
2300+
channel_id: self.context.channel_id(),
2301+
feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2302+
is_initiator: self.funding.is_outbound(),
2303+
funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2304+
inputs_to_contribute: funding_inputs,
2305+
outputs_to_contribute: funding_outputs,
2306+
expected_remote_shared_funding_output,
2307+
};
2308+
let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2309+
.map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2310+
let msg = tx_constructor.take_initiator_first_message();
2311+
2312+
self.interactive_tx_constructor = Some(tx_constructor);
2313+
2314+
Ok(msg)
2315+
}
2316+
22162317
pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
22172318
InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
22182319
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4671,6 +4772,9 @@ fn estimate_v2_funding_transaction_fee(
46714772
pub(super) struct DualFundingChannelContext {
46724773
/// The amount in satoshis we will be contributing to the channel.
46734774
pub our_funding_satoshis: u64,
4775+
/// The amount in satoshis our counterparty will be contributing to the channel.
4776+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4777+
pub their_funding_satoshis: Option<u64>,
46744778
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
46754779
/// to the current block height to align incentives against fee-sniping.
46764780
pub funding_tx_locktime: LockTime,
@@ -4682,10 +4786,39 @@ pub(super) struct DualFundingChannelContext {
46824786
/// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
46834787
/// minus any fees paid for our contributed weight. This means that change will never be generated
46844788
/// and the maximum value possible will go towards funding the channel.
4789+
///
4790+
/// Note that this field may be emptied once the interactive negotiation has been started.
46854791
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
46864792
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
46874793
}
46884794

4795+
impl DualFundingChannelContext {
4796+
/// Obtain prev outputs for each supplied input and matching transaction.
4797+
/// Will error when a prev tx does not have an output for the specified vout.
4798+
/// Also checks for matching of transaction IDs.
4799+
fn txouts_from_input_prev_txs(inputs: &Vec<(TxIn, TransactionU16LenLimited)>) -> Result<Vec<&TxOut>, ChannelError> {
4800+
let mut prev_outputs: Vec<&TxOut> = Vec::with_capacity(inputs.len());
4801+
// Check that vouts exist for each TxIn in provided transactions.
4802+
for (idx, (txin, tx)) in inputs.iter().enumerate() {
4803+
let txid = tx.as_transaction().compute_txid();
4804+
if txin.previous_output.txid != txid {
4805+
return Err(ChannelError::Warn(
4806+
format!("Transaction input txid mismatch, {} vs. {}, at index {}", txin.previous_output.txid, txid, idx)
4807+
));
4808+
}
4809+
if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
4810+
prev_outputs.push(output);
4811+
} else {
4812+
return Err(ChannelError::Warn(
4813+
format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn, at index {}",
4814+
txid, txin.previous_output.vout, idx)
4815+
));
4816+
}
4817+
}
4818+
Ok(prev_outputs)
4819+
}
4820+
}
4821+
46894822
// Holder designates channel data owned for the benefit of the user client.
46904823
// Counterparty designates channel data owned by the another channel participant entity.
46914824
pub(super) struct FundedChannel<SP: Deref> where SP::Target: SignerProvider {
@@ -9602,16 +9735,18 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
96029735
unfunded_channel_age_ticks: 0,
96039736
holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
96049737
};
9738+
let dual_funding_context = DualFundingChannelContext {
9739+
our_funding_satoshis: funding_satoshis,
9740+
their_funding_satoshis: None,
9741+
funding_tx_locktime,
9742+
funding_feerate_sat_per_1000_weight,
9743+
our_funding_inputs: funding_inputs,
9744+
};
96059745
let chan = Self {
96069746
funding,
96079747
context,
96089748
unfunded_context,
9609-
dual_funding_context: DualFundingChannelContext {
9610-
our_funding_satoshis: funding_satoshis,
9611-
funding_tx_locktime,
9612-
funding_feerate_sat_per_1000_weight,
9613-
our_funding_inputs: funding_inputs,
9614-
},
9749+
dual_funding_context,
96159750
interactive_tx_constructor: None,
96169751
interactive_tx_signing_session: None,
96179752
};
@@ -9753,6 +9888,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
97539888

97549889
let dual_funding_context = DualFundingChannelContext {
97559890
our_funding_satoshis: our_funding_satoshis,
9891+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
97569892
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
97579893
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
97589894
our_funding_inputs: our_funding_inputs.clone(),

0 commit comments

Comments
 (0)