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
+ estimate_input_weight, get_output_weight, 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};
@@ -1161,6 +1161,7 @@ impl<'a, SP: Deref> ChannelPhase<SP> where
1161
1161
}
1162
1162
1163
1163
/// Contains all state common to unfunded inbound/outbound channels.
1164
+ #[derive(Default)]
1164
1165
pub(super) struct UnfundedChannelContext {
1165
1166
/// A counter tracking how many ticks have elapsed since this unfunded channel was
1166
1167
/// created. If this unfunded channel reaches peer has yet to respond after reaching
@@ -1684,6 +1685,92 @@ pub(super) trait InteractivelyFunded<SP: Deref> where SP::Target: SignerProvider
1684
1685
1685
1686
fn dual_funding_context(&self) -> &DualFundingChannelContext;
1686
1687
1688
+ fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext;
1689
+
1690
+ fn is_initiator(&self) -> bool;
1691
+
1692
+ fn begin_interactive_funding_tx_construction<ES: Deref>(
1693
+ &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
1694
+ extra_input: Option<(TxIn, TransactionU16LenLimited)>,
1695
+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
1696
+ where ES::Target: EntropySource
1697
+ {
1698
+ let mut funding_inputs_with_extra = self.dual_funding_context_mut().our_funding_inputs.take().unwrap_or_else(|| vec![]);
1699
+
1700
+ if let Some(extra_input) = extra_input {
1701
+ funding_inputs_with_extra.push(extra_input);
1702
+ }
1703
+
1704
+ let mut funding_inputs_prev_outputs: Vec<TxOut> = Vec::with_capacity(funding_inputs_with_extra.len());
1705
+ // Check that vouts exist for each TxIn in provided transactions.
1706
+ for (idx, input) in funding_inputs_with_extra.iter().enumerate() {
1707
+ if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
1708
+ funding_inputs_prev_outputs.push(output.clone());
1709
+ } else {
1710
+ return Err(APIError::APIMisuseError {
1711
+ err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs_with_extra[{}]",
1712
+ input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
1713
+ }
1714
+ }
1715
+
1716
+ let total_input_satoshis: u64 = funding_inputs_with_extra.iter().map(
1717
+ |input| input.1.as_transaction().output.get(input.0.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
1718
+ ).sum();
1719
+ if total_input_satoshis < self.dual_funding_context().our_funding_satoshis {
1720
+ return Err(APIError::APIMisuseError {
1721
+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
1722
+ total_input_satoshis) });
1723
+ }
1724
+
1725
+ // Add output for funding tx
1726
+ let mut funding_outputs = Vec::new();
1727
+ let funding_output_value_satoshis = self.context().get_value_satoshis();
1728
+ let funding_output_script_pubkey = self.context().get_funding_redeemscript().to_p2wsh();
1729
+ let expected_remote_shared_funding_output = if self.is_initiator() {
1730
+ let tx_out = TxOut {
1731
+ value: Amount::from_sat(funding_output_value_satoshis),
1732
+ script_pubkey: funding_output_script_pubkey,
1733
+ };
1734
+ funding_outputs.push(
1735
+ if self.dual_funding_context().their_funding_satoshis.unwrap_or(0) == 0 {
1736
+ OutputOwned::SharedControlFullyOwned(tx_out)
1737
+ } else {
1738
+ OutputOwned::Shared(SharedOwnedOutput::new(
1739
+ tx_out, self.dual_funding_context().our_funding_satoshis
1740
+ ))
1741
+ }
1742
+ );
1743
+ None
1744
+ } else {
1745
+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
1746
+ };
1747
+
1748
+ maybe_add_funding_change_output(signer_provider, self.is_initiator(), self.dual_funding_context().our_funding_satoshis,
1749
+ &funding_inputs_prev_outputs, &mut funding_outputs, self.dual_funding_context().funding_feerate_sat_per_1000_weight,
1750
+ total_input_satoshis, self.context().holder_dust_limit_satoshis, self.context().channel_keys_id).map_err(
1751
+ |_| APIError::APIMisuseError { err: "Could not create change output".to_string() })?;
1752
+
1753
+ let constructor_args = InteractiveTxConstructorArgs {
1754
+ entropy_source,
1755
+ holder_node_id,
1756
+ counterparty_node_id: self.context().counterparty_node_id,
1757
+ channel_id: self.context().channel_id(),
1758
+ feerate_sat_per_kw: self.dual_funding_context_mut().funding_feerate_sat_per_1000_weight,
1759
+ is_initiator: self.is_initiator(),
1760
+ funding_tx_locktime: self.dual_funding_context_mut().funding_tx_locktime,
1761
+ inputs_to_contribute: funding_inputs_with_extra,
1762
+ outputs_to_contribute: funding_outputs,
1763
+ expected_remote_shared_funding_output,
1764
+ };
1765
+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
1766
+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
1767
+ let msg = tx_constructor.take_initiator_first_message();
1768
+
1769
+ self.interactive_tx_constructor_mut().replace(tx_constructor);
1770
+
1771
+ Ok(msg)
1772
+ }
1773
+
1687
1774
fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
1688
1775
InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
1689
1776
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -1846,9 +1933,15 @@ impl<SP: Deref> InteractivelyFunded<SP> for OutboundV2Channel<SP> where SP::Targ
1846
1933
fn dual_funding_context(&self) -> &DualFundingChannelContext {
1847
1934
&self.dual_funding_context
1848
1935
}
1936
+ fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext {
1937
+ &mut self.dual_funding_context
1938
+ }
1849
1939
fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
1850
1940
&mut self.interactive_tx_constructor
1851
1941
}
1942
+ fn is_initiator(&self) -> bool {
1943
+ true
1944
+ }
1852
1945
}
1853
1946
1854
1947
impl<SP: Deref> InteractivelyFunded<SP> for InboundV2Channel<SP> where SP::Target: SignerProvider {
@@ -1861,9 +1954,15 @@ impl<SP: Deref> InteractivelyFunded<SP> for InboundV2Channel<SP> where SP::Targe
1861
1954
fn dual_funding_context(&self) -> &DualFundingChannelContext {
1862
1955
&self.dual_funding_context
1863
1956
}
1957
+ fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext {
1958
+ &mut self.dual_funding_context
1959
+ }
1864
1960
fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
1865
1961
&mut self.interactive_tx_constructor
1866
1962
}
1963
+ fn is_initiator(&self) -> bool {
1964
+ false
1965
+ }
1867
1966
}
1868
1967
1869
1968
impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
@@ -4150,6 +4249,54 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
4150
4249
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
4151
4250
}
4152
4251
4252
+ pub(super) fn maybe_add_funding_change_output<SP: Deref>(signer_provider: &SP, is_initiator: bool,
4253
+ our_funding_satoshis: u64, funding_inputs_prev_outputs: &Vec<TxOut>,
4254
+ funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4255
+ total_input_satoshis: u64, holder_dust_limit_satoshis: u64, channel_keys_id: [u8; 32],
4256
+ ) -> Result<Option<TxOut>, ChannelError> where
4257
+ SP::Target: SignerProvider,
4258
+ {
4259
+ let our_funding_inputs_weight = funding_inputs_prev_outputs.iter().fold(0u64, |weight, prev_output| {
4260
+ weight.saturating_add(estimate_input_weight(prev_output).to_wu())
4261
+ });
4262
+ let our_funding_outputs_weight = funding_outputs.iter().fold(0u64, |weight, out| {
4263
+ weight.saturating_add(get_output_weight(&out.tx_out().script_pubkey).to_wu())
4264
+ });
4265
+ let our_contributed_weight = our_funding_outputs_weight.saturating_add(our_funding_inputs_weight);
4266
+ let mut fees_sats = fee_for_weight(funding_feerate_sat_per_1000_weight, our_contributed_weight);
4267
+
4268
+ // If we are the initiator, we must pay for weight of all common fields in the funding transaction.
4269
+ if is_initiator {
4270
+ let common_fees = fee_for_weight(funding_feerate_sat_per_1000_weight, TX_COMMON_FIELDS_WEIGHT);
4271
+ fees_sats = fees_sats.saturating_add(common_fees);
4272
+ }
4273
+
4274
+ let remaining_value = total_input_satoshis
4275
+ .saturating_sub(our_funding_satoshis)
4276
+ .saturating_sub(fees_sats);
4277
+
4278
+ if remaining_value < holder_dust_limit_satoshis {
4279
+ Ok(None)
4280
+ } else {
4281
+ let change_script = signer_provider.get_destination_script(channel_keys_id).map_err(
4282
+ |_| ChannelError::Close((
4283
+ "Failed to get change script as new destination script".to_owned(),
4284
+ ClosureReason::ProcessingError { err: "Failed to get change script as new destination script".to_owned() }
4285
+ ))
4286
+ )?;
4287
+ let mut change_output = TxOut {
4288
+ value: Amount::from_sat(remaining_value),
4289
+ script_pubkey: change_script,
4290
+ };
4291
+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4292
+
4293
+ let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4294
+ change_output.value = Amount::from_sat(remaining_value.saturating_sub(change_output_fee));
4295
+ funding_outputs.push(OutputOwned::Single(change_output.clone()));
4296
+ Ok(Some(change_output))
4297
+ }
4298
+ }
4299
+
4153
4300
pub(super) fn calculate_our_funding_satoshis(
4154
4301
is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
4155
4302
total_witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32,
@@ -4195,6 +4342,8 @@ pub(super) fn calculate_our_funding_satoshis(
4195
4342
pub(super) struct DualFundingChannelContext {
4196
4343
/// The amount in satoshis we will be contributing to the channel.
4197
4344
pub our_funding_satoshis: u64,
4345
+ /// The amount in satoshis our counterparty will be contributing to the channel.
4346
+ pub their_funding_satoshis: Option<u64>,
4198
4347
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
4199
4348
/// to the current block height to align incentives against fee-sniping.
4200
4349
pub funding_tx_locktime: LockTime,
@@ -4206,7 +4355,7 @@ pub(super) struct DualFundingChannelContext {
4206
4355
/// minus any fees paid for our contributed weight. This means that change will never be generated
4207
4356
/// and the maximum value possible will go towards funding the channel.
4208
4357
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4209
- pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4358
+ pub our_funding_inputs: Option< Vec<(TxIn, TransactionU16LenLimited)> >,
4210
4359
}
4211
4360
4212
4361
// Holder designates channel data owned for the benefit of the user client.
@@ -8295,7 +8444,7 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
8295
8444
pubkeys,
8296
8445
logger,
8297
8446
)?,
8298
- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 }
8447
+ unfunded_context: UnfundedChannelContext::default(),
8299
8448
};
8300
8449
Ok(chan)
8301
8450
}
@@ -8599,7 +8748,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
8599
8748
msg.push_msat,
8600
8749
msg.common_fields.clone(),
8601
8750
)?,
8602
- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 } ,
8751
+ unfunded_context: UnfundedChannelContext::default() ,
8603
8752
};
8604
8753
Ok(chan)
8605
8754
}
@@ -8782,12 +8931,13 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
8782
8931
pubkeys,
8783
8932
logger,
8784
8933
)?,
8785
- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 } ,
8934
+ unfunded_context: UnfundedChannelContext::default() ,
8786
8935
dual_funding_context: DualFundingChannelContext {
8787
8936
our_funding_satoshis: funding_satoshis,
8937
+ their_funding_satoshis: None,
8788
8938
funding_tx_locktime,
8789
8939
funding_feerate_sat_per_1000_weight,
8790
- our_funding_inputs: funding_inputs,
8940
+ our_funding_inputs: Some( funding_inputs) ,
8791
8941
},
8792
8942
interactive_tx_constructor: None,
8793
8943
};
@@ -8948,9 +9098,10 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
8948
9098
8949
9099
let dual_funding_context = DualFundingChannelContext {
8950
9100
our_funding_satoshis: funding_satoshis,
9101
+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
8951
9102
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
8952
9103
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
8953
- our_funding_inputs: funding_inputs.clone(),
9104
+ our_funding_inputs: Some( funding_inputs.clone() ),
8954
9105
};
8955
9106
8956
9107
let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
@@ -8975,7 +9126,7 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
8975
9126
context,
8976
9127
dual_funding_context,
8977
9128
interactive_tx_constructor,
8978
- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 } ,
9129
+ unfunded_context: UnfundedChannelContext::default() ,
8979
9130
})
8980
9131
}
8981
9132
0 commit comments