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};
@@ -2213,6 +2213,106 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
2213
2213
}
2214
2214
2215
2215
impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2216
+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2217
+ pub fn begin_interactive_funding_tx_construction<ES: Deref>(
2218
+ &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2219
+ prev_funding_input: Option<(TxIn, TransactionU16LenLimited)>,
2220
+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
2221
+ where ES::Target: EntropySource
2222
+ {
2223
+ let mut funding_inputs = Vec::new();
2224
+ mem::swap(&mut self.dual_funding_context.our_funding_inputs, &mut funding_inputs);
2225
+
2226
+ if let Some(prev_funding_input) = prev_funding_input {
2227
+ funding_inputs.push(prev_funding_input);
2228
+ }
2229
+
2230
+ let mut funding_inputs_prev_outputs: Vec<&TxOut> = Vec::with_capacity(funding_inputs.len());
2231
+ // Check that vouts exist for each TxIn in provided transactions.
2232
+ for (idx, (txin, tx)) in funding_inputs.iter().enumerate() {
2233
+ if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
2234
+ funding_inputs_prev_outputs.push(output);
2235
+ } else {
2236
+ return Err(APIError::APIMisuseError {
2237
+ err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs[{}]",
2238
+ tx.as_transaction().compute_txid(), txin.previous_output.vout, idx) });
2239
+ }
2240
+ }
2241
+
2242
+ let total_input_satoshis: u64 = funding_inputs.iter().map(
2243
+ |(txin, tx)| tx.as_transaction().output.get(txin.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
2244
+ ).sum();
2245
+ if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2246
+ return Err(APIError::APIMisuseError {
2247
+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2248
+ total_input_satoshis) });
2249
+ }
2250
+
2251
+ // Add output for funding tx
2252
+ let mut funding_outputs = Vec::new();
2253
+ let funding_output_value_satoshis = self.funding.get_value_satoshis();
2254
+ let funding_output_script_pubkey = self.context.get_funding_redeemscript().to_p2wsh();
2255
+ let expected_remote_shared_funding_output = if self.context.is_outbound() {
2256
+ let tx_out = TxOut {
2257
+ value: Amount::from_sat(funding_output_value_satoshis),
2258
+ script_pubkey: funding_output_script_pubkey,
2259
+ };
2260
+ funding_outputs.push(
2261
+ if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2262
+ OutputOwned::SharedControlFullyOwned(tx_out)
2263
+ } else {
2264
+ OutputOwned::Shared(SharedOwnedOutput::new(
2265
+ tx_out, self.dual_funding_context.our_funding_satoshis
2266
+ ))
2267
+ }
2268
+ );
2269
+ None
2270
+ } else {
2271
+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
2272
+ };
2273
+
2274
+ // Optionally add change output
2275
+ if let Some(change_value) = calculate_change_output_value(
2276
+ self.context.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2277
+ &funding_inputs_prev_outputs, &funding_outputs,
2278
+ self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2279
+ self.context.holder_dust_limit_satoshis,
2280
+ ) {
2281
+ let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2282
+ |err| APIError::APIMisuseError {
2283
+ err: format!("Failed to get change script as new destination script, {:?}", err),
2284
+ })?;
2285
+ let mut change_output = TxOut {
2286
+ value: Amount::from_sat(change_value),
2287
+ script_pubkey: change_script,
2288
+ };
2289
+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2290
+ let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2291
+ change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
2292
+ funding_outputs.push(OutputOwned::Single(change_output));
2293
+ }
2294
+
2295
+ let constructor_args = InteractiveTxConstructorArgs {
2296
+ entropy_source,
2297
+ holder_node_id,
2298
+ counterparty_node_id: self.context.counterparty_node_id,
2299
+ channel_id: self.context.channel_id(),
2300
+ feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2301
+ is_initiator: self.context.is_outbound(),
2302
+ funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2303
+ inputs_to_contribute: funding_inputs,
2304
+ outputs_to_contribute: funding_outputs,
2305
+ expected_remote_shared_funding_output,
2306
+ };
2307
+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2308
+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2309
+ let msg = tx_constructor.take_initiator_first_message();
2310
+
2311
+ self.interactive_tx_constructor = Some(tx_constructor);
2312
+
2313
+ Ok(msg)
2314
+ }
2315
+
2216
2316
pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
2217
2317
InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
2218
2318
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4671,6 +4771,9 @@ fn estimate_v2_funding_transaction_fee(
4671
4771
pub(super) struct DualFundingChannelContext {
4672
4772
/// The amount in satoshis we will be contributing to the channel.
4673
4773
pub our_funding_satoshis: u64,
4774
+ /// The amount in satoshis our counterparty will be contributing to the channel.
4775
+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4776
+ pub their_funding_satoshis: Option<u64>,
4674
4777
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
4675
4778
/// to the current block height to align incentives against fee-sniping.
4676
4779
pub funding_tx_locktime: LockTime,
@@ -4682,6 +4785,8 @@ pub(super) struct DualFundingChannelContext {
4682
4785
/// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
4683
4786
/// minus any fees paid for our contributed weight. This means that change will never be generated
4684
4787
/// and the maximum value possible will go towards funding the channel.
4788
+ ///
4789
+ /// Note that this field may be emptied once the interactive negotiation has been started.
4685
4790
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4686
4791
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4687
4792
}
@@ -9608,6 +9713,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
9608
9713
unfunded_context,
9609
9714
dual_funding_context: DualFundingChannelContext {
9610
9715
our_funding_satoshis: funding_satoshis,
9716
+ their_funding_satoshis: None,
9611
9717
funding_tx_locktime,
9612
9718
funding_feerate_sat_per_1000_weight,
9613
9719
our_funding_inputs: funding_inputs,
@@ -9753,6 +9859,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
9753
9859
9754
9860
let dual_funding_context = DualFundingChannelContext {
9755
9861
our_funding_satoshis: our_funding_satoshis,
9862
+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
9756
9863
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
9757
9864
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
9758
9865
our_funding_inputs: our_funding_inputs.clone(),
0 commit comments