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, calculate_change_output_value, 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};
@@ -1681,6 +1681,91 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for Channel<SP> where SP::Ta
1681
1681
}
1682
1682
1683
1683
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
+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
1688
+ where ES::Target: EntropySource
1689
+ {
1690
+ let mut funding_inputs = Vec::new();
1691
+ mem::swap(&mut self.dual_funding_context.our_funding_inputs, &mut funding_inputs);
1692
+
1693
+ let funding_inputs_prev_outputs = DualFundingChannelContext::txouts_from_input_prev_txs(&funding_inputs)
1694
+ .map_err(|err| APIError::APIMisuseError { err: err.to_string() })?;
1695
+
1696
+ let total_input_satoshis: u64 = funding_inputs_prev_outputs.iter().map(|txout| txout.value.to_sat()).sum();
1697
+ if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
1698
+ return Err(APIError::APIMisuseError {
1699
+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
1700
+ total_input_satoshis) });
1701
+ }
1702
+
1703
+ // Add output for funding tx
1704
+ let mut funding_outputs = Vec::new();
1705
+ let funding_output_value_satoshis = self.context.get_value_satoshis();
1706
+ let funding_output_script_pubkey = self.context.get_funding_redeemscript().to_p2wsh();
1707
+ let expected_remote_shared_funding_output = if self.context.is_outbound() {
1708
+ let tx_out = TxOut {
1709
+ value: Amount::from_sat(funding_output_value_satoshis),
1710
+ script_pubkey: funding_output_script_pubkey,
1711
+ };
1712
+ funding_outputs.push(
1713
+ if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
1714
+ OutputOwned::SharedControlFullyOwned(tx_out)
1715
+ } else {
1716
+ OutputOwned::Shared(SharedOwnedOutput::new(
1717
+ tx_out, self.dual_funding_context.our_funding_satoshis
1718
+ ))
1719
+ }
1720
+ );
1721
+ None
1722
+ } else {
1723
+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
1724
+ };
1725
+
1726
+ // Optionally add change output
1727
+ if let Some(change_value) = calculate_change_output_value(
1728
+ self.context.is_outbound(), self.dual_funding_context.our_funding_satoshis,
1729
+ &funding_inputs_prev_outputs, &funding_outputs,
1730
+ self.dual_funding_context.funding_feerate_sat_per_1000_weight,
1731
+ self.context.holder_dust_limit_satoshis,
1732
+ ) {
1733
+ let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
1734
+ |err| APIError::APIMisuseError {
1735
+ err: format!("Failed to get change script as new destination script, {:?}", err),
1736
+ })?;
1737
+ let mut change_output = TxOut {
1738
+ value: Amount::from_sat(change_value),
1739
+ script_pubkey: change_script,
1740
+ };
1741
+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
1742
+ let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
1743
+ change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
1744
+ // Note: dust check not done here, should be handled before
1745
+ funding_outputs.push(OutputOwned::Single(change_output));
1746
+ }
1747
+
1748
+ let constructor_args = InteractiveTxConstructorArgs {
1749
+ entropy_source,
1750
+ holder_node_id,
1751
+ counterparty_node_id: self.context.counterparty_node_id,
1752
+ channel_id: self.context.channel_id(),
1753
+ feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
1754
+ is_initiator: self.context.is_outbound(),
1755
+ funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
1756
+ inputs_to_contribute: funding_inputs,
1757
+ outputs_to_contribute: funding_outputs,
1758
+ expected_remote_shared_funding_output,
1759
+ };
1760
+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
1761
+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
1762
+ let msg = tx_constructor.take_initiator_first_message();
1763
+
1764
+ self.interactive_tx_constructor = Some(tx_constructor);
1765
+
1766
+ Ok(msg)
1767
+ }
1768
+
1684
1769
pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
1685
1770
InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
1686
1771
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4103,7 +4188,6 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
4103
4188
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
4104
4189
}
4105
4190
4106
- #[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
4107
4191
pub(super) fn calculate_our_funding_satoshis(
4108
4192
is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
4109
4193
total_witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32,
@@ -4149,6 +4233,9 @@ pub(super) fn calculate_our_funding_satoshis(
4149
4233
pub(super) struct DualFundingChannelContext {
4150
4234
/// The amount in satoshis we will be contributing to the channel.
4151
4235
pub our_funding_satoshis: u64,
4236
+ /// The amount in satoshis our counterparty will be contributing to the channel.
4237
+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4238
+ pub their_funding_satoshis: Option<u64>,
4152
4239
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
4153
4240
/// to the current block height to align incentives against fee-sniping.
4154
4241
pub funding_tx_locktime: LockTime,
@@ -4160,10 +4247,39 @@ pub(super) struct DualFundingChannelContext {
4160
4247
/// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
4161
4248
/// minus any fees paid for our contributed weight. This means that change will never be generated
4162
4249
/// and the maximum value possible will go towards funding the channel.
4250
+ ///
4251
+ /// Note that this field may be emptied once the interactive negotiation has been started.
4163
4252
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4164
4253
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4165
4254
}
4166
4255
4256
+ impl DualFundingChannelContext {
4257
+ /// Obtain prev outputs for each supplied input and matching transaction.
4258
+ /// Can error when there a prev tx does not have an output for the specified vout number.
4259
+ /// Also checks for matching of transaction IDs.
4260
+ fn txouts_from_input_prev_txs(inputs: &Vec<(TxIn, TransactionU16LenLimited)>) -> Result<Vec<&TxOut>, ChannelError> {
4261
+ let mut prev_outputs: Vec<&TxOut> = Vec::with_capacity(inputs.len());
4262
+ // Check that vouts exist for each TxIn in provided transactions.
4263
+ for (idx, (txin, tx)) in inputs.iter().enumerate() {
4264
+ let txid = tx.as_transaction().compute_txid();
4265
+ if txin.previous_output.txid != txid {
4266
+ return Err(ChannelError::Warn(
4267
+ format!("Transaction input txid mismatch, {} vs. {}, at index {}", txin.previous_output.txid, txid, idx)
4268
+ ));
4269
+ }
4270
+ if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
4271
+ prev_outputs.push(output);
4272
+ } else {
4273
+ return Err(ChannelError::Warn(
4274
+ format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn, at index {}",
4275
+ txid, txin.previous_output.vout, idx)
4276
+ ));
4277
+ }
4278
+ }
4279
+ Ok(prev_outputs)
4280
+ }
4281
+ }
4282
+
4167
4283
// Holder designates channel data owned for the benefit of the user client.
4168
4284
// Counterparty designates channel data owned by the another channel participant entity.
4169
4285
pub(super) struct Channel<SP: Deref> where SP::Target: SignerProvider {
@@ -8829,15 +8945,17 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
8829
8945
unfunded_channel_age_ticks: 0,
8830
8946
holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
8831
8947
};
8948
+ let dual_funding_context = DualFundingChannelContext {
8949
+ our_funding_satoshis: funding_satoshis,
8950
+ their_funding_satoshis: None,
8951
+ funding_tx_locktime,
8952
+ funding_feerate_sat_per_1000_weight,
8953
+ our_funding_inputs: funding_inputs,
8954
+ };
8832
8955
let chan = Self {
8833
8956
context,
8834
8957
unfunded_context,
8835
- dual_funding_context: DualFundingChannelContext {
8836
- our_funding_satoshis: funding_satoshis,
8837
- funding_tx_locktime,
8838
- funding_feerate_sat_per_1000_weight,
8839
- our_funding_inputs: funding_inputs,
8840
- },
8958
+ dual_funding_context,
8841
8959
interactive_tx_constructor: None,
8842
8960
};
8843
8961
Ok(chan)
@@ -8982,6 +9100,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
8982
9100
8983
9101
let dual_funding_context = DualFundingChannelContext {
8984
9102
our_funding_satoshis: funding_satoshis,
9103
+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
8985
9104
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
8986
9105
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
8987
9106
our_funding_inputs: funding_inputs.clone(),
0 commit comments