Skip to content

Commit d37f966

Browse files
committed
Add begin_interactive_funding_tx_construction()
1 parent f5c0433 commit d37f966

File tree

3 files changed

+272
-19
lines changed

3 files changed

+272
-19
lines changed

lightning/src/ln/channel.rs

Lines changed: 130 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
use bitcoin::amount::Amount;
1111
use bitcoin::constants::ChainHash;
1212
use bitcoin::script::{Script, ScriptBuf, Builder, WScriptHash};
13-
use bitcoin::transaction::{Transaction, TxIn};
13+
use bitcoin::transaction::{Transaction, TxIn, TxOut};
1414
use bitcoin::sighash;
1515
use bitcoin::sighash::EcdsaSighashType;
1616
use bitcoin::consensus::encode;
@@ -31,9 +31,9 @@ use crate::ln::types::ChannelId;
3131
use crate::types::payment::{PaymentPreimage, PaymentHash};
3232
use crate::types::features::{ChannelTypeFeatures, InitFeatures};
3333
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,
3737
};
3838
use crate::ln::msgs;
3939
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError};
@@ -2032,6 +2032,91 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
20322032
}
20332033

20342034
impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2035+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2036+
fn begin_interactive_funding_tx_construction<ES: Deref>(
2037+
&mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2038+
) -> Result<Option<InteractiveTxMessageSend>, APIError>
2039+
where ES::Target: EntropySource
2040+
{
2041+
let mut funding_inputs = Vec::new();
2042+
mem::swap(&mut self.dual_funding_context.our_funding_inputs, &mut funding_inputs);
2043+
2044+
let funding_inputs_prev_outputs = DualFundingChannelContext::txouts_from_input_prev_txs(&funding_inputs)
2045+
.map_err(|err| APIError::APIMisuseError { err: err.to_string() })?;
2046+
2047+
let total_input_satoshis: u64 = funding_inputs_prev_outputs.iter().map(|txout| txout.value.to_sat()).sum();
2048+
if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2049+
return Err(APIError::APIMisuseError {
2050+
err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2051+
total_input_satoshis) });
2052+
}
2053+
2054+
// Add output for funding tx
2055+
let mut funding_outputs = Vec::new();
2056+
let funding_output_value_satoshis = self.context.get_value_satoshis();
2057+
let funding_output_script_pubkey = self.context.get_funding_redeemscript().to_p2wsh();
2058+
let expected_remote_shared_funding_output = if self.context.is_outbound() {
2059+
let tx_out = TxOut {
2060+
value: Amount::from_sat(funding_output_value_satoshis),
2061+
script_pubkey: funding_output_script_pubkey,
2062+
};
2063+
funding_outputs.push(
2064+
if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2065+
OutputOwned::SharedControlFullyOwned(tx_out)
2066+
} else {
2067+
OutputOwned::Shared(SharedOwnedOutput::new(
2068+
tx_out, self.dual_funding_context.our_funding_satoshis
2069+
))
2070+
}
2071+
);
2072+
None
2073+
} else {
2074+
Some((funding_output_script_pubkey, funding_output_value_satoshis))
2075+
};
2076+
2077+
// Optionally add change output
2078+
if let Some(change_value) = calculate_change_output_value(
2079+
self.context.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2080+
&funding_inputs_prev_outputs, &funding_outputs,
2081+
self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2082+
self.context.holder_dust_limit_satoshis,
2083+
) {
2084+
let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2085+
|err| APIError::APIMisuseError {
2086+
err: format!("Failed to get change script as new destination script, {:?}", err),
2087+
})?;
2088+
let mut change_output = TxOut {
2089+
value: Amount::from_sat(change_value),
2090+
script_pubkey: change_script,
2091+
};
2092+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2093+
let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2094+
change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
2095+
// Note: dust check not done here, should be handled before
2096+
funding_outputs.push(OutputOwned::Single(change_output));
2097+
}
2098+
2099+
let constructor_args = InteractiveTxConstructorArgs {
2100+
entropy_source,
2101+
holder_node_id,
2102+
counterparty_node_id: self.context.counterparty_node_id,
2103+
channel_id: self.context.channel_id(),
2104+
feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2105+
is_initiator: self.context.is_outbound(),
2106+
funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2107+
inputs_to_contribute: funding_inputs,
2108+
outputs_to_contribute: funding_outputs,
2109+
expected_remote_shared_funding_output,
2110+
};
2111+
let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2112+
.map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2113+
let msg = tx_constructor.take_initiator_first_message();
2114+
2115+
self.interactive_tx_constructor = Some(tx_constructor);
2116+
2117+
Ok(msg)
2118+
}
2119+
20352120
pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
20362121
InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
20372122
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4470,7 +4555,6 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
44704555
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
44714556
}
44724557

