Skip to content

Commit 5ec09c7

Browse files
committed
Add begin_interactive_funding_tx_construction()
1 parent 609f89d commit 5ec09c7

File tree

3 files changed

+312
-15
lines changed

3 files changed

+312
-15
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;
1515
use bitcoin::sighash::EcdsaSighashType;
1616
use bitcoin::consensus::encode;
@@ -31,9 +31,9 @@ use crate::ln::types::ChannelId;
3131
use crate::types::payment::{PaymentPreimage, PaymentHash};
3232
use crate::types::features::{ChannelTypeFeatures, InitFeatures};
3333
use crate::ln::interactivetxs::{
34-
get_output_weight, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
35-
InteractiveTxConstructorArgs, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
36-
TX_COMMON_FIELDS_WEIGHT,
34+
get_output_weight, need_to_add_funding_change_output, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
35+
InteractiveTxConstructorArgs, InteractiveTxMessageSend, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
36+
OutputOwned, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
3737
};
3838
use crate::ln::msgs;
3939
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError};
@@ -2129,6 +2129,99 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
21292129
}
21302130

21312131
impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2132+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2133+
fn begin_interactive_funding_tx_construction<ES: Deref>(
2134+
&mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2135+
extra_input: Option<(TxIn, TransactionU16LenLimited)>,
2136+
) -> Result<Option<InteractiveTxMessageSend>, APIError>
2137+
where ES::Target: EntropySource
2138+
{
2139+
let mut funding_inputs_with_extra = self.dual_funding_context.our_funding_inputs.take().unwrap_or_else(|| vec![]);
2140+
2141+
if let Some(extra_input) = extra_input {
2142+
funding_inputs_with_extra.push(extra_input);
2143+
}
2144+
2145+
let mut funding_inputs_prev_outputs: Vec<TxOut> = Vec::with_capacity(funding_inputs_with_extra.len());
2146+
// Check that vouts exist for each TxIn in provided transactions.
2147+
for (idx, input) in funding_inputs_with_extra.iter().enumerate() {
2148+
if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
2149+
funding_inputs_prev_outputs.push(output.clone());
2150+
} else {
2151+
return Err(APIError::APIMisuseError {
2152+
err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs_with_extra[{}]",
2153+
input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
2154+
}
2155+
}
2156+
2157+
let total_input_satoshis: u64 = funding_inputs_with_extra.iter().map(
2158+
|input| input.1.as_transaction().output.get(input.0.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
2159+
).sum();
2160+
if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2161+
return Err(APIError::APIMisuseError {
2162+
err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2163+
total_input_satoshis) });
2164+
}
2165+
2166+
// Add output for funding tx
2167+
let mut funding_outputs = Vec::new();
2168+
let funding_output_value_satoshis = self.funding.get_value_satoshis();
2169+
let funding_output_script_pubkey = self.context.get_funding_redeemscript().to_p2wsh();
2170+
let expected_remote_shared_funding_output = if self.context.is_outbound() {
2171+
let tx_out = TxOut {
2172+
value: Amount::from_sat(funding_output_value_satoshis),
2173+
script_pubkey: funding_output_script_pubkey,
2174+
};
2175+
funding_outputs.push(
2176+
if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2177+
OutputOwned::SharedControlFullyOwned(tx_out)
2178+
} else {
2179+
OutputOwned::Shared(SharedOwnedOutput::new(
2180+
tx_out, self.dual_funding_context.our_funding_satoshis
2181+
))
2182+
}
2183+
);
2184+
None
2185+
} else {
2186+
Some((funding_output_script_pubkey, funding_output_value_satoshis))
2187+
};
2188+
2189+
// Optionally add change output
2190+
if let Some(change_value) = need_to_add_funding_change_output(
2191+
self.context.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2192+
&funding_inputs_prev_outputs, &funding_outputs,
2193+
self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2194+
self.context.holder_dust_limit_satoshis,
2195+
) {
2196+
let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2197+
|err| APIError::APIMisuseError {
2198+
err: format!("Failed to get change script as new destination script, {:?}", err),
2199+
})?;
2200+
let _res = add_funding_change_output(
2201+
change_value, change_script, &mut funding_outputs, self.dual_funding_context.funding_feerate_sat_per_1000_weight);
2202+
}
2203+
2204+
let constructor_args = InteractiveTxConstructorArgs {
2205+
entropy_source,
2206+
holder_node_id,
2207+
counterparty_node_id: self.context.counterparty_node_id,
2208+
channel_id: self.context.channel_id(),
2209+
feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2210+
is_initiator: self.context.is_outbound(),
2211+
funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2212+
inputs_to_contribute: funding_inputs_with_extra,
2213+
outputs_to_contribute: funding_outputs,
2214+
expected_remote_shared_funding_output,
2215+
};
2216+
let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2217+
.map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2218+
let msg = tx_constructor.take_initiator_first_message();
2219+
2220+
self.interactive_tx_constructor.replace(tx_constructor);
2221+
2222+
Ok(msg)
2223+
}
2224+
21322225
pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
21332226
InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
21342227
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4631,10 +4724,29 @@ fn estimate_v2_funding_transaction_fee(
46314724
fee_for_weight(funding_feerate_sat_per_1000_weight, weight)
46324725
}
46334726

