Skip to content

Commit c778534

Browse files
committed
Add begin_interactive_funding_tx_construction()
1 parent 85d1e5f commit c778534

File tree

3 files changed

+332
-16
lines changed

3 files changed

+332
-16
lines changed

lightning/src/ln/channel.rs

Lines changed: 141 additions & 8 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};
@@ -1693,8 +1693,105 @@ pub(super) trait InteractivelyFunded<SP: Deref> where SP::Target: SignerProvider
16931693

16941694
fn dual_funding_context(&self) -> &DualFundingChannelContext;
16951695

1696+
fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext;
1697+
16961698
fn unfunded_context(&self) -> &UnfundedChannelContext;
16971699

1700+
fn is_initiator(&self) -> bool;
1701+
1702+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
1703+
fn begin_interactive_funding_tx_construction<ES: Deref>(
1704+
&mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
1705+
extra_input: Option<(TxIn, TransactionU16LenLimited)>,
1706+
) -> Result<Option<InteractiveTxMessageSend>, APIError>
1707+
where ES::Target: EntropySource
1708+
{
1709+
let mut funding_inputs_with_extra = self.dual_funding_context_mut().our_funding_inputs.take().unwrap_or_else(|| vec![]);
1710+
1711+
if let Some(extra_input) = extra_input {
1712+
funding_inputs_with_extra.push(extra_input);
1713+
}
1714+
1715+
let mut funding_inputs_prev_outputs: Vec<TxOut> = Vec::with_capacity(funding_inputs_with_extra.len());
1716+
// Check that vouts exist for each TxIn in provided transactions.
1717+
for (idx, input) in funding_inputs_with_extra.iter().enumerate() {
1718+
if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
1719+
funding_inputs_prev_outputs.push(output.clone());
1720+
} else {
1721+
return Err(APIError::APIMisuseError {
1722+
err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs_with_extra[{}]",
1723+
input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
1724+
}
1725+
}
1726+
1727+
let total_input_satoshis: u64 = funding_inputs_with_extra.iter().map(
1728+
|input| input.1.as_transaction().output.get(input.0.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
1729+
).sum();
1730+
if total_input_satoshis < self.dual_funding_context().our_funding_satoshis {
1731+
return Err(APIError::APIMisuseError {
1732+
err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
1733+
total_input_satoshis) });
1734+
}
1735+
1736+
// Add output for funding tx
1737+
let mut funding_outputs = Vec::new();
1738+
let funding_output_value_satoshis = self.context().get_value_satoshis();
1739+
let funding_output_script_pubkey = self.context().get_funding_redeemscript().to_p2wsh();
1740+
let expected_remote_shared_funding_output = if self.is_initiator() {
1741+
let tx_out = TxOut {
1742+
value: Amount::from_sat(funding_output_value_satoshis),
1743+
script_pubkey: funding_output_script_pubkey,
1744+
};
1745+
funding_outputs.push(
1746+
if self.dual_funding_context().their_funding_satoshis.unwrap_or(0) == 0 {
1747+
OutputOwned::SharedControlFullyOwned(tx_out)
1748+
} else {
1749+
OutputOwned::Shared(SharedOwnedOutput::new(
1750+
tx_out, self.dual_funding_context().our_funding_satoshis
1751+
))
1752+
}
1753+
);
1754+
None
1755+
} else {
1756+
Some((funding_output_script_pubkey, funding_output_value_satoshis))
1757+
};
1758+
1759+
// Optionally add change output
1760+
if let Some(change_value) = need_to_add_funding_change_output(
1761+
self.is_initiator(), self.dual_funding_context().our_funding_satoshis,
1762+
&funding_inputs_prev_outputs, &funding_outputs,
1763+
self.dual_funding_context().funding_feerate_sat_per_1000_weight,
1764+
self.context().holder_dust_limit_satoshis,
1765+
) {
1766+
let change_script = signer_provider.get_destination_script(self.context().channel_keys_id).map_err(
1767+
|err| APIError::APIMisuseError {
1768+
err: format!("Failed to get change script as new destination script, {:?}", err),
1769+
})?;
1770+
let _res = add_funding_change_output(
1771+
change_value, change_script, &mut funding_outputs, self.dual_funding_context().funding_feerate_sat_per_1000_weight);
1772+
}
1773+
1774+
let constructor_args = InteractiveTxConstructorArgs {
1775+
entropy_source,
1776+
holder_node_id,
1777+
counterparty_node_id: self.context().counterparty_node_id,
1778+
channel_id: self.context().channel_id(),
1779+
feerate_sat_per_kw: self.dual_funding_context_mut().funding_feerate_sat_per_1000_weight,
1780+
is_initiator: self.is_initiator(),
1781+
funding_tx_locktime: self.dual_funding_context_mut().funding_tx_locktime,
1782+
inputs_to_contribute: funding_inputs_with_extra,
1783+
outputs_to_contribute: funding_outputs,
1784+
expected_remote_shared_funding_output,
1785+
};
1786+
let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
1787+
.map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
1788+
let msg = tx_constructor.take_initiator_first_message();
1789+
1790+
self.interactive_tx_constructor_mut().replace(tx_constructor);
1791+
1792+
Ok(msg)
1793+
}
1794+
16981795
fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
16991796
InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
17001797
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -1859,12 +1956,20 @@ impl<SP: Deref> InteractivelyFunded<SP> for OutboundV2Channel<SP> where SP::Targ
18591956
fn dual_funding_context(&self) -> &DualFundingChannelContext {
18601957
&self.dual_funding_context
18611958
}
1959+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
1960+
fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext {
1961+
&mut self.dual_funding_context
1962+
}
18621963
fn unfunded_context(&self) -> &UnfundedChannelContext {
18631964
&self.unfunded_context
18641965
}
18651966
fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
18661967
&mut self.interactive_tx_constructor
18671968
}
1969+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
1970+
fn is_initiator(&self) -> bool {
1971+
true
1972+
}
18681973
}
18691974

