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};
@@ -1681,6 +1681,99 @@ 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
+ extra_input: Option<(TxIn, TransactionU16LenLimited)>,
1688
+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
1689
+ where ES::Target: EntropySource
1690
+ {
1691
+ let mut funding_inputs_with_extra = self.dual_funding_context.our_funding_inputs.take().unwrap_or_else(|| vec![]);
1692
+
1693
+ if let Some(extra_input) = extra_input {
1694
+ funding_inputs_with_extra.push(extra_input);
1695
+ }
1696
+
1697
+ let mut funding_inputs_prev_outputs: Vec<TxOut> = Vec::with_capacity(funding_inputs_with_extra.len());
1698
+ // Check that vouts exist for each TxIn in provided transactions.
1699
+ for (idx, input) in funding_inputs_with_extra.iter().enumerate() {
1700
+ if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
1701
+ funding_inputs_prev_outputs.push(output.clone());
1702
+ } else {
1703
+ return Err(APIError::APIMisuseError {
1704
+ err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs_with_extra[{}]",
1705
+ input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
1706
+ }
1707
+ }
1708
+
1709
+ let total_input_satoshis: u64 = funding_inputs_with_extra.iter().map(
1710
+ |input| input.1.as_transaction().output.get(input.0.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
1711
+ ).sum();
1712
+ if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
1713
+ return Err(APIError::APIMisuseError {
1714
+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
1715
+ total_input_satoshis) });
1716
+ }
1717
+
1718
+ // Add output for funding tx
1719
+ let mut funding_outputs = Vec::new();
1720
+ let funding_output_value_satoshis = self.context.get_value_satoshis();
1721
+ let funding_output_script_pubkey = self.context.get_funding_redeemscript().to_p2wsh();
1722
+ let expected_remote_shared_funding_output = if self.context.is_outbound() {
1723
+ let tx_out = TxOut {
1724
+ value: Amount::from_sat(funding_output_value_satoshis),
1725
+ script_pubkey: funding_output_script_pubkey,
1726
+ };
1727
+ funding_outputs.push(
1728
+ if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
1729
+ OutputOwned::SharedControlFullyOwned(tx_out)
1730
+ } else {
1731
+ OutputOwned::Shared(SharedOwnedOutput::new(
1732
+ tx_out, self.dual_funding_context.our_funding_satoshis
1733
+ ))
1734
+ }
1735
+ );
1736
+ None
1737
+ } else {
1738
+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
1739
+ };
1740
+
1741
+ // Optionally add change output
1742
+ if let Some(change_value) = need_to_add_funding_change_output(
1743
+ self.context.is_outbound(), self.dual_funding_context.our_funding_satoshis,
1744
+ &funding_inputs_prev_outputs, &funding_outputs,
1745
+ self.dual_funding_context.funding_feerate_sat_per_1000_weight,
1746
+ self.context.holder_dust_limit_satoshis,
1747
+ ) {
1748
+ let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
1749
+ |err| APIError::APIMisuseError {
1750
+ err: format!("Failed to get change script as new destination script, {:?}", err),
1751
+ })?;
1752
+ let _res = add_funding_change_output(
1753
+ change_value, change_script, &mut funding_outputs, self.dual_funding_context.funding_feerate_sat_per_1000_weight);
1754
+ }
1755
+
1756
+ let constructor_args = InteractiveTxConstructorArgs {
1757
+ entropy_source,
1758
+ holder_node_id,
1759
+ counterparty_node_id: self.context.counterparty_node_id,
1760
+ channel_id: self.context.channel_id(),
1761
+ feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
1762
+ is_initiator: self.context.is_outbound(),
1763
+ funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
1764
+ inputs_to_contribute: funding_inputs_with_extra,
1765
+ outputs_to_contribute: funding_outputs,
1766
+ expected_remote_shared_funding_output,
1767
+ };
1768
+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
1769
+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
1770
+ let msg = tx_constructor.take_initiator_first_message();
1771
+
1772
+ self.interactive_tx_constructor.replace(tx_constructor);
1773
+
1774
+ Ok(msg)
1775
+ }
1776
+
1684
1777
pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
1685
1778
InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
1686
1779
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4103,7 +4196,22 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
4103
4196
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
4104
4197
}
4105
4198
4106
- #[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
4199
+ #[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
4200
+ fn add_funding_change_output(
4201
+ change_value: u64, change_script: ScriptBuf,
4202
+ funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4203
+ ) -> TxOut {
4204
+ let mut change_output = TxOut {
4205
+ value: Amount::from_sat(change_value),
4206
+ script_pubkey: change_script,
4207
+ };
4208
+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4209
+ let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4210
+ change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
4211
+ funding_outputs.push(OutputOwned::Single(change_output.clone()));
4212
+ change_output
4213
+ }
4214
+
4107
4215
pub(super) fn calculate_our_funding_satoshis(
4108
4216
is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
4109
4217
total_witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32,
@@ -4149,6 +4257,9 @@ pub(super) fn calculate_our_funding_satoshis(
4149
4257
pub(super) struct DualFundingChannelContext {
4150
4258
/// The amount in satoshis we will be contributing to the channel.
4151
4259
pub our_funding_satoshis: u64,
4260
+ /// The amount in satoshis our counterparty will be contributing to the channel.
4261
+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4262
+ pub their_funding_satoshis: Option<u64>,
4152
4263
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
4153
4264
/// to the current block height to align incentives against fee-sniping.
4154
4265
pub funding_tx_locktime: LockTime,
@@ -4161,7 +4272,7 @@ pub(super) struct DualFundingChannelContext {
4161
4272
/// minus any fees paid for our contributed weight. This means that change will never be generated
4162
4273
/// and the maximum value possible will go towards funding the channel.
4163
4274
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4164
- pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4275
+ pub our_funding_inputs: Option< Vec<(TxIn, TransactionU16LenLimited)> >,
4165
4276
}
4166
4277
4167
4278
// Holder designates channel data owned for the benefit of the user client.
@@ -8834,9 +8945,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
8834
8945
unfunded_context,
8835
8946
dual_funding_context: DualFundingChannelContext {
8836
8947
our_funding_satoshis: funding_satoshis,
8948
+ their_funding_satoshis: None,
8837
8949
funding_tx_locktime,
8838
8950
funding_feerate_sat_per_1000_weight,
8839
- our_funding_inputs: funding_inputs,
8951
+ our_funding_inputs: Some( funding_inputs) ,
8840
8952
},
8841
8953
interactive_tx_constructor: None,
8842
8954
};
@@ -8982,9 +9094,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
8982
9094
8983
9095
let dual_funding_context = DualFundingChannelContext {
8984
9096
our_funding_satoshis: funding_satoshis,
9097
+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
8985
9098
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
8986
9099
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
8987
- our_funding_inputs: funding_inputs.clone(),
9100
+ our_funding_inputs: Some( funding_inputs.clone() ),
8988
9101
};
8989
9102
8990
9103
let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
0 commit comments