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};
@@ -1161,6 +1161,7 @@ impl<'a, SP: Deref> ChannelPhase<SP> where
1161
1161
}
1162
1162
1163
1163
/// Contains all state common to unfunded inbound/outbound channels.
1164
+ #[derive(Default)]
1164
1165
pub(super) struct UnfundedChannelContext {
1165
1166
/// A counter tracking how many ticks have elapsed since this unfunded channel was
1166
1167
/// 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
1684
1685
1685
1686
fn dual_funding_context(&self) -> &DualFundingChannelContext;
1686
1687
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
+
1687
1785
fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
1688
1786
InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
1689
1787
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
1846
1944
fn dual_funding_context(&self) -> &DualFundingChannelContext {
1847
1945
&self.dual_funding_context
1848
1946
}
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
+ }
1849
1951
fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
1850
1952
&mut self.interactive_tx_constructor
1851
1953
}
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
+ }
1852
1958
}
1853
1959
1854
1960
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
1861
1967
fn dual_funding_context(&self) -> &DualFundingChannelContext {
1862
1968
&self.dual_funding_context
1863
1969
}
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
+ }
1864
1974
fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
1865
1975
&mut self.interactive_tx_constructor
1866
1976
}
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
+ }
1867
1981
}
1868
1982
1869
1983
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
4150
4264
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
4151
4265
}
4152
4266
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
+
4153
4283
pub(super) fn calculate_our_funding_satoshis(
4154
4284
is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
4155
4285
total_witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32,
@@ -4195,6 +4325,9 @@ pub(super) fn calculate_our_funding_satoshis(
4195
4325
pub(super) struct DualFundingChannelContext {
4196
4326
/// The amount in satoshis we will be contributing to the channel.
4197
4327
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>,
4198
4331
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
4199
4332
/// to the current block height to align incentives against fee-sniping.
4200
4333
pub funding_tx_locktime: LockTime,
@@ -4206,7 +4339,7 @@ pub(super) struct DualFundingChannelContext {
4206
4339
/// minus any fees paid for our contributed weight. This means that change will never be generated
4207
4340
/// and the maximum value possible will go towards funding the channel.
4208
4341
#[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)> >,
4210
4343
}
4211
4344
4212
4345
// 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 {
8295
8428
pubkeys,
8296
8429
logger,
8297
8430
)?,
8298
- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 }
8431
+ unfunded_context: UnfundedChannelContext::default(),
8299
8432
};
8300
8433
Ok(chan)
8301
8434
}
@@ -8599,7 +8732,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
8599
8732
msg.push_msat,
8600
8733
msg.common_fields.clone(),
8601
8734
)?,
8602
- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 } ,
8735
+ unfunded_context: UnfundedChannelContext::default() ,
8603
8736
};
8604
8737
Ok(chan)
8605
8738
}
@@ -8782,12 +8915,13 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
8782
8915
pubkeys,
8783
8916
logger,
8784
8917
)?,
8785
- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 } ,
8918
+ unfunded_context: UnfundedChannelContext::default() ,
8786
8919
dual_funding_context: DualFundingChannelContext {
8787
8920
our_funding_satoshis: funding_satoshis,
8921
+ their_funding_satoshis: None,
8788
8922
funding_tx_locktime,
8789
8923
funding_feerate_sat_per_1000_weight,
8790
- our_funding_inputs: funding_inputs,
8924
+ our_funding_inputs: Some( funding_inputs) ,
8791
8925
},
8792
8926
interactive_tx_constructor: None,
8793
8927
};
@@ -8948,9 +9082,10 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
8948
9082
8949
9083
let dual_funding_context = DualFundingChannelContext {
8950
9084
our_funding_satoshis: funding_satoshis,
9085
+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
8951
9086
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
8952
9087
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() ),
8954
9089
};
8955
9090
8956
9091
let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
@@ -8975,7 +9110,7 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
8975
9110
context,
8976
9111
dual_funding_context,
8977
9112
interactive_tx_constructor,
8978
- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 } ,
9113
+ unfunded_context: UnfundedChannelContext::default() ,
8979
9114
})
8980
9115
}
8981
9116
0 commit comments