10
10
use bitcoin::amount::Amount;
11
11
use bitcoin::constants::ChainHash;
12
12
use bitcoin::script::{Script, ScriptBuf, Builder, WScriptHash};
13
- use bitcoin::transaction::{Transaction, TxIn};
13
+ use bitcoin::transaction::{Transaction, TxIn, TxOut };
14
14
use bitcoin::sighash;
15
15
use bitcoin::sighash::EcdsaSighashType;
16
16
use bitcoin::consensus::encode;
@@ -31,9 +31,9 @@ use crate::ln::types::ChannelId;
31
31
use crate::types::payment::{PaymentPreimage, PaymentHash};
32
32
use crate::types::features::{ChannelTypeFeatures, InitFeatures};
33
33
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,
37
37
};
38
38
use crate::ln::msgs;
39
39
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError};
@@ -1693,8 +1693,105 @@ pub(super) trait InteractivelyFunded<SP: Deref> where SP::Target: SignerProvider
1693
1693
1694
1694
fn dual_funding_context(&self) -> &DualFundingChannelContext;
1695
1695
1696
+ fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext;
1697
+
1696
1698
fn unfunded_context(&self) -> &UnfundedChannelContext;
1697
1699
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
+
1698
1795
fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
1699
1796
InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
1700
1797
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
1859
1956
fn dual_funding_context(&self) -> &DualFundingChannelContext {
1860
1957
&self.dual_funding_context
1861
1958
}
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
+ }
1862
1963
fn unfunded_context(&self) -> &UnfundedChannelContext {
1863
1964
&self.unfunded_context
1864
1965
}
1865
1966
fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
1866
1967
&mut self.interactive_tx_constructor
1867
1968
}
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
+ }
1868
1973
}
1869
1974
1870
1975
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
1877
1982
fn dual_funding_context(&self) -> &DualFundingChannelContext {
1878
1983
&self.dual_funding_context
1879
1984
}
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
+ }
1880
1989
fn unfunded_context(&self) -> &UnfundedChannelContext {
1881
1990
&self.unfunded_context
1882
1991
}
1883
1992
fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
1884
1993
&mut self.interactive_tx_constructor
1885
1994
}
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
+ }
1886
1999
}
1887
2000
1888
2001
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
4154
4267
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
4155
4268
}
4156
4269
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
+
4158
4286
pub(super) fn calculate_our_funding_satoshis(
4159
4287
is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
4160
4288
total_witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32,
@@ -4200,6 +4328,9 @@ pub(super) fn calculate_our_funding_satoshis(
4200
4328
pub(super) struct DualFundingChannelContext {
4201
4329
/// The amount in satoshis we will be contributing to the channel.
4202
4330
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>,
4203
4334
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
4204
4335
/// to the current block height to align incentives against fee-sniping.
4205
4336
pub funding_tx_locktime: LockTime,
@@ -4212,7 +4343,7 @@ pub(super) struct DualFundingChannelContext {
4212
4343
/// minus any fees paid for our contributed weight. This means that change will never be generated
4213
4344
/// and the maximum value possible will go towards funding the channel.
4214
4345
#[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)> >,
4216
4347
}
4217
4348
4218
4349
// 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 {
8885
9016
unfunded_context,
8886
9017
dual_funding_context: DualFundingChannelContext {
8887
9018
our_funding_satoshis: funding_satoshis,
9019
+ their_funding_satoshis: None,
8888
9020
funding_tx_locktime,
8889
9021
funding_feerate_sat_per_1000_weight,
8890
- our_funding_inputs: funding_inputs,
9022
+ our_funding_inputs: Some( funding_inputs) ,
8891
9023
},
8892
9024
interactive_tx_constructor: None,
8893
9025
};
@@ -9053,9 +9185,10 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
9053
9185
9054
9186
let dual_funding_context = DualFundingChannelContext {
9055
9187
our_funding_satoshis: funding_satoshis,
9188
+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
9056
9189
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
9057
9190
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() ),
9059
9192
};
9060
9193
9061
9194
let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
0 commit comments