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};
@@ -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
+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2224
+ pub fn begin_interactive_funding_tx_construction<ES: Deref>(
2225
+ &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2226
+ prev_funding_input: Option<(TxIn, TransactionU16LenLimited)>,
2227
+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
2228
+ where ES::Target: EntropySource
2229
+ {
2230
+ let mut funding_inputs = Vec::new();
2231
+ mem::swap(&mut self.dual_funding_context.our_funding_inputs, &mut funding_inputs);
2232
+
2233
+ if let Some(prev_funding_input) = prev_funding_input {
2234
+ funding_inputs.push(prev_funding_input);
2235
+ }
2236
+
2237
+ let mut funding_inputs_prev_outputs: Vec<&TxOut> = Vec::with_capacity(funding_inputs.len());
2238
+ // Check that vouts exist for each TxIn in provided transactions.
2239
+ for (idx, (txin, tx)) in funding_inputs.iter().enumerate() {
2240
+ if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
2241
+ funding_inputs_prev_outputs.push(output);
2242
+ } else {
2243
+ return Err(APIError::APIMisuseError {
2244
+ err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs[{}]",
2245
+ tx.as_transaction().compute_txid(), txin.previous_output.vout, idx) });
2246
+ }
2247
+ }
2248
+
2249
+ let total_input_satoshis: u64 = funding_inputs.iter().map(
2250
+ |(txin, tx)| tx.as_transaction().output.get(txin.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
2251
+ ).sum();
2252
+ if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2253
+ return Err(APIError::APIMisuseError {
2254
+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2255
+ total_input_satoshis) });
2256
+ }
2257
+
2258
+ // Add output for funding tx
2259
+ let mut funding_outputs = Vec::new();
2260
+ let funding_output_value_satoshis = self.funding.get_value_satoshis();
2261
+ let funding_output_script_pubkey = self.funding.get_funding_redeemscript().to_p2wsh();
2262
+ let expected_remote_shared_funding_output = if self.funding.is_outbound() {
2263
+ let tx_out = TxOut {
2264
+ value: Amount::from_sat(funding_output_value_satoshis),
2265
+ script_pubkey: funding_output_script_pubkey,
2266
+ };
2267
+ funding_outputs.push(
2268
+ if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2269
+ OutputOwned::SharedControlFullyOwned(tx_out)
2270
+ } else {
2271
+ OutputOwned::Shared(SharedOwnedOutput::new(
2272
+ tx_out, self.dual_funding_context.our_funding_satoshis
2273
+ ))
2274
+ }
2275
+ );
2276
+ None
2277
+ } else {
2278
+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
2279
+ };
2280
+
2281
+ // Optionally add change output
2282
+ if let Some(change_value) = calculate_change_output_value(
2283
+ self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2284
+ &funding_inputs_prev_outputs, &funding_outputs,
2285
+ self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2286
+ self.context.holder_dust_limit_satoshis,
2287
+ ) {
2288
+ let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2289
+ |err| APIError::APIMisuseError {
2290
+ err: format!("Failed to get change script as new destination script, {:?}", err),
2291
+ })?;
2292
+ let mut change_output = TxOut {
2293
+ value: Amount::from_sat(change_value),
2294
+ script_pubkey: change_script,
2295
+ };
2296
+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2297
+ let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2298
+ change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
2299
+ funding_outputs.push(OutputOwned::Single(change_output));
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,6 +4963,8 @@ 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
}
@@ -9835,6 +9940,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
9835
9940
unfunded_context,
9836
9941
dual_funding_context: DualFundingChannelContext {
9837
9942
our_funding_satoshis: funding_satoshis,
9943
+ their_funding_satoshis: None,
9838
9944
funding_tx_locktime,
9839
9945
funding_feerate_sat_per_1000_weight,
9840
9946
our_funding_inputs: funding_inputs,
@@ -9980,6 +10086,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
9980
10086
9981
10087
let dual_funding_context = DualFundingChannelContext {
9982
10088
our_funding_satoshis: our_funding_satoshis,
10089
+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
9983
10090
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
9984
10091
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
9985
10092
our_funding_inputs: our_funding_inputs.clone(),
0 commit comments