4727+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
4728+
fn add_funding_change_output(
4729+
change_value: u64, change_script: ScriptBuf,
4730+
funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4731+
) -> TxOut {
4732+
let mut change_output = TxOut {
4733+
value: Amount::from_sat(change_value),
4734+
script_pubkey: change_script,
4735+
};
4736+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4737+
let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4738+
change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
4739+
funding_outputs.push(OutputOwned::Single(change_output.clone()));
4740+
change_output
4741+
}
4742+
46344743
/// Context for dual-funded channels.
46354744
pub(super) struct DualFundingChannelContext {
46364745
/// The amount in satoshis we will be contributing to the channel.
46374746
pub our_funding_satoshis: u64,
4747+
/// The amount in satoshis our counterparty will be contributing to the channel.
4748+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4749+
pub their_funding_satoshis: Option<u64>,
46384750
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
46394751
/// to the current block height to align incentives against fee-sniping.
46404752
pub funding_tx_locktime: LockTime,
@@ -4647,7 +4759,7 @@ pub(super) struct DualFundingChannelContext {
46474759
/// minus any fees paid for our contributed weight. This means that change will never be generated
46484760
/// and the maximum value possible will go towards funding the channel.
46494761
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4650-
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4762+
pub our_funding_inputs: Option<Vec<(TxIn, TransactionU16LenLimited)>>,
46514763
}
46524764

46534765
// Holder designates channel data owned for the benefit of the user client.
@@ -9573,9 +9685,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
95739685
unfunded_context,
95749686
dual_funding_context: DualFundingChannelContext {
95759687
our_funding_satoshis: funding_satoshis,
9688+
their_funding_satoshis: None,
95769689
funding_tx_locktime,
95779690
funding_feerate_sat_per_1000_weight,
9578-
our_funding_inputs: funding_inputs,
9691+
our_funding_inputs: Some(funding_inputs),
95799692
},
95809693
interactive_tx_constructor: None,
95819694
};
@@ -9719,9 +9832,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
97199832

97209833
let dual_funding_context = DualFundingChannelContext {
97219834
our_funding_satoshis: our_funding_satoshis,
9835+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
97229836
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
97239837
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
9724-
our_funding_inputs: our_funding_inputs.clone(),
9838+
our_funding_inputs: Some(our_funding_inputs.clone()),
97259839
};
97269840

97279841
let interactive_tx_constructor = Some(InteractiveTxConstructor::new(

lightning/src/ln/channelmanager.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ use crate::ln::inbound_payment;
4949
use crate::ln::types::ChannelId;
5050
use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
5151
use crate::ln::channel::{self, Channel, ChannelError, ChannelUpdateStatus, FundedChannel, ShutdownResult, UpdateFulfillCommitFetch, OutboundV1Channel, ReconnectionMsg, InboundV1Channel, WithChannelContext};
52-
#[cfg(any(dual_funding, splicing))]
52+
#[cfg(dual_funding)]
5353
use crate::ln::channel::PendingV2Channel;
5454
use crate::ln::channel_state::ChannelDetails;
5555
use crate::types::features::{Bolt12InvoiceFeatures, ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};

0 commit comments

Comments
 (0)