Skip to content

Commit 2aa29de

Browse files
committed
Add begin_interactive_funding_tx_construction()
1 parent 7c77daf commit 2aa29de

File tree

3 files changed

+312
-16
lines changed

3 files changed

+312
-16
lines changed

lightning/src/ln/channel.rs

Lines changed: 121 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};
@@ -1681,6 +1681,99 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for Channel<SP> where SP::Ta
16811681
}
16821682

16831683
impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
1684+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
1685+
fn begin_interactive_funding_tx_construction<ES: Deref>(
1686+
&mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
1687+
extra_input: Option<(TxIn, TransactionU16LenLimited)>,
1688+
) -> Result<Option<InteractiveTxMessageSend>, APIError>
1689+
where ES::Target: EntropySource
1690+
{
1691+
let mut funding_inputs_with_extra = self.dual_funding_context.our_funding_inputs.take().unwrap_or_else(|| vec![]);
1692+
1693+
if let Some(extra_input) = extra_input {
1694+
funding_inputs_with_extra.push(extra_input);
1695+
}
1696+
1697+
let mut funding_inputs_prev_outputs: Vec<TxOut> = Vec::with_capacity(funding_inputs_with_extra.len());
1698+
// Check that vouts exist for each TxIn in provided transactions.
1699+
for (idx, input) in funding_inputs_with_extra.iter().enumerate() {
1700+
if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
1701+
funding_inputs_prev_outputs.push(output.clone());
1702+
} else {
1703+
return Err(APIError::APIMisuseError {
1704+
err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs_with_extra[{}]",
1705+
input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
1706+
}
1707+
}
1708+
1709+
let total_input_satoshis: u64 = funding_inputs_with_extra.iter().map(
1710+
|input| input.1.as_transaction().output.get(input.0.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
1711+
).sum();
1712+
if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
1713+
return Err(APIError::APIMisuseError {
1714+
err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
1715+
total_input_satoshis) });
1716+
}
1717+
1718+
// Add output for funding tx
1719+
let mut funding_outputs = Vec::new();
1720+
let funding_output_value_satoshis = self.context.get_value_satoshis();
1721+
let funding_output_script_pubkey = self.context.get_funding_redeemscript().to_p2wsh();
1722+
let expected_remote_shared_funding_output = if self.context.is_outbound() {
1723+
let tx_out = TxOut {
1724+
value: Amount::from_sat(funding_output_value_satoshis),
1725+
script_pubkey: funding_output_script_pubkey,
1726+
};
1727+
funding_outputs.push(
1728+
if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
1729+
OutputOwned::SharedControlFullyOwned(tx_out)
1730+
} else {
1731+
OutputOwned::Shared(SharedOwnedOutput::new(
1732+
tx_out, self.dual_funding_context.our_funding_satoshis
1733+
))
1734+
}
1735+
);
1736+
None
1737+
} else {
1738+
Some((funding_output_script_pubkey, funding_output_value_satoshis))
1739+
};
1740+
1741+
// Optionally add change output
1742+
if let Some(change_value) = need_to_add_funding_change_output(
1743+
self.context.is_outbound(), self.dual_funding_context.our_funding_satoshis,
1744+
&funding_inputs_prev_outputs, &funding_outputs,
1745+
self.dual_funding_context.funding_feerate_sat_per_1000_weight,
1746+
self.context.holder_dust_limit_satoshis,
1747+
) {
1748+
let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
1749+
|err| APIError::APIMisuseError {
1750+
err: format!("Failed to get change script as new destination script, {:?}", err),
1751+
})?;
1752+
let _res = add_funding_change_output(
1753+
change_value, change_script, &mut funding_outputs, self.dual_funding_context.funding_feerate_sat_per_1000_weight);
1754+
}
1755+
1756+
let constructor_args = InteractiveTxConstructorArgs {
1757+
entropy_source,
1758+
holder_node_id,
1759+
counterparty_node_id: self.context.counterparty_node_id,
1760+
channel_id: self.context.channel_id(),
1761+
feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
1762+
is_initiator: self.context.is_outbound(),
1763+
funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
1764+
inputs_to_contribute: funding_inputs_with_extra,
1765+
outputs_to_contribute: funding_outputs,
1766+
expected_remote_shared_funding_output,
1767+
};
1768+
let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
1769+
.map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
1770+
let msg = tx_constructor.take_initiator_first_message();
1771+
1772+
self.interactive_tx_constructor.replace(tx_constructor);
1773+
1774+
Ok(msg)
1775+
}
1776+
16841777
pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
16851778
InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
16861779
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4103,7 +4196,22 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
41034196
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
41044197
}
41054198

4106-
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
4199+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
4200+
fn add_funding_change_output(
4201+
change_value: u64, change_script: ScriptBuf,
4202+
funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4203+
) -> TxOut {
4204+
let mut change_output = TxOut {
4205+
value: Amount::from_sat(change_value),
4206+
script_pubkey: change_script,
4207+
};
4208+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4209+
let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4210+
change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
4211+
funding_outputs.push(OutputOwned::Single(change_output.clone()));
4212+
change_output
4213+
}
4214+
41074215
pub(super) fn calculate_our_funding_satoshis(
41084216
is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
41094217
total_witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32,
@@ -4149,6 +4257,9 @@ pub(super) fn calculate_our_funding_satoshis(
41494257
pub(super) struct DualFundingChannelContext {
41504258
/// The amount in satoshis we will be contributing to the channel.
41514259
pub our_funding_satoshis: u64,
4260+
/// The amount in satoshis our counterparty will be contributing to the channel.
4261+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4262+
pub their_funding_satoshis: Option<u64>,
41524263
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
41534264
/// to the current block height to align incentives against fee-sniping.
41544265
pub funding_tx_locktime: LockTime,
@@ -4161,7 +4272,7 @@ pub(super) struct DualFundingChannelContext {
41614272
/// minus any fees paid for our contributed weight. This means that change will never be generated
41624273
/// and the maximum value possible will go towards funding the channel.
41634274
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4164-
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4275+
pub our_funding_inputs: Option<Vec<(TxIn, TransactionU16LenLimited)>>,
41654276
}
41664277

41674278
// Holder designates channel data owned for the benefit of the user client.
@@ -8834,9 +8945,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
88348945
unfunded_context,
88358946
dual_funding_context: DualFundingChannelContext {
88368947
our_funding_satoshis: funding_satoshis,
8948+
their_funding_satoshis: None,
88378949
funding_tx_locktime,
88388950
funding_feerate_sat_per_1000_weight,
8839-
our_funding_inputs: funding_inputs,
8951+
our_funding_inputs: Some(funding_inputs),
88408952
},
88418953
interactive_tx_constructor: None,
88428954
};
@@ -8982,9 +9094,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
89829094

89839095
let dual_funding_context = DualFundingChannelContext {
89849096
our_funding_satoshis: funding_satoshis,
9097+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
89859098
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
89869099
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
8987-
our_funding_inputs: funding_inputs.clone(),
9100+
our_funding_inputs: Some(funding_inputs.clone()),
89889101
};
89899102

89909103
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};
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)