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,93 @@ 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
+ maybe_add_funding_change_output(signer_provider, self.is_initiator(), self.dual_funding_context().our_funding_satoshis,
1750
+ &funding_inputs_prev_outputs, &mut funding_outputs, self.dual_funding_context().funding_feerate_sat_per_1000_weight,
1751
+ self.context().holder_dust_limit_satoshis, self.context().channel_keys_id).map_err(
1752
+ |err| APIError::APIMisuseError { err: format!("Could not create change output, {:?}", err)})?;
1753
+
1754
+ let constructor_args = InteractiveTxConstructorArgs {
1755
+ entropy_source,
1756
+ holder_node_id,
1757
+ counterparty_node_id: self.context().counterparty_node_id,
1758
+ channel_id: self.context().channel_id(),
1759
+ feerate_sat_per_kw: self.dual_funding_context_mut().funding_feerate_sat_per_1000_weight,
1760
+ is_initiator: self.is_initiator(),
1761
+ funding_tx_locktime: self.dual_funding_context_mut().funding_tx_locktime,
1762
+ inputs_to_contribute: funding_inputs_with_extra,
1763
+ outputs_to_contribute: funding_outputs,
1764
+ expected_remote_shared_funding_output,
1765
+ };
1766
+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
1767
+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
1768
+ let msg = tx_constructor.take_initiator_first_message();
1769
+
1770
+ self.interactive_tx_constructor_mut().replace(tx_constructor);
1771
+
1772
+ Ok(msg)
1773
+ }
1774
+
1687
1775
fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
1688
1776
InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
1689
1777
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -1846,9 +1934,17 @@ impl<SP: Deref> InteractivelyFunded<SP> for OutboundV2Channel<SP> where SP::Targ
1846
1934
fn dual_funding_context(&self) -> &DualFundingChannelContext {
1847
1935
&self.dual_funding_context
1848
1936
}
1937
+ #[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
1938
+ fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext {
1939
+ &mut self.dual_funding_context
1940
+ }
1849
1941
fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
1850
1942
&mut self.interactive_tx_constructor
1851
1943
}
1944
+ #[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
1945
+ fn is_initiator(&self) -> bool {
1946
+ true
1947
+ }
1852
1948
}
1853
1949
1854
1950
impl<SP: Deref> InteractivelyFunded<SP> for InboundV2Channel<SP> where SP::Target: SignerProvider {
@@ -1861,9 +1957,17 @@ impl<SP: Deref> InteractivelyFunded<SP> for InboundV2Channel<SP> where SP::Targe
1861
1957
fn dual_funding_context(&self) -> &DualFundingChannelContext {
1862
1958
&self.dual_funding_context
1863
1959
}
1960
+ #[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
1961
+ fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext {
1962
+ &mut self.dual_funding_context
1963
+ }
1864
1964
fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
1865
1965
&mut self.interactive_tx_constructor
1866
1966
}
1967
+ #[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
1968
+ fn is_initiator(&self) -> bool {
1969
+ false
1970
+ }
1867
1971
}
1868
1972
1869
1973
impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
@@ -4150,6 +4254,41 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
4150
4254
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
4151
4255
}
4152
4256
4257
+ #[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
4258
+ fn maybe_add_funding_change_output<SP: Deref>(signer_provider: &SP, is_initiator: bool,
4259
+ our_funding_satoshis: u64, funding_inputs_prev_outputs: &Vec<TxOut>,
4260
+ funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4261
+ holder_dust_limit_satoshis: u64, channel_keys_id: [u8; 32],
4262
+ ) -> Result<Option<TxOut>, ChannelError> where SP::Target: SignerProvider {
4263
+ let remaining_value = match need_to_add_funding_change_output(
4264
+ is_initiator, our_funding_satoshis, funding_inputs_prev_outputs,
4265
+ funding_outputs, funding_feerate_sat_per_1000_weight, holder_dust_limit_satoshis
4266
+ ) {
4267
+ None => {
4268
+ // No need to add
4269
+ return Ok(None);
4270
+ }
4271
+ Some(remaining_value) => remaining_value,
4272
+ };
4273
+
4274
+ let change_script = signer_provider.get_destination_script(channel_keys_id).map_err(
4275
+ |_| ChannelError::Close((
4276
+ "Failed to get change script as new destination script".to_owned(),
4277
+ ClosureReason::ProcessingError { err: "Failed to get change script as new destination script".to_owned() }
4278
+ ))
4279
+ )?;
4280
+ let mut change_output = TxOut {
4281
+ value: Amount::from_sat(remaining_value),
4282
+ script_pubkey: change_script,
4283
+ };
4284
+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4285
+
4286
+ let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4287
+ change_output.value = Amount::from_sat(remaining_value.saturating_sub(change_output_fee));
4288
+ funding_outputs.push(OutputOwned::Single(change_output.clone()));
4289
+ Ok(Some(change_output))
4290
+ }
4291
+
4153
4292
pub(super) fn calculate_our_funding_satoshis(
4154
4293
is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
4155
4294
total_witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32,
@@ -4195,6 +4334,9 @@ pub(super) fn calculate_our_funding_satoshis(
4195
4334
pub(super) struct DualFundingChannelContext {
4196
4335
/// The amount in satoshis we will be contributing to the channel.
4197
4336
pub our_funding_satoshis: u64,
4337
+ /// The amount in satoshis our counterparty will be contributing to the channel.
4338
+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4339
+ pub their_funding_satoshis: Option<u64>,
4198
4340
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
4199
4341
/// to the current block height to align incentives against fee-sniping.
4200
4342
pub funding_tx_locktime: LockTime,
@@ -4206,7 +4348,7 @@ pub(super) struct DualFundingChannelContext {
4206
4348
/// minus any fees paid for our contributed weight. This means that change will never be generated
4207
4349
/// and the maximum value possible will go towards funding the channel.
4208
4350
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4209
- pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4351
+ pub our_funding_inputs: Option< Vec<(TxIn, TransactionU16LenLimited)> >,
4210
4352
}
4211
4353
4212
4354
// Holder designates channel data owned for the benefit of the user client.
@@ -8295,7 +8437,7 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
8295
8437
pubkeys,
8296
8438
logger,
8297
8439
)?,
8298
- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 }
8440
+ unfunded_context: UnfundedChannelContext::default(),
8299
8441
};
8300
8442
Ok(chan)
8301
8443
}
@@ -8599,7 +8741,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
8599
8741
msg.push_msat,
8600
8742
msg.common_fields.clone(),
8601
8743
)?,
8602
- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 } ,
8744
+ unfunded_context: UnfundedChannelContext::default() ,
8603
8745
};
8604
8746
Ok(chan)
8605
8747
}
@@ -8782,12 +8924,13 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
8782
8924
pubkeys,
8783
8925
logger,
8784
8926
)?,
8785
- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 } ,
8927
+ unfunded_context: UnfundedChannelContext::default() ,
8786
8928
dual_funding_context: DualFundingChannelContext {
8787
8929
our_funding_satoshis: funding_satoshis,
8930
+ their_funding_satoshis: None,
8788
8931
funding_tx_locktime,
8789
8932
funding_feerate_sat_per_1000_weight,
8790
- our_funding_inputs: funding_inputs,
8933
+ our_funding_inputs: Some( funding_inputs) ,
8791
8934
},
8792
8935
interactive_tx_constructor: None,
8793
8936
};
@@ -8948,9 +9091,10 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
8948
9091
8949
9092
let dual_funding_context = DualFundingChannelContext {
8950
9093
our_funding_satoshis: funding_satoshis,
9094
+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
8951
9095
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
8952
9096
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
8953
- our_funding_inputs: funding_inputs.clone(),
9097
+ our_funding_inputs: Some( funding_inputs.clone() ),
8954
9098
};
8955
9099
8956
9100
let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
@@ -8975,7 +9119,7 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
8975
9119
context,
8976
9120
dual_funding_context,
8977
9121
interactive_tx_constructor,
8978
- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 } ,
9122
+ unfunded_context: UnfundedChannelContext::default() ,
8979
9123
})
8980
9124
}
8981
9125
0 commit comments