Skip to content

Commit ef08a54

Browse files
committed
Add begin_interactive_funding_tx_construction()
1 parent 030a784 commit ef08a54

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};
@@ -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+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2224+
pub fn begin_interactive_funding_tx_construction<ES: Deref>(
2225+
&mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2226+
prev_funding_input: Option<(TxIn, TransactionU16LenLimited)>,
2227+
) -> Result<Option<InteractiveTxMessageSend>, APIError>
2228+
where ES::Target: EntropySource
2229+
{
2230+
let mut funding_inputs = Vec::new();
2231+
mem::swap(&mut self.dual_funding_context.our_funding_inputs, &mut funding_inputs);
2232+
2233+
if let Some(prev_funding_input) = prev_funding_input {
2234+
funding_inputs.push(prev_funding_input);
2235+
}
2236+
2237+
let mut funding_inputs_prev_outputs: Vec<&TxOut> = Vec::with_capacity(funding_inputs.len());
2238+
// Check that vouts exist for each TxIn in provided transactions.
2239+
for (idx, (txin, tx)) in funding_inputs.iter().enumerate() {
2240+
if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
2241+
funding_inputs_prev_outputs.push(output);
2242+
} else {
2243+
return Err(APIError::APIMisuseError {
2244+
err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs[{}]",
2245+
tx.as_transaction().compute_txid(), txin.previous_output.vout, idx) });
2246+
}
2247+
}
2248+
2249+
let total_input_satoshis: u64 = funding_inputs.iter().map(
2250+
|(txin, tx)| tx.as_transaction().output.get(txin.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
2251+
).sum();
2252+
if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2253+
return Err(APIError::APIMisuseError {
2254+
err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2255+
total_input_satoshis) });
2256+
}
2257+
2258+
// Add output for funding tx
2259+
let mut funding_outputs = Vec::new();
2260+
let funding_output_value_satoshis = self.funding.get_value_satoshis();
2261+
let funding_output_script_pubkey = self.funding.get_funding_redeemscript().to_p2wsh();
2262+
let expected_remote_shared_funding_output = if self.funding.is_outbound() {
2263+
let tx_out = TxOut {
2264+
value: Amount::from_sat(funding_output_value_satoshis),
2265+
script_pubkey: funding_output_script_pubkey,
2266+
};
2267+
funding_outputs.push(
2268+
if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2269+
OutputOwned::SharedControlFullyOwned(tx_out)
2270+
} else {
2271+
OutputOwned::Shared(SharedOwnedOutput::new(
2272+
tx_out, self.dual_funding_context.our_funding_satoshis
2273+
))
2274+
}
2275+
);
2276+
None
2277+
} else {
2278+
Some((funding_output_script_pubkey, funding_output_value_satoshis))
2279+
};
2280+
2281+
// Optionally add change output
2282+
if let Some(change_value) = calculate_change_output_value(
2283+
self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2284+
&funding_inputs_prev_outputs, &funding_outputs,
2285+
self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2286+
self.context.holder_dust_limit_satoshis,
2287+
) {
2288+
let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2289+
|err| APIError::APIMisuseError {
2290+
err: format!("Failed to get change script as new destination script, {:?}", err),
2291+
})?;
2292+
let mut change_output = TxOut {
2293+
value: Amount::from_sat(change_value),
2294+
script_pubkey: change_script,
2295+
};
2296+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2297+
let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2298+
change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
2299+
funding_outputs.push(OutputOwned::Single(change_output));
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,6 +4963,8 @@ 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
}
@@ -9835,6 +9940,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
98359940
unfunded_context,
98369941
dual_funding_context: DualFundingChannelContext {
98379942
our_funding_satoshis: funding_satoshis,
9943+
their_funding_satoshis: None,
98389944
funding_tx_locktime,
98399945
funding_feerate_sat_per_1000_weight,
98409946
our_funding_inputs: funding_inputs,
@@ -9980,6 +10086,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
998010086

998110087
let dual_funding_context = DualFundingChannelContext {
998210088
our_funding_satoshis: our_funding_satoshis,
10089+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
998310090
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
998410091
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
998510092
our_funding_inputs: our_funding_inputs.clone(),

0 commit comments

Comments
 (0)