1010use bitcoin::amount::Amount;
1111use bitcoin::constants::ChainHash;
1212use bitcoin::script::{Script, ScriptBuf, Builder, WScriptHash};
13- use bitcoin::transaction::{Transaction, TxIn};
13+ use bitcoin::transaction::{Transaction, TxIn, TxOut };
1414use bitcoin::sighash;
1515use bitcoin::sighash::EcdsaSighashType;
1616use bitcoin::consensus::encode;
@@ -31,9 +31,9 @@ use crate::ln::types::ChannelId;
3131use crate::types::payment::{PaymentPreimage, PaymentHash};
3232use crate::types::features::{ChannelTypeFeatures, InitFeatures};
3333use 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,
3737};
3838use crate::ln::msgs;
3939use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError};
@@ -1161,6 +1161,7 @@ impl<'a, SP: Deref> ChannelPhase<SP> where
11611161}
11621162
11631163/// Contains all state common to unfunded inbound/outbound channels.
1164+ #[derive(Default)]
11641165pub(super) struct UnfundedChannelContext {
11651166 /// A counter tracking how many ticks have elapsed since this unfunded channel was
11661167 /// 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
16841685
16851686 fn dual_funding_context(&self) -> &DualFundingChannelContext;
16861687
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+
16871774 fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
16881775 InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
16891776 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
18461933 fn dual_funding_context(&self) -> &DualFundingChannelContext {
18471934 &self.dual_funding_context
18481935 }
1936+ fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext {
1937+ &mut self.dual_funding_context
1938+ }
18491939 fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
18501940 &mut self.interactive_tx_constructor
18511941 }
1942+ fn is_initiator(&self) -> bool {
1943+ true
1944+ }
18521945}
18531946
18541947impl<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
18611954 fn dual_funding_context(&self) -> &DualFundingChannelContext {
18621955 &self.dual_funding_context
18631956 }
1957+ fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext {
1958+ &mut self.dual_funding_context
1959+ }
18641960 fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
18651961 &mut self.interactive_tx_constructor
18661962 }
1963+ fn is_initiator(&self) -> bool {
1964+ false
1965+ }
18671966}
18681967
18691968impl<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
41504249 cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
41514250}
41524251
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+
41534300pub(super) fn calculate_our_funding_satoshis(
41544301 is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
41554302 total_witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32,
@@ -4195,6 +4342,8 @@ pub(super) fn calculate_our_funding_satoshis(
41954342pub(super) struct DualFundingChannelContext {
41964343 /// The amount in satoshis we will be contributing to the channel.
41974344 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>,
41984347 /// The funding transaction locktime suggested by the initiator. If set by us, it is always set
41994348 /// to the current block height to align incentives against fee-sniping.
42004349 pub funding_tx_locktime: LockTime,
@@ -4206,7 +4355,7 @@ pub(super) struct DualFundingChannelContext {
42064355 /// minus any fees paid for our contributed weight. This means that change will never be generated
42074356 /// and the maximum value possible will go towards funding the channel.
42084357 #[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)> >,
42104359}
42114360
42124361// 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 {
82958444 pubkeys,
82968445 logger,
82978446 )?,
8298- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 }
8447+ unfunded_context: UnfundedChannelContext::default(),
82998448 };
83008449 Ok(chan)
83018450 }
@@ -8599,7 +8748,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
85998748 msg.push_msat,
86008749 msg.common_fields.clone(),
86018750 )?,
8602- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 } ,
8751+ unfunded_context: UnfundedChannelContext::default() ,
86038752 };
86048753 Ok(chan)
86058754 }
@@ -8782,12 +8931,13 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
87828931 pubkeys,
87838932 logger,
87848933 )?,
8785- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 } ,
8934+ unfunded_context: UnfundedChannelContext::default() ,
87868935 dual_funding_context: DualFundingChannelContext {
87878936 our_funding_satoshis: funding_satoshis,
8937+ their_funding_satoshis: None,
87888938 funding_tx_locktime,
87898939 funding_feerate_sat_per_1000_weight,
8790- our_funding_inputs: funding_inputs,
8940+ our_funding_inputs: Some( funding_inputs) ,
87918941 },
87928942 interactive_tx_constructor: None,
87938943 };
@@ -8948,9 +9098,10 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
89489098
89499099 let dual_funding_context = DualFundingChannelContext {
89509100 our_funding_satoshis: funding_satoshis,
9101+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
89519102 funding_tx_locktime: LockTime::from_consensus(msg.locktime),
89529103 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() ),
89549105 };
89559106
89569107 let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
@@ -8975,7 +9126,7 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
89759126 context,
89769127 dual_funding_context,
89779128 interactive_tx_constructor,
8978- unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 } ,
9129+ unfunded_context: UnfundedChannelContext::default() ,
89799130 })
89809131 }
89819132
0 commit comments