Skip to content

Commit d1da349

Browse files
committed
Add begin_interactive_funding_tx_construction()
This method is needed by both V2 channel open and splicing. Auxiliary changes: - 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). - In `DualFundingChannelContext` add a new field for the counterparty contribution, `their_funding_satoshis`.
1 parent 4c43a5b commit d1da349

File tree

2 files changed

+296
-17
lines changed

2 files changed

+296
-17
lines changed

lightning/src/ln/channel.rs

Lines changed: 145 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::EcdsaSighashType;
1515
use bitcoin::consensus::encode;
1616
use bitcoin::absolute::LockTime;
@@ -30,9 +30,9 @@ use crate::ln::types::ChannelId;
3030
use crate::types::payment::{PaymentPreimage, PaymentHash};
3131
use crate::types::features::{ChannelTypeFeatures, InitFeatures};
3232
use crate::ln::interactivetxs::{
33-
get_output_weight, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
34-
InteractiveTxConstructorArgs, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
35-
TX_COMMON_FIELDS_WEIGHT,
33+
calculate_change_output_value, get_output_weight, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
34+
InteractiveTxConstructorArgs, InteractiveTxMessageSend, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
35+
OutputOwned, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
3636
};
3737
use crate::ln::msgs;
3838
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError};
@@ -2222,6 +2222,106 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
22222222
}
22232223

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

4998+
impl DualFundingChannelContext {
4999+
/// Obtain prev outputs for each supplied input and matching transaction.
5000+
/// Will error when a prev tx does not have an output for the specified vout.
5001+
/// Also checks for matching of transaction IDs.
5002+
fn txouts_from_input_prev_txs(inputs: &Vec<(TxIn, TransactionU16LenLimited)>) -> Result<Vec<&TxOut>, ChannelError> {
5003+
let mut prev_outputs: Vec<&TxOut> = Vec::with_capacity(inputs.len());
5004+
// Check that vouts exist for each TxIn in provided transactions.
5005+
for (idx, (txin, tx)) in inputs.iter().enumerate() {
5006+
let txid = tx.as_transaction().compute_txid();
5007+
if txin.previous_output.txid != txid {
5008+
return Err(ChannelError::Warn(
5009+
format!("Transaction input txid mismatch, {} vs. {}, at index {}", txin.previous_output.txid, txid, idx)
5010+
));
5011+
}
5012+
if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
5013+
prev_outputs.push(output);
5014+
} else {
5015+
return Err(ChannelError::Warn(
5016+
format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn, at index {}",
5017+
txid, txin.previous_output.vout, idx)
5018+
));
5019+
}
5020+
}
5021+
Ok(prev_outputs)
5022+
}
5023+
}
5024+
48935025
// Holder designates channel data owned for the benefit of the user client.
48945026
// Counterparty designates channel data owned by the another channel participant entity.
48955027
pub(super) struct FundedChannel<SP: Deref> where SP::Target: SignerProvider {
@@ -9851,16 +9983,18 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
98519983
unfunded_channel_age_ticks: 0,
98529984
holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
98539985
};
9986+
let dual_funding_context = DualFundingChannelContext {
9987+
our_funding_satoshis: funding_satoshis,
9988+
their_funding_satoshis: None,
9989+
funding_tx_locktime,
9990+
funding_feerate_sat_per_1000_weight,
9991+
our_funding_inputs: funding_inputs,
9992+
};
98549993
let chan = Self {
98559994
funding,
98569995
context,
98579996
unfunded_context,
9858-
dual_funding_context: DualFundingChannelContext {
9859-
our_funding_satoshis: funding_satoshis,
9860-
funding_tx_locktime,
9861-
funding_feerate_sat_per_1000_weight,
9862-
our_funding_inputs: funding_inputs,
9863-
},
9997+
dual_funding_context,
98649998
interactive_tx_constructor: None,
98659999
interactive_tx_signing_session: None,
986610000
};
@@ -10002,6 +10136,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
1000210136

1000310137
let dual_funding_context = DualFundingChannelContext {
1000410138
our_funding_satoshis: our_funding_satoshis,
10139+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
1000510140
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
1000610141
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
1000710142
our_funding_inputs: our_funding_inputs.clone(),

0 commit comments

Comments
 (0)