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::EcdsaSighashType;
15
15
use bitcoin::consensus::encode;
16
16
use bitcoin::absolute::LockTime;
@@ -30,9 +30,9 @@ use crate::ln::types::ChannelId;
30
30
use crate::types::payment::{PaymentPreimage, PaymentHash};
31
31
use crate::types::features::{ChannelTypeFeatures, InitFeatures};
32
32
use crate::ln::interactivetxs::{
33
- get_output_weight, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
34
- InteractiveTxConstructorArgs, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
35
- TX_COMMON_FIELDS_WEIGHT,
33
+ calculate_change_output_value, get_output_weight, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
34
+ InteractiveTxConstructorArgs, InteractiveTxMessageSend, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
35
+ OutputOwned, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
36
36
};
37
37
use crate::ln::msgs;
38
38
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket};
@@ -2220,6 +2220,106 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
2220
2220
}
2221
2221
2222
2222
impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2223
+ /// Prepare and start interactive transaction negotiation.
2224
+ /// `change_destination_opt` - Optional destination for optional change; if None, default destination address is used.
2225
+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2226
+ fn begin_interactive_funding_tx_construction<ES: Deref>(
2227
+ &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2228
+ change_destination_opt: Option<ScriptBuf>,
2229
+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
2230
+ where ES::Target: EntropySource
2231
+ {
2232
+ let mut funding_inputs = Vec::new();
2233
+ mem::swap(&mut self.dual_funding_context.our_funding_inputs, &mut funding_inputs);
2234
+
2235
+ let funding_inputs_prev_outputs = DualFundingChannelContext::txouts_from_input_prev_txs(&funding_inputs)
2236
+ .map_err(|err| APIError::APIMisuseError { err: err.to_string() })?;
2237
+
2238
+ let total_input_satoshis: u64 = funding_inputs_prev_outputs.iter().map(|txout| txout.value.to_sat()).sum();
2239
+ if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2240
+ return Err(APIError::APIMisuseError {
2241
+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2242
+ total_input_satoshis) });
2243
+ }
2244
+
2245
+ // Add output for funding tx
2246
+ let mut funding_outputs = Vec::new();
2247
+ let funding_output_value_satoshis = self.funding.get_value_satoshis();
2248
+ let funding_output_script_pubkey = self.funding.get_funding_redeemscript().to_p2wsh();
2249
+ let expected_remote_shared_funding_output = if self.funding.is_outbound() {
2250
+ let tx_out = TxOut {
2251
+ value: Amount::from_sat(funding_output_value_satoshis),
2252
+ script_pubkey: funding_output_script_pubkey,
2253
+ };
2254
+ funding_outputs.push(
2255
+ if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2256
+ OutputOwned::SharedControlFullyOwned(tx_out)
2257
+ } else {
2258
+ OutputOwned::Shared(SharedOwnedOutput::new(
2259
+ tx_out, self.dual_funding_context.our_funding_satoshis
2260
+ ))
2261
+ }
2262
+ );
2263
+ None
2264
+ } else {
2265
+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
2266
+ };
2267
+
2268
+ // Optionally add change output
2269
+ let change_value_opt = calculate_change_output_value(
2270
+ self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2271
+ &funding_inputs_prev_outputs, &funding_outputs,
2272
+ self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2273
+ self.context.holder_dust_limit_satoshis,
2274
+ ).map_err(|err| APIError::APIMisuseError {
2275
+ err: format!("Insufficient inputs, cannot cover intended contribution of {} and fees; {}",
2276
+ self.dual_funding_context.our_funding_satoshis, err
2277
+ ),
2278
+ })?;
2279
+ if let Some(change_value) = change_value_opt {
2280
+ let change_script = if let Some(script) = change_destination_opt {
2281
+ script
2282
+ } else {
2283
+ signer_provider.get_destination_script(self.context.channel_keys_id)
2284
+ .map_err(|err| APIError::APIMisuseError {
2285
+ err: format!("Failed to get change script as new destination script, {:?}", err),
2286
+ })?
2287
+ };
2288
+ let mut change_output = TxOut {
2289
+ value: Amount::from_sat(change_value),
2290
+ script_pubkey: change_script,
2291
+ };
2292
+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2293
+ let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2294
+ let change_value_decreased_with_fee = change_value.saturating_sub(change_output_fee);
2295
+ // Check dust limit again
2296
+ if change_value_decreased_with_fee > self.context.holder_dust_limit_satoshis {
2297
+ change_output.value = Amount::from_sat(change_value_decreased_with_fee);
2298
+ funding_outputs.push(OutputOwned::Single(change_output));
2299
+ }
2300
+ }
2301
+
2302
+ let constructor_args = InteractiveTxConstructorArgs {
2303
+ entropy_source,
2304
+ holder_node_id,
2305
+ counterparty_node_id: self.context.counterparty_node_id,
2306
+ channel_id: self.context.channel_id(),
2307
+ feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2308
+ is_initiator: self.funding.is_outbound(),
2309
+ funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2310
+ inputs_to_contribute: funding_inputs,
2311
+ outputs_to_contribute: funding_outputs,
2312
+ expected_remote_shared_funding_output,
2313
+ };
2314
+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2315
+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2316
+ let msg = tx_constructor.take_initiator_first_message();
2317
+
2318
+ self.interactive_tx_constructor = Some(tx_constructor);
2319
+
2320
+ Ok(msg)
2321
+ }
2322
+
2223
2323
pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
2224
2324
InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
2225
2325
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4849,6 +4949,9 @@ fn check_v2_funding_inputs_sufficient(
4849
4949
pub(super) struct DualFundingChannelContext {
4850
4950
/// The amount in satoshis we will be contributing to the channel.
4851
4951
pub our_funding_satoshis: u64,
4952
+ /// The amount in satoshis our counterparty will be contributing to the channel.
4953
+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4954
+ pub their_funding_satoshis: Option<u64>,
4852
4955
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
4853
4956
/// to the current block height to align incentives against fee-sniping.
4854
4957
pub funding_tx_locktime: LockTime,
@@ -4860,10 +4963,39 @@ pub(super) struct DualFundingChannelContext {
4860
4963
/// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
4861
4964
/// minus any fees paid for our contributed weight. This means that change will never be generated
4862
4965
/// and the maximum value possible will go towards funding the channel.
4966
+ ///
4967
+ /// Note that this field may be emptied once the interactive negotiation has been started.
4863
4968
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4864
4969
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4865
4970
}
4866
4971
4972
+ impl DualFundingChannelContext {
4973
+ /// Obtain prev outputs for each supplied input and matching transaction.
4974
+ /// Will error when a prev tx does not have an output for the specified vout.
4975
+ /// Also checks for matching of transaction IDs.
4976
+ fn txouts_from_input_prev_txs(inputs: &Vec<(TxIn, TransactionU16LenLimited)>) -> Result<Vec<&TxOut>, ChannelError> {
4977
+ let mut prev_outputs: Vec<&TxOut> = Vec::with_capacity(inputs.len());
4978
+ // Check that vouts exist for each TxIn in provided transactions.
4979
+ for (idx, (txin, tx)) in inputs.iter().enumerate() {
4980
+ let txid = tx.as_transaction().compute_txid();
4981
+ if txin.previous_output.txid != txid {
4982
+ return Err(ChannelError::Warn(
4983
+ format!("Transaction input txid mismatch, {} vs. {}, at index {}", txin.previous_output.txid, txid, idx)
4984
+ ));
4985
+ }
4986
+ if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
4987
+ prev_outputs.push(output);
4988
+ } else {
4989
+ return Err(ChannelError::Warn(
4990
+ format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn, at index {}",
4991
+ txid, txin.previous_output.vout, idx)
4992
+ ));
4993
+ }
4994
+ }
4995
+ Ok(prev_outputs)
4996
+ }
4997
+ }
4998
+
4867
4999
// Holder designates channel data owned for the benefit of the user client.
4868
5000
// Counterparty designates channel data owned by the another channel participant entity.
4869
5001
pub(super) struct FundedChannel<SP: Deref> where SP::Target: SignerProvider {
@@ -9829,16 +9961,18 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
9829
9961
unfunded_channel_age_ticks: 0,
9830
9962
holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
9831
9963
};
9964
+ let dual_funding_context = DualFundingChannelContext {
9965
+ our_funding_satoshis: funding_satoshis,
9966
+ their_funding_satoshis: None,
9967
+ funding_tx_locktime,
9968
+ funding_feerate_sat_per_1000_weight,
9969
+ our_funding_inputs: funding_inputs,
9970
+ };
9832
9971
let chan = Self {
9833
9972
funding,
9834
9973
context,
9835
9974
unfunded_context,
9836
- dual_funding_context: DualFundingChannelContext {
9837
- our_funding_satoshis: funding_satoshis,
9838
- funding_tx_locktime,
9839
- funding_feerate_sat_per_1000_weight,
9840
- our_funding_inputs: funding_inputs,
9841
- },
9975
+ dual_funding_context,
9842
9976
interactive_tx_constructor: None,
9843
9977
interactive_tx_signing_session: None,
9844
9978
};
@@ -9980,6 +10114,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
9980
10114
9981
10115
let dual_funding_context = DualFundingChannelContext {
9982
10116
our_funding_satoshis: our_funding_satoshis,
10117
+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
9983
10118
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
9984
10119
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
9985
10120
our_funding_inputs: our_funding_inputs.clone(),
0 commit comments