Skip to content

Commit c44c9ad

Browse files
committed
Add begin_interactive_funding_tx_construction()
1 parent 6a64dd1 commit c44c9ad

File tree

2 files changed

+311
-14
lines changed

2 files changed

+311
-14
lines changed

lightning/src/ln/channel.rs

Lines changed: 121 additions & 7 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, need_to_add_funding_change_output, 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};
@@ -2239,6 +2239,99 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
22392239
}
22402240

22412241
impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2242+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2243+
fn begin_interactive_funding_tx_construction<ES: Deref>(
2244+
&mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2245+
extra_input: Option<(TxIn, TransactionU16LenLimited)>,
2246+
) -> Result<Option<InteractiveTxMessageSend>, APIError>
2247+
where ES::Target: EntropySource
2248+
{
2249+
let mut funding_inputs_with_extra = self.dual_funding_context.our_funding_inputs.take().unwrap_or_else(|| vec![]);
2250+
2251+
if let Some(extra_input) = extra_input {
2252+
funding_inputs_with_extra.push(extra_input);
2253+
}
2254+
2255+
let mut funding_inputs_prev_outputs: Vec<TxOut> = Vec::with_capacity(funding_inputs_with_extra.len());
2256+
// Check that vouts exist for each TxIn in provided transactions.
2257+
for (idx, input) in funding_inputs_with_extra.iter().enumerate() {
2258+
if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
2259+
funding_inputs_prev_outputs.push(output.clone());
2260+
} else {
2261+
return Err(APIError::APIMisuseError {
2262+
err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs_with_extra[{}]",
2263+
input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
2264+
}
2265+
}
2266+
2267+
let total_input_satoshis: u64 = funding_inputs_with_extra.iter().map(
2268+
|input| input.1.as_transaction().output.get(input.0.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
2269+
).sum();
2270+
if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2271+
return Err(APIError::APIMisuseError {
2272+
err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2273+
total_input_satoshis) });
2274+
}
2275+
2276+
// Add output for funding tx
2277+
let mut funding_outputs = Vec::new();
2278+
let funding_output_value_satoshis = self.funding.get_value_satoshis();
2279+
let funding_output_script_pubkey = self.funding.get_funding_redeemscript().to_p2wsh();
2280+
let expected_remote_shared_funding_output = if self.funding.is_outbound() {
2281+
let tx_out = TxOut {
2282+
value: Amount::from_sat(funding_output_value_satoshis),
2283+
script_pubkey: funding_output_script_pubkey,
2284+
};
2285+
funding_outputs.push(
2286+
if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2287+
OutputOwned::SharedControlFullyOwned(tx_out)
2288+
} else {
2289+
OutputOwned::Shared(SharedOwnedOutput::new(
2290+
tx_out, self.dual_funding_context.our_funding_satoshis
2291+
))
2292+
}
2293+
);
2294+
None
2295+
} else {
2296+
Some((funding_output_script_pubkey, funding_output_value_satoshis))
2297+
};
2298+
2299+
// Optionally add change output
2300+
if let Some(change_value) = need_to_add_funding_change_output(
2301+
self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2302+
&funding_inputs_prev_outputs, &funding_outputs,
2303+
self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2304+
self.context.holder_dust_limit_satoshis,
2305+
) {
2306+
let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2307+
|err| APIError::APIMisuseError {
2308+
err: format!("Failed to get change script as new destination script, {:?}", err),
2309+
})?;
2310+
let _res = add_funding_change_output(
2311+
change_value, change_script, &mut funding_outputs, self.dual_funding_context.funding_feerate_sat_per_1000_weight);
2312+
}
2313+
2314+
let constructor_args = InteractiveTxConstructorArgs {
2315+
entropy_source,
2316+
holder_node_id,
2317+
counterparty_node_id: self.context.counterparty_node_id,
2318+
channel_id: self.context.channel_id(),
2319+
feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2320+
is_initiator: self.funding.is_outbound(),
2321+
funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2322+
inputs_to_contribute: funding_inputs_with_extra,
2323+
outputs_to_contribute: funding_outputs,
2324+
expected_remote_shared_funding_output,
2325+
};
2326+
let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2327+
.map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2328+
let msg = tx_constructor.take_initiator_first_message();
2329+
2330+
self.interactive_tx_constructor.replace(tx_constructor);
2331+
2332+
Ok(msg)
2333+
}
2334+
22422335
pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
22432336
InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
22442337
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4915,10 +5008,29 @@ fn check_v2_funding_inputs_sufficient(
49155008
}
49165009
}
49175010

5011+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
5012+
fn add_funding_change_output(
5013+
change_value: u64, change_script: ScriptBuf,
5014+
funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
5015+
) -> TxOut {
5016+
let mut change_output = TxOut {
5017+
value: Amount::from_sat(change_value),
5018+
script_pubkey: change_script,
5019+
};
5020+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
5021+
let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
5022+
change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
5023+
funding_outputs.push(OutputOwned::Single(change_output.clone()));
5024+
change_output
5025+
}
5026+
49185027
/// Context for dual-funded channels.
49195028
pub(super) struct DualFundingChannelContext {
49205029
/// The amount in satoshis we will be contributing to the channel.
49215030
pub our_funding_satoshis: u64,
5031+
/// The amount in satoshis our counterparty will be contributing to the channel.
5032+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
5033+
pub their_funding_satoshis: Option<u64>,
49225034
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
49235035
/// to the current block height to align incentives against fee-sniping.
49245036
pub funding_tx_locktime: LockTime,
@@ -4931,7 +5043,7 @@ pub(super) struct DualFundingChannelContext {
49315043
/// minus any fees paid for our contributed weight. This means that change will never be generated
49325044
/// and the maximum value possible will go towards funding the channel.
49335045
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4934-
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
5046+
pub our_funding_inputs: Option<Vec<(TxIn, TransactionU16LenLimited)>>,
49355047
}
49365048

49375049
// Holder designates channel data owned for the benefit of the user client.
@@ -9920,9 +10032,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
992010032
unfunded_context,
992110033
dual_funding_context: DualFundingChannelContext {
992210034
our_funding_satoshis: funding_satoshis,
10035+
their_funding_satoshis: None,
992310036
funding_tx_locktime,
992410037
funding_feerate_sat_per_1000_weight,
9925-
our_funding_inputs: funding_inputs,
10038+
our_funding_inputs: Some(funding_inputs),
992610039
},
992710040
interactive_tx_constructor: None,
992810041
interactive_tx_signing_session: None,
@@ -10065,9 +10178,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
1006510178

1006610179
let dual_funding_context = DualFundingChannelContext {
1006710180
our_funding_satoshis: our_funding_satoshis,
10181+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
1006810182
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
1006910183
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
10070-
our_funding_inputs: our_funding_inputs.clone(),
10184+
our_funding_inputs: Some(our_funding_inputs.clone()),
1007110185
};
1007210186

1007310187
let interactive_tx_constructor = Some(InteractiveTxConstructor::new(

0 commit comments

Comments
 (0)