Skip to content

Commit 0e47819

Browse files
committed
Add begin_interactive_funding_tx_construction()
1 parent 8a54da6 commit 0e47819

File tree

2 files changed

+336
-18
lines changed

2 files changed

+336
-18
lines changed

lightning/src/ln/channel.rs

+146-11
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};
@@ -1161,6 +1161,7 @@ impl<'a, SP: Deref> ChannelPhase<SP> where
11611161
}
11621162

11631163
/// Contains all state common to unfunded inbound/outbound channels.
1164+
#[derive(Default)]
11641165
pub(super) struct UnfundedChannelContext {
11651166
/// A counter tracking how many ticks have elapsed since this unfunded channel was
11661167
/// created. If this unfunded channel reaches peer has yet to respond after reaching
@@ -1684,6 +1685,103 @@ pub(super) trait InteractivelyFunded<SP: Deref> where SP::Target: SignerProvider
16841685

16851686
fn dual_funding_context(&self) -> &DualFundingChannelContext;
16861687

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

18541960
impl<SP: Deref> InteractivelyFunded<SP> for InboundV2Channel<SP> where SP::Target: SignerProvider {
@@ -1861,9 +1967,17 @@ impl<SP: Deref> InteractivelyFunded<SP> for InboundV2Channel<SP> where SP::Targe
18611967
fn dual_funding_context(&self) -> &DualFundingChannelContext {
18621968
&self.dual_funding_context
18631969
}
1970+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
1971+
fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext {
1972+
&mut self.dual_funding_context
1973+
}
18641974
fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
18651975
&mut self.interactive_tx_constructor
18661976
}
1977+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
1978+
fn is_initiator(&self) -> bool {
1979+
false
1980+
}
18671981
}
18681982

18691983
impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
@@ -4150,6 +4264,22 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
41504264
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
41514265
}
41524266

4267+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
4268+
fn add_funding_change_output(
4269+
change_value: u64, change_script: ScriptBuf,
4270+
funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4271+
) -> TxOut {
4272+
let mut change_output = TxOut {
4273+
value: Amount::from_sat(change_value),
4274+
script_pubkey: change_script,
4275+
};
4276+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4277+
let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4278+
change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
4279+
funding_outputs.push(OutputOwned::Single(change_output.clone()));
4280+
change_output
4281+
}
4282+
41534283
pub(super) fn calculate_our_funding_satoshis(
41544284
is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
41554285
total_witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32,
@@ -4195,6 +4325,9 @@ pub(super) fn calculate_our_funding_satoshis(
41954325
pub(super) struct DualFundingChannelContext {
41964326
/// The amount in satoshis we will be contributing to the channel.
41974327
pub our_funding_satoshis: u64,
4328+
/// The amount in satoshis our counterparty will be contributing to the channel.
4329+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4330+
pub their_funding_satoshis: Option<u64>,
41984331
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
41994332
/// to the current block height to align incentives against fee-sniping.
42004333
pub funding_tx_locktime: LockTime,
@@ -4206,7 +4339,7 @@ pub(super) struct DualFundingChannelContext {
42064339
/// minus any fees paid for our contributed weight. This means that change will never be generated
42074340
/// and the maximum value possible will go towards funding the channel.
42084341
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4209-
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4342+
pub our_funding_inputs: Option<Vec<(TxIn, TransactionU16LenLimited)>>,
42104343
}
42114344

42124345
// Holder designates channel data owned for the benefit of the user client.
@@ -8295,7 +8428,7 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
82958428
pubkeys,
82968429
logger,
82978430
)?,
8298-
unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 }
8431+
unfunded_context: UnfundedChannelContext::default(),
82998432
};
83008433
Ok(chan)
83018434
}
@@ -8599,7 +8732,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
85998732
msg.push_msat,
86008733
msg.common_fields.clone(),
86018734
)?,
8602-
unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 },
8735+
unfunded_context: UnfundedChannelContext::default(),
86038736
};
86048737
Ok(chan)
86058738
}
@@ -8782,12 +8915,13 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
87828915
pubkeys,
87838916
logger,
87848917
)?,
8785-
unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 },
8918+
unfunded_context: UnfundedChannelContext::default(),
87868919
dual_funding_context: DualFundingChannelContext {
87878920
our_funding_satoshis: funding_satoshis,
8921+
their_funding_satoshis: None,
87888922
funding_tx_locktime,
87898923
funding_feerate_sat_per_1000_weight,
8790-
our_funding_inputs: funding_inputs,
8924+
our_funding_inputs: Some(funding_inputs),
87918925
},
87928926
interactive_tx_constructor: None,
87938927
};
@@ -8948,9 +9082,10 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
89489082

89499083
let dual_funding_context = DualFundingChannelContext {
89509084
our_funding_satoshis: funding_satoshis,
9085+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
89519086
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
89529087
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
8953-
our_funding_inputs: funding_inputs.clone(),
9088+
our_funding_inputs: Some(funding_inputs.clone()),
89549089
};
89559090

89569091
let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
@@ -8975,7 +9110,7 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
89759110
context,
89769111
dual_funding_context,
89779112
interactive_tx_constructor,
8978-
unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 },
9113+
unfunded_context: UnfundedChannelContext::default(),
89799114
})
89809115
}
89819116

0 commit comments

Comments
 (0)