Skip to content

Commit 8f2807c

Browse files
committed
Add begin_interactive_funding_tx_construction()
1 parent abf06d9 commit 8f2807c

File tree

2 files changed

+314
-17
lines changed

2 files changed

+314
-17
lines changed

lightning/src/ln/channel.rs

Lines changed: 161 additions & 10 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::EcdsaSighashType;
1515
use bitcoin::consensus::encode;
1616
use bitcoin::absolute::LockTime;
@@ -30,9 +30,9 @@ use crate::ln::types::ChannelId;
3030
use crate::types::payment::{PaymentPreimage, PaymentHash};
3131
use crate::types::features::{ChannelTypeFeatures, InitFeatures};
3232
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,
3636
};
3737
use crate::ln::msgs;
3838
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket};
@@ -2237,6 +2237,107 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
22372237
}
22382238

22392239
impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2240+
/// Prepare and start interactive transaction negotiation.
2241+
/// `change_destination_opt` - Optional destination for optional change; if None, default destination address is used.
2242+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2243+
fn begin_interactive_funding_tx_construction<ES: Deref>(
2244+
&mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2245+
change_destination_opt: Option<ScriptBuf>,
2246+
) -> Result<Option<InteractiveTxMessageSend>, APIError>
2247+
where ES::Target: EntropySource
2248+
{
2249+
let mut funding_inputs = Vec::new();
2250+
mem::swap(&mut self.dual_funding_context.our_funding_inputs, &mut funding_inputs);
2251+
2252+
let funding_inputs_prev_outputs = DualFundingChannelContext::txouts_from_input_prev_txs(&funding_inputs)
2253+
.map_err(|err| APIError::APIMisuseError { err: err.to_string() })?;
2254+
2255+
let total_input_satoshis: u64 = funding_inputs_prev_outputs.iter().map(|txout| txout.value.to_sat()).sum();
2256+
if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2257+
return Err(APIError::APIMisuseError {
2258+
err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2259+
total_input_satoshis) });
2260+
}
2261+
2262+
// Add output for funding tx
2263+
let mut funding_outputs = Vec::new();
2264+
let funding_output_value_satoshis = self.funding.get_value_satoshis();
2265+
let funding_output_script_pubkey = self.funding.get_funding_redeemscript().to_p2wsh();
2266+
let expected_remote_shared_funding_output = if self.funding.is_outbound() {
2267+
let tx_out = TxOut {
2268+
value: Amount::from_sat(funding_output_value_satoshis),
2269+
script_pubkey: funding_output_script_pubkey,
2270+
};
2271+
funding_outputs.push(
2272+
if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2273+
OutputOwned::SharedControlFullyOwned(tx_out)
2274+
} else {
2275+
OutputOwned::Shared(SharedOwnedOutput::new(
2276+
tx_out, self.dual_funding_context.our_funding_satoshis
2277+
))
2278+
}
2279+
);
2280+
None
2281+
} else {
2282+
Some((funding_output_script_pubkey, funding_output_value_satoshis))
2283+
};
2284+
2285+
// Optionally add change output
2286+
let change_value_opt = calculate_change_output_value(
2287+
self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2288+
&funding_inputs_prev_outputs, &funding_outputs,
2289+
self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2290+
self.context.holder_dust_limit_satoshis,
2291+
).map_err(|err| APIError::APIMisuseError {
2292+
err: format!("Insufficient inputs, cannot cover intended contribution of {} and fees; {}",
2293+
self.dual_funding_context.our_funding_satoshis, err
2294+
),
2295+
})?;
2296+
if let Some(change_value) = change_value_opt {
2297+
let change_script = match change_destination_opt {
2298+
Some(script) => script,
2299+
None => {
2300+
signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2301+
|err| APIError::APIMisuseError {
2302+
err: format!("Failed to get change script as new destination script, {:?}", err),
2303+
})?
2304+
}
2305+
};
2306+
let mut change_output = TxOut {
2307+
value: Amount::from_sat(change_value),
2308+
script_pubkey: change_script,
2309+
};
2310+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2311+
let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2312+
let change_value_decreased_with_fee = change_value.saturating_sub(change_output_fee);
2313+
// Check dust limit again
2314+
if change_value_decreased_with_fee > self.context.holder_dust_limit_satoshis {
2315+
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
2316+
funding_outputs.push(OutputOwned::Single(change_output));
2317+
}
2318+
}
2319+
2320+
let constructor_args = InteractiveTxConstructorArgs {
2321+
entropy_source,
2322+
holder_node_id,
2323+
counterparty_node_id: self.context.counterparty_node_id,
2324+
channel_id: self.context.channel_id(),
2325+
feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2326+
is_initiator: self.funding.is_outbound(),
2327+
funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2328+
inputs_to_contribute: funding_inputs,
2329+
outputs_to_contribute: funding_outputs,
2330+
expected_remote_shared_funding_output,
2331+
};
2332+
let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2333+
.map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2334+
let msg = tx_constructor.take_initiator_first_message();
2335+
2336+
self.interactive_tx_constructor = Some(tx_constructor);
2337+
2338+
Ok(msg)
2339+
}
2340+
22402341
pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
22412342
InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
22422343
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4873,10 +4974,28 @@ fn check_v2_funding_inputs_sufficient(
48734974
}
48744975
}
48754976