4473-
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
44744558
pub(super) fn calculate_our_funding_satoshis(
44754559
is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
44764560
total_witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32,
@@ -4516,6 +4600,9 @@ pub(super) fn calculate_our_funding_satoshis(
45164600
pub(super) struct DualFundingChannelContext {
45174601
/// The amount in satoshis we will be contributing to the channel.
45184602
pub our_funding_satoshis: u64,
4603+
/// The amount in satoshis our counterparty will be contributing to the channel.
4604+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4605+
pub their_funding_satoshis: Option<u64>,
45194606
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
45204607
/// to the current block height to align incentives against fee-sniping.
45214608
pub funding_tx_locktime: LockTime,
@@ -4527,10 +4614,39 @@ pub(super) struct DualFundingChannelContext {
45274614
/// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
45284615
/// minus any fees paid for our contributed weight. This means that change will never be generated
45294616
/// and the maximum value possible will go towards funding the channel.
4617+
///
4618+
/// Note that this field may be emptied once the interactive negotiation has been started.
45304619
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
45314620
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
45324621
}
45334622

4623+
impl DualFundingChannelContext {
4624+
/// Obtain prev outputs for each supplied input and matching transaction.
4625+
/// Can error when there a prev tx does not have an output for the specified vout number.
4626+
/// Also checks for matching of transaction IDs.
4627+
fn txouts_from_input_prev_txs(inputs: &Vec<(TxIn, TransactionU16LenLimited)>) -> Result<Vec<&TxOut>, ChannelError> {
4628+
let mut prev_outputs: Vec<&TxOut> = Vec::with_capacity(inputs.len());
4629+
// Check that vouts exist for each TxIn in provided transactions.
4630+
for (idx, (txin, tx)) in inputs.iter().enumerate() {
4631+
let txid = tx.as_transaction().compute_txid();
4632+
if txin.previous_output.txid != txid {
4633+
return Err(ChannelError::Warn(
4634+
format!("Transaction input txid mismatch, {} vs. {}, at index {}", txin.previous_output.txid, txid, idx)
4635+
));
4636+
}
4637+
if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
4638+
prev_outputs.push(output);
4639+
} else {
4640+
return Err(ChannelError::Warn(
4641+
format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn, at index {}",
4642+
txid, txin.previous_output.vout, idx)
4643+
));
4644+
}
4645+
}
4646+
Ok(prev_outputs)
4647+
}
4648+
}
4649+
45344650
// Holder designates channel data owned for the benefit of the user client.
45354651
// Counterparty designates channel data owned by the another channel participant entity.
45364652
pub(super) struct FundedChannel<SP: Deref> where SP::Target: SignerProvider {
@@ -9164,15 +9280,17 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
91649280
unfunded_channel_age_ticks: 0,
91659281
holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
91669282
};
9283+
let dual_funding_context = DualFundingChannelContext {
9284+
our_funding_satoshis: funding_satoshis,
9285+
their_funding_satoshis: None,
9286+
funding_tx_locktime,
9287+
funding_feerate_sat_per_1000_weight,
9288+
our_funding_inputs: funding_inputs,
9289+
};
91679290
let chan = Self {
91689291
context,
91699292
unfunded_context,
9170-
dual_funding_context: DualFundingChannelContext {
9171-
our_funding_satoshis: funding_satoshis,
9172-
funding_tx_locktime,
9173-
funding_feerate_sat_per_1000_weight,
9174-
our_funding_inputs: funding_inputs,
9175-
},
9293+
dual_funding_context,
91769294
interactive_tx_constructor: None,
91779295
};
91789296
Ok(chan)
@@ -9319,6 +9437,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
93199437

93209438
let dual_funding_context = DualFundingChannelContext {
93219439
our_funding_satoshis: funding_satoshis,
9440+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
93229441
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
93239442
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
93249443
our_funding_inputs: funding_inputs.clone(),

lightning/src/ln/channelmanager.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ use crate::ln::inbound_payment;
4949
use crate::ln::types::ChannelId;
5050
use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
5151
use crate::ln::channel::{self, Channel, ChannelError, ChannelUpdateStatus, FundedChannel, ShutdownResult, UpdateFulfillCommitFetch, OutboundV1Channel, ReconnectionMsg, InboundV1Channel, WithChannelContext};
52-
#[cfg(any(dual_funding, splicing))]
52+
#[cfg(dual_funding)]
5353
use crate::ln::channel::PendingV2Channel;
5454
use crate::ln::channel_state::ChannelDetails;
5555
use crate::types::features::{Bolt12InvoiceFeatures, ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};

0 commit comments

Comments
 (0)