Skip to content

Commit d80f237

Browse files
committed
Add begin_interactive_funding_tx_construction()
1 parent c355ea4 commit d80f237

File tree

2 files changed

+305
-11
lines changed

2 files changed

+305
-11
lines changed

lightning/src/ln/channel.rs

Lines changed: 111 additions & 4 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+
get_output_weight, calculate_change_output_value, 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};
@@ -2215,6 +2215,106 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
22152215
}
22162216

22172217
impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2218+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2219+
pub fn begin_interactive_funding_tx_construction<ES: Deref>(
2220+
&mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2221+
prev_funding_input: Option<(TxIn, TransactionU16LenLimited)>,
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+
if let Some(prev_funding_input) = prev_funding_input {
2229+
funding_inputs.push(prev_funding_input);
2230+
}
2231+
2232+
let mut funding_inputs_prev_outputs: Vec<&TxOut> = Vec::with_capacity(funding_inputs.len());
2233+
// Check that vouts exist for each TxIn in provided transactions.
2234+
for (idx, (txin, tx)) in funding_inputs.iter().enumerate() {
2235+
if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
2236+
funding_inputs_prev_outputs.push(output);
2237+
} else {
2238+
return Err(APIError::APIMisuseError {
2239+
err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs[{}]",
2240+
tx.as_transaction().compute_txid(), txin.previous_output.vout, idx) });
2241+
}
2242+
}
2243+
2244+
let total_input_satoshis: u64 = funding_inputs.iter().map(
2245+
|(txin, tx)| tx.as_transaction().output.get(txin.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
2246+
).sum();
2247+
if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2248+
return Err(APIError::APIMisuseError {
2249+
err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2250+
total_input_satoshis) });
2251+
}
2252+
2253+
// Add output for funding tx
2254+
let mut funding_outputs = Vec::new();
2255+
let funding_output_value_satoshis = self.funding.get_value_satoshis();
2256+
let funding_output_script_pubkey = self.funding.get_funding_redeemscript().to_p2wsh();
2257+
let expected_remote_shared_funding_output = if self.funding.is_outbound() {
2258+
let tx_out = TxOut {
2259+
value: Amount::from_sat(funding_output_value_satoshis),
2260+
script_pubkey: funding_output_script_pubkey,
2261+
};
2262+
funding_outputs.push(
2263+
if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2264+
OutputOwned::SharedControlFullyOwned(tx_out)
2265+
} else {
2266+
OutputOwned::Shared(SharedOwnedOutput::new(
2267+
tx_out, self.dual_funding_context.our_funding_satoshis
2268+
))
2269+
}
2270+
);
2271+
None
2272+
} else {
2273+
Some((funding_output_script_pubkey, funding_output_value_satoshis))
2274+
};
2275+
2276+
// Optionally add change output
2277+
if let Some(change_value) = calculate_change_output_value(
2278+
self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2279+
&funding_inputs_prev_outputs, &funding_outputs,
2280+
self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2281+
self.context.holder_dust_limit_satoshis,
2282+
) {
2283+
let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2284+
|err| APIError::APIMisuseError {
2285+
err: format!("Failed to get change script as new destination script, {:?}", err),
2286+
})?;
2287+
let mut change_output = TxOut {
2288+
value: Amount::from_sat(change_value),
2289+
script_pubkey: change_script,
2290+
};
2291+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2292+
let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2293+
change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
2294+
funding_outputs.push(OutputOwned::Single(change_output));
2295+
}
2296+
2297+
let constructor_args = InteractiveTxConstructorArgs {
2298+
entropy_source,
2299+
holder_node_id,
2300+
counterparty_node_id: self.context.counterparty_node_id,
2301+
channel_id: self.context.channel_id(),
2302+
feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2303+
is_initiator: self.funding.is_outbound(),
2304+
funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2305+
inputs_to_contribute: funding_inputs,
2306+
outputs_to_contribute: funding_outputs,
2307+
expected_remote_shared_funding_output,
2308+
};
2309+
let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2310+
.map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2311+
let msg = tx_constructor.take_initiator_first_message();
2312+
2313+
self.interactive_tx_constructor = Some(tx_constructor);
2314+
2315+
Ok(msg)
2316+
}
2317+
22182318
pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
22192319
InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
22202320
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4871,6 +4971,9 @@ fn check_v2_funding_inputs_sufficient(
48714971
pub(super) struct DualFundingChannelContext {
48724972
/// The amount in satoshis we will be contributing to the channel.
48734973
pub our_funding_satoshis: u64,
4974+
/// The amount in satoshis our counterparty will be contributing to the channel.
4975+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4976+
pub their_funding_satoshis: Option<u64>,
48744977
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
48754978
/// to the current block height to align incentives against fee-sniping.
48764979
pub funding_tx_locktime: LockTime,
@@ -4882,6 +4985,8 @@ pub(super) struct DualFundingChannelContext {
48824985
/// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
48834986
/// minus any fees paid for our contributed weight. This means that change will never be generated
48844987
/// and the maximum value possible will go towards funding the channel.
4988+
///
4989+
/// Note that this field may be emptied once the interactive negotiation has been started.
48854990
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
48864991
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
48874992
}
@@ -9852,6 +9957,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
98529957
unfunded_context,
98539958
dual_funding_context: DualFundingChannelContext {
98549959
our_funding_satoshis: funding_satoshis,
9960+
their_funding_satoshis: None,
98559961
funding_tx_locktime,
98569962
funding_feerate_sat_per_1000_weight,
98579963
our_funding_inputs: funding_inputs,
@@ -9997,6 +10103,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
999710103

999810104
let dual_funding_context = DualFundingChannelContext {
999910105
our_funding_satoshis: our_funding_satoshis,
10106+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
1000010107
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
1000110108
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
1000210109
our_funding_inputs: our_funding_inputs.clone(),

0 commit comments

Comments
 (0)