Skip to content

Commit 0e812e0

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 030a784 commit 0e812e0

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, OnionErrorPacket};
@@ -2220,6 +2220,106 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
22202220
}
22212221

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

4972+
impl DualFundingChannelContext {
4973+
/// Obtain prev outputs for each supplied input and matching transaction.
4974+
/// Will error when a prev tx does not have an output for the specified vout.
4975+
/// Also checks for matching of transaction IDs.
4976+
fn txouts_from_input_prev_txs(inputs: &Vec<(TxIn, TransactionU16LenLimited)>) -> Result<Vec<&TxOut>, ChannelError> {
4977+
let mut prev_outputs: Vec<&TxOut> = Vec::with_capacity(inputs.len());
4978+
// Check that vouts exist for each TxIn in provided transactions.
4979+
for (idx, (txin, tx)) in inputs.iter().enumerate() {
4980+
let txid = tx.as_transaction().compute_txid();
4981+
if txin.previous_output.txid != txid {
4982+
return Err(ChannelError::Warn(
4983+
format!("Transaction input txid mismatch, {} vs. {}, at index {}", txin.previous_output.txid, txid, idx)
4984+
));
4985+
}
4986+
if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
4987+
prev_outputs.push(output);
4988+
} else {
4989+
return Err(ChannelError::Warn(
4990+
format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn, at index {}",
4991+
txid, txin.previous_output.vout, idx)
4992+
));
4993+
}
4994+
}
4995+
Ok(prev_outputs)
4996+
}
4997+
}
4998+
48674999
// Holder designates channel data owned for the benefit of the user client.
48685000
// Counterparty designates channel data owned by the another channel participant entity.
48695001
pub(super) struct FundedChannel<SP: Deref> where SP::Target: SignerProvider {
@@ -9829,16 +9961,18 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
98299961
unfunded_channel_age_ticks: 0,
98309962
holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
98319963
};
9964+
let dual_funding_context = DualFundingChannelContext {
9965+
our_funding_satoshis: funding_satoshis,
9966+
their_funding_satoshis: None,
9967+
funding_tx_locktime,
9968+
funding_feerate_sat_per_1000_weight,
9969+
our_funding_inputs: funding_inputs,
9970+
};
98329971
let chan = Self {
98339972
funding,
98349973
context,
98359974
unfunded_context,
9836-
dual_funding_context: DualFundingChannelContext {
9837-
our_funding_satoshis: funding_satoshis,
9838-
funding_tx_locktime,
9839-
funding_feerate_sat_per_1000_weight,
9840-
our_funding_inputs: funding_inputs,
9841-
},
9975+
dual_funding_context,
98429976
interactive_tx_constructor: None,
98439977
interactive_tx_signing_session: None,
98449978
};
@@ -9980,6 +10114,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
998010114

998110115
let dual_funding_context = DualFundingChannelContext {
998210116
our_funding_satoshis: our_funding_satoshis,
10117+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
998310118
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
998410119
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
998510120
our_funding_inputs: our_funding_inputs.clone(),

0 commit comments

Comments
 (0)