4977+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
4978+
fn add_funding_change_output(
4979+
change_value: u64, change_script: ScriptBuf,
4980+
funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4981+
) {
4982+
let mut change_output = TxOut {
4983+
value: Amount::from_sat(change_value),
4984+
script_pubkey: change_script,
4985+
};
4986+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4987+
let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4988+
change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
4989+
funding_outputs.push(OutputOwned::Single(change_output.clone()));
4990+
}
4991+
48764992
/// Context for dual-funded channels.
48774993
pub(super) struct DualFundingChannelContext {
48784994
/// The amount in satoshis we will be contributing to the channel.
48794995
pub our_funding_satoshis: u64,
4996+
/// The amount in satoshis our counterparty will be contributing to the channel.
4997+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4998+
pub their_funding_satoshis: Option<u64>,
48804999
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
48815000
/// to the current block height to align incentives against fee-sniping.
48825001
pub funding_tx_locktime: LockTime,
@@ -4888,10 +5007,39 @@ pub(super) struct DualFundingChannelContext {
48885007
/// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
48895008
/// minus any fees paid for our contributed weight. This means that change will never be generated
48905009
/// and the maximum value possible will go towards funding the channel.
5010+
///
5011+
/// Note that this field may be emptied once the interactive negotiation has been started.
48915012
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
48925013
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
48935014
}
48945015

5016+
impl DualFundingChannelContext {
5017+
/// Obtain prev outputs for each supplied input and matching transaction.
5018+
/// Can error when there a prev tx does not have an output for the specified vout number.
5019+
/// Also checks for matching of transaction IDs.
5020+
fn txouts_from_input_prev_txs(inputs: &Vec<(TxIn, TransactionU16LenLimited)>) -> Result<Vec<&TxOut>, ChannelError> {
5021+
let mut prev_outputs: Vec<&TxOut> = Vec::with_capacity(inputs.len());
5022+
// Check that vouts exist for each TxIn in provided transactions.
5023+
for (idx, (txin, tx)) in inputs.iter().enumerate() {
5024+
let txid = tx.as_transaction().compute_txid();
5025+
if txin.previous_output.txid != txid {
5026+
return Err(ChannelError::Warn(
5027+
format!("Transaction input txid mismatch, {} vs. {}, at index {}", txin.previous_output.txid, txid, idx)
5028+
));
5029+
}
5030+
if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
5031+
prev_outputs.push(output);
5032+
} else {
5033+
return Err(ChannelError::Warn(
5034+
format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn, at index {}",
5035+
txid, txin.previous_output.vout, idx)
5036+
));
5037+
}
5038+
}
5039+
Ok(prev_outputs)
5040+
}
5041+
}
5042+
48955043
// Holder designates channel data owned for the benefit of the user client.
48965044
// Counterparty designates channel data owned by the another channel participant entity.
48975045
pub(super) struct FundedChannel<SP: Deref> where SP::Target: SignerProvider {
@@ -9876,16 +10024,18 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
987610024
unfunded_channel_age_ticks: 0,
987710025
holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
987810026
};
10027+
let dual_funding_context = DualFundingChannelContext {
10028+
our_funding_satoshis: funding_satoshis,
10029+
their_funding_satoshis: None,
10030+
funding_tx_locktime,
10031+
funding_feerate_sat_per_1000_weight,
10032+
our_funding_inputs: funding_inputs,
10033+
};
987910034
let chan = Self {
988010035
funding,
988110036
context,
988210037
unfunded_context,
9883-
dual_funding_context: DualFundingChannelContext {
9884-
our_funding_satoshis: funding_satoshis,
9885-
funding_tx_locktime,
9886-
funding_feerate_sat_per_1000_weight,
9887-
our_funding_inputs: funding_inputs,
9888-
},
10038+
dual_funding_context,
988910039
interactive_tx_constructor: None,
989010040
interactive_tx_signing_session: None,
989110041
};
@@ -10027,6 +10177,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
1002710177

1002810178
let dual_funding_context = DualFundingChannelContext {
1002910179
our_funding_satoshis: our_funding_satoshis,
10180+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
1003010181
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
1003110182
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
1003210183
our_funding_inputs: our_funding_inputs.clone(),

0 commit comments

Comments
 (0)