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
+ get_output_weight, calculate_change_output_value, 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};
@@ -2237,6 +2237,107 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
2237
2237
}
2238
2238
2239
2239
impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2240
+ /// Prepare and start interactive transaction negotiation.
2241
+ /// `change_destination_opt` - Optional destination for optional change; if None, default destination address is used.
2242
+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2243
+ fn begin_interactive_funding_tx_construction<ES: Deref>(
2244
+ &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2245
+ change_destination_opt: Option<ScriptBuf>,
2246
+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
2247
+ where ES::Target: EntropySource
2248
+ {
2249
+ let mut funding_inputs = Vec::new();
2250
+ mem::swap(&mut self.dual_funding_context.our_funding_inputs, &mut funding_inputs);
2251
+
2252
+ let funding_inputs_prev_outputs = DualFundingChannelContext::txouts_from_input_prev_txs(&funding_inputs)
2253
+ .map_err(|err| APIError::APIMisuseError { err: err.to_string() })?;
2254
+
2255
+ let total_input_satoshis: u64 = funding_inputs_prev_outputs.iter().map(|txout| txout.value.to_sat()).sum();
2256
+ if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2257
+ return Err(APIError::APIMisuseError {
2258
+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2259
+ total_input_satoshis) });
2260
+ }
2261
+
2262
+ // Add output for funding tx
2263
+ let mut funding_outputs = Vec::new();
2264
+ let funding_output_value_satoshis = self.funding.get_value_satoshis();
2265
+ let funding_output_script_pubkey = self.funding.get_funding_redeemscript().to_p2wsh();
2266
+ let expected_remote_shared_funding_output = if self.funding.is_outbound() {
2267
+ let tx_out = TxOut {
2268
+ value: Amount::from_sat(funding_output_value_satoshis),
2269
+ script_pubkey: funding_output_script_pubkey,
2270
+ };
2271
+ funding_outputs.push(
2272
+ if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2273
+ OutputOwned::SharedControlFullyOwned(tx_out)
2274
+ } else {
2275
+ OutputOwned::Shared(SharedOwnedOutput::new(
2276
+ tx_out, self.dual_funding_context.our_funding_satoshis
2277
+ ))
2278
+ }
2279
+ );
2280
+ None
2281
+ } else {
2282
+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
2283
+ };
2284
+
2285
+ // Optionally add change output
2286
+ let change_value_opt = calculate_change_output_value(
2287
+ self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2288
+ &funding_inputs_prev_outputs, &funding_outputs,
2289
+ self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2290
+ self.context.holder_dust_limit_satoshis,
2291
+ ).map_err(|err| APIError::APIMisuseError {
2292
+ err: format!("Insufficient inputs, cannot cover intended contribution of {} and fees; {}",
2293
+ self.dual_funding_context.our_funding_satoshis, err
2294
+ ),
2295
+ })?;
2296
+ if let Some(change_value) = change_value_opt {
2297
+ let change_script = match change_destination_opt {
2298
+ Some(script) => script,
2299
+ None => {
2300
+ signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2301
+ |err| APIError::APIMisuseError {
2302
+ err: format!("Failed to get change script as new destination script, {:?}", err),
2303
+ })?
2304
+ }
2305
+ };
2306
+ let mut change_output = TxOut {
2307
+ value: Amount::from_sat(change_value),
2308
+ script_pubkey: change_script,
2309
+ };
2310
+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2311
+ let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2312
+ let change_value_decreased_with_fee = change_value.saturating_sub(change_output_fee);
2313
+ // Check dust limit again
2314
+ if change_value_decreased_with_fee > self.context.holder_dust_limit_satoshis {
2315
+ change_output.value = Amount::from_sat(change_value_decreased_with_fee);
2316
+ funding_outputs.push(OutputOwned::Single(change_output));
2317
+ }
2318
+ }
2319
+
2320
+ let constructor_args = InteractiveTxConstructorArgs {
2321
+ entropy_source,
2322
+ holder_node_id,
2323
+ counterparty_node_id: self.context.counterparty_node_id,
2324
+ channel_id: self.context.channel_id(),
2325
+ feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2326
+ is_initiator: self.funding.is_outbound(),
2327
+ funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2328
+ inputs_to_contribute: funding_inputs,
2329
+ outputs_to_contribute: funding_outputs,
2330
+ expected_remote_shared_funding_output,
2331
+ };
2332
+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2333
+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2334
+ let msg = tx_constructor.take_initiator_first_message();
2335
+
2336
+ self.interactive_tx_constructor = Some(tx_constructor);
2337
+
2338
+ Ok(msg)
2339
+ }
2340
+
2240
2341
pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
2241
2342
InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
2242
2343
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4873,10 +4974,28 @@ fn check_v2_funding_inputs_sufficient(
4873
4974
}
4874
4975
}
4875
4976
4977
+ #[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
4978
+ fn add_funding_change_output(
4979
+ change_value: u64, change_script: ScriptBuf,
4980
+ funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4981
+ ) {
4982
+ let mut change_output = TxOut {
4983
+ value: Amount::from_sat(change_value),
4984
+ script_pubkey: change_script,
4985
+ };
4986
+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4987
+ let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4988
+ change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
4989
+ funding_outputs.push(OutputOwned::Single(change_output.clone()));
4990
+ }
4991
+
4876
4992
/// Context for dual-funded channels.
4877
4993
pub(super) struct DualFundingChannelContext {
4878
4994
/// The amount in satoshis we will be contributing to the channel.
4879
4995
pub our_funding_satoshis: u64,
4996
+ /// The amount in satoshis our counterparty will be contributing to the channel.
4997
+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4998
+ pub their_funding_satoshis: Option<u64>,
4880
4999
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
4881
5000
/// to the current block height to align incentives against fee-sniping.
4882
5001
pub funding_tx_locktime: LockTime,
@@ -4888,10 +5007,39 @@ pub(super) struct DualFundingChannelContext {
4888
5007
/// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
4889
5008
/// minus any fees paid for our contributed weight. This means that change will never be generated
4890
5009
/// and the maximum value possible will go towards funding the channel.
5010
+ ///
5011
+ /// Note that this field may be emptied once the interactive negotiation has been started.
4891
5012
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4892
5013
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4893
5014
}
4894
5015
5016
+ impl DualFundingChannelContext {
5017
+ /// Obtain prev outputs for each supplied input and matching transaction.
5018
+ /// Can error when there a prev tx does not have an output for the specified vout number.
5019
+ /// Also checks for matching of transaction IDs.
5020
+ fn txouts_from_input_prev_txs(inputs: &Vec<(TxIn, TransactionU16LenLimited)>) -> Result<Vec<&TxOut>, ChannelError> {
5021
+ let mut prev_outputs: Vec<&TxOut> = Vec::with_capacity(inputs.len());
5022
+ // Check that vouts exist for each TxIn in provided transactions.
5023
+ for (idx, (txin, tx)) in inputs.iter().enumerate() {
5024
+ let txid = tx.as_transaction().compute_txid();
5025
+ if txin.previous_output.txid != txid {
5026
+ return Err(ChannelError::Warn(
5027
+ format!("Transaction input txid mismatch, {} vs. {}, at index {}", txin.previous_output.txid, txid, idx)
5028
+ ));
5029
+ }
5030
+ if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
5031
+ prev_outputs.push(output);
5032
+ } else {
5033
+ return Err(ChannelError::Warn(
5034
+ format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn, at index {}",
5035
+ txid, txin.previous_output.vout, idx)
5036
+ ));
5037
+ }
5038
+ }
5039
+ Ok(prev_outputs)
5040
+ }
5041
+ }
5042
+
4895
5043
// Holder designates channel data owned for the benefit of the user client.
4896
5044
// Counterparty designates channel data owned by the another channel participant entity.
4897
5045
pub(super) struct FundedChannel<SP: Deref> where SP::Target: SignerProvider {
@@ -9876,16 +10024,18 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
9876
10024
unfunded_channel_age_ticks: 0,
9877
10025
holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
9878
10026
};
10027
+ let dual_funding_context = DualFundingChannelContext {
10028
+ our_funding_satoshis: funding_satoshis,
10029
+ their_funding_satoshis: None,
10030
+ funding_tx_locktime,
10031
+ funding_feerate_sat_per_1000_weight,
10032
+ our_funding_inputs: funding_inputs,
10033
+ };
9879
10034
let chan = Self {
9880
10035
funding,
9881
10036
context,
9882
10037
unfunded_context,
9883
- dual_funding_context: DualFundingChannelContext {
9884
- our_funding_satoshis: funding_satoshis,
9885
- funding_tx_locktime,
9886
- funding_feerate_sat_per_1000_weight,
9887
- our_funding_inputs: funding_inputs,
9888
- },
10038
+ dual_funding_context,
9889
10039
interactive_tx_constructor: None,
9890
10040
interactive_tx_signing_session: None,
9891
10041
};
@@ -10027,6 +10177,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
10027
10177
10028
10178
let dual_funding_context = DualFundingChannelContext {
10029
10179
our_funding_satoshis: our_funding_satoshis,
10180
+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
10030
10181
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
10031
10182
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
10032
10183
our_funding_inputs: our_funding_inputs.clone(),
0 commit comments