18701975
impl<SP: Deref> InteractivelyFunded<SP> for InboundV2Channel<SP> where SP::Target: SignerProvider {
@@ -1877,12 +1982,20 @@ impl<SP: Deref> InteractivelyFunded<SP> for InboundV2Channel<SP> where SP::Targe
18771982
fn dual_funding_context(&self) -> &DualFundingChannelContext {
18781983
&self.dual_funding_context
18791984
}
1985+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
1986+
fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext {
1987+
&mut self.dual_funding_context
1988+
}
18801989
fn unfunded_context(&self) -> &UnfundedChannelContext {
18811990
&self.unfunded_context
18821991
}
18831992
fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
18841993
&mut self.interactive_tx_constructor
18851994
}
1995+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
1996+
fn is_initiator(&self) -> bool {
1997+
false
1998+
}
18861999
}
18872000

18882001
impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
@@ -4154,7 +4267,22 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
41544267
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
41554268
}
41564269

4157-
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
4270+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
4271+
fn add_funding_change_output(
4272+
change_value: u64, change_script: ScriptBuf,
4273+
funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4274+
) -> TxOut {
4275+
let mut change_output = TxOut {
4276+
value: Amount::from_sat(change_value),
4277+
script_pubkey: change_script,
4278+
};
4279+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4280+
let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4281+
change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
4282+
funding_outputs.push(OutputOwned::Single(change_output.clone()));
4283+
change_output
4284+
}
4285+
41584286
pub(super) fn calculate_our_funding_satoshis(
41594287
is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
41604288
total_witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32,
@@ -4200,6 +4328,9 @@ pub(super) fn calculate_our_funding_satoshis(
42004328
pub(super) struct DualFundingChannelContext {
42014329
/// The amount in satoshis we will be contributing to the channel.
42024330
pub our_funding_satoshis: u64,
4331+
/// The amount in satoshis our counterparty will be contributing to the channel.
4332+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4333+
pub their_funding_satoshis: Option<u64>,
42034334
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
42044335
/// to the current block height to align incentives against fee-sniping.
42054336
pub funding_tx_locktime: LockTime,
@@ -4212,7 +4343,7 @@ pub(super) struct DualFundingChannelContext {
42124343
/// minus any fees paid for our contributed weight. This means that change will never be generated
42134344
/// and the maximum value possible will go towards funding the channel.
42144345
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4215-
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4346+
pub our_funding_inputs: Option<Vec<(TxIn, TransactionU16LenLimited)>>,
42164347
}
42174348

42184349
// Holder designates channel data owned for the benefit of the user client.
@@ -8885,9 +9016,10 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
88859016
unfunded_context,
88869017
dual_funding_context: DualFundingChannelContext {
88879018
our_funding_satoshis: funding_satoshis,
9019+
their_funding_satoshis: None,
88889020
funding_tx_locktime,
88899021
funding_feerate_sat_per_1000_weight,
8890-
our_funding_inputs: funding_inputs,
9022+
our_funding_inputs: Some(funding_inputs),
88919023
},
88929024
interactive_tx_constructor: None,
88939025
};
@@ -9053,9 +9185,10 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
90539185

90549186
let dual_funding_context = DualFundingChannelContext {
90559187
our_funding_satoshis: funding_satoshis,
9188+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
90569189
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
90579190
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
9058-
our_funding_inputs: funding_inputs.clone(),
9191+
our_funding_inputs: Some(funding_inputs.clone()),
90599192
};
90609193

90619194
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, ChannelPhase, ChannelError, ChannelUpdateStatus, ShutdownResult, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel, WithChannelContext, InteractivelyFunded as _};
52-
#[cfg(any(dual_funding, splicing))]
52+
#[cfg(dual_funding)]
5353
use crate::ln::channel::InboundV2Channel;
5454
use crate::ln::channel_state::ChannelDetails;
5555
use crate::types::features::{Bolt12InvoiceFeatures, ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};

0 commit comments

Comments
 (0)