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