Skip to content

Commit 5f06d37

Browse files
committed
Replace funding input tuple with struct
The funding inputs used for splicing and v2 channel establishment are passed as a tuple of txin, prevtx, and witness weight. Add a struct so that the items included can be better documented.
1 parent f4b62b9 commit 5f06d37

File tree

5 files changed

+75
-49
lines changed

5 files changed

+75
-49
lines changed

lightning/src/ln/channel.rs

Lines changed: 32 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ use crate::ln::channel_state::{
5252
OutboundHTLCDetails, OutboundHTLCStateDetails,
5353
};
5454
use crate::ln::channelmanager::{
55-
self, FundingConfirmedMessage, HTLCFailureMsg, HTLCSource, OpenChannelMessage,
55+
self, FundingConfirmedMessage, FundingTxInput, HTLCFailureMsg, HTLCSource, OpenChannelMessage,
5656
PaymentClaimDetails, PendingHTLCInfo, PendingHTLCStatus, RAACommitmentOrder, SentHTLCId,
5757
BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA,
5858
};
@@ -5914,10 +5914,11 @@ fn estimate_v2_funding_transaction_fee(
59145914
#[cfg(splicing)]
59155915
#[rustfmt::skip]
59165916
fn check_v2_funding_inputs_sufficient(
5917-
contribution_amount: i64, funding_inputs: &[(TxIn, Transaction, Weight)], is_initiator: bool,
5917+
contribution_amount: i64, funding_inputs: &[FundingTxInput], is_initiator: bool,
59185918
is_splice: bool, funding_feerate_sat_per_1000_weight: u32,
59195919
) -> Result<u64, ChannelError> {
5920-
let mut total_input_witness_weight = Weight::from_wu(funding_inputs.iter().map(|(_, _, w)| w.to_wu()).sum());
5920+
let mut total_input_witness_weight =
5921+
funding_inputs.iter().map(|FundingTxInput { witness_weight, .. }| witness_weight).sum();
59215922
let mut funding_inputs_len = funding_inputs.len();
59225923
if is_initiator && is_splice {
59235924
// consider the weight of the input and witness needed for spending the old funding transaction
@@ -5927,13 +5928,13 @@ fn check_v2_funding_inputs_sufficient(
59275928
let estimated_fee = estimate_v2_funding_transaction_fee(is_initiator, funding_inputs_len, total_input_witness_weight, funding_feerate_sat_per_1000_weight);
59285929

59295930
let mut total_input_sats = 0u64;
5930-
for (idx, input) in funding_inputs.iter().enumerate() {
5931-
if let Some(output) = input.1.output.get(input.0.previous_output.vout as usize) {
5931+
for (idx, FundingTxInput { txin, prevtx, .. }) in funding_inputs.iter().enumerate() {
5932+
if let Some(output) = prevtx.output.get(txin.previous_output.vout as usize) {
59325933
total_input_sats = total_input_sats.saturating_add(output.value.to_sat());
59335934
} else {
59345935
return Err(ChannelError::Warn(format!(
59355936
"Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs[{}]",
5936-
input.1.compute_txid(), input.0.previous_output.vout, idx
5937+
prevtx.compute_txid(), txin.previous_output.vout, idx
59375938
)));
59385939
}
59395940
}
@@ -5977,7 +5978,7 @@ pub(super) struct FundingNegotiationContext {
59775978
pub shared_funding_input: Option<SharedOwnedInput>,
59785979
/// The funding inputs we will be contributing to the channel.
59795980
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
5980-
pub our_funding_inputs: Vec<(TxIn, Transaction, Weight)>,
5981+
pub our_funding_inputs: Vec<FundingTxInput>,
59815982
/// The change output script. This will be used if needed or -- if not set -- generated using
59825983
/// `SignerProvider::get_destination_script`.
59835984
#[allow(dead_code)] // TODO(splicing): Remove once splicing is enabled.
@@ -6049,8 +6050,11 @@ impl FundingNegotiationContext {
60496050
}
60506051
}
60516052

6052-
let funding_inputs =
6053-
self.our_funding_inputs.into_iter().map(|(txin, tx, _)| (txin, tx)).collect();
6053+
let funding_inputs = self
6054+
.our_funding_inputs
6055+
.into_iter()
6056+
.map(|FundingTxInput { txin, prevtx, .. }| (txin, prevtx))
6057+
.collect();
60546058

60556059
let constructor_args = InteractiveTxConstructorArgs {
60566060
entropy_source,
@@ -10610,9 +10614,8 @@ where
1061010614
/// generated by `SignerProvider::get_destination_script`.
1061110615
#[cfg(splicing)]
1061210616
pub fn splice_channel(
10613-
&mut self, our_funding_contribution_satoshis: i64,
10614-
our_funding_inputs: Vec<(TxIn, Transaction, Weight)>, change_script: Option<ScriptBuf>,
10615-
funding_feerate_per_kw: u32, locktime: u32,
10617+
&mut self, our_funding_contribution_satoshis: i64, our_funding_inputs: Vec<FundingTxInput>,
10618+
change_script: Option<ScriptBuf>, funding_feerate_per_kw: u32, locktime: u32,
1061610619
) -> Result<msgs::SpliceInit, APIError> {
1061710620
// Check if a splice has been initiated already.
1061810621
// Note: only a single outstanding splice is supported (per spec)
@@ -10678,7 +10681,7 @@ where
1067810681
),
1067910682
})?;
1068010683

10681-
for (_, tx, _) in our_funding_inputs.iter() {
10684+
for FundingTxInput { txin, prevtx, .. } in our_funding_inputs.iter() {
1068210685
const MESSAGE_TEMPLATE: msgs::TxAddInput = msgs::TxAddInput {
1068310686
channel_id: ChannelId([0; 32]),
1068410687
serial_id: 0,
@@ -10687,7 +10690,7 @@ where
1068710690
sequence: 0,
1068810691
shared_input_txid: None,
1068910692
};
10690-
let message_len = MESSAGE_TEMPLATE.serialized_length() + tx.serialized_length();
10693+
let message_len = MESSAGE_TEMPLATE.serialized_length() + prevtx.serialized_length();
1069110694
if message_len > LN_MAX_MSG_LEN {
1069210695
return Err(APIError::APIMisuseError {
1069310696
err: format!(
@@ -12472,7 +12475,7 @@ where
1247212475
pub fn new_outbound<ES: Deref, F: Deref, L: Deref>(
1247312476
fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
1247412477
counterparty_node_id: PublicKey, their_features: &InitFeatures, funding_satoshis: u64,
12475-
funding_inputs: Vec<(TxIn, Transaction, Weight)>, user_id: u128, config: &UserConfig,
12478+
funding_inputs: Vec<FundingTxInput>, user_id: u128, config: &UserConfig,
1247612479
current_chain_height: u32, outbound_scid_alias: u64, funding_confirmation_target: ConfirmationTarget,
1247712480
logger: L,
1247812481
) -> Result<Self, APIError>
@@ -12686,8 +12689,10 @@ where
1268612689
value: Amount::from_sat(funding.get_value_satoshis()),
1268712690
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
1268812691
};
12689-
let inputs_to_contribute =
12690-
our_funding_inputs.into_iter().map(|(txin, tx, _)| (txin, tx)).collect();
12692+
let inputs_to_contribute = our_funding_inputs
12693+
.into_iter()
12694+
.map(|FundingTxInput { txin, prevtx, .. }| (txin, prevtx))
12695+
.collect();
1269112696

1269212697
let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
1269312698
InteractiveTxConstructorArgs {
@@ -14123,7 +14128,7 @@ mod tests {
1412314128
TOTAL_BITCOIN_SUPPLY_SATOSHIS,
1412414129
};
1412514130
use crate::ln::channel_keys::{RevocationBasepoint, RevocationKey};
14126-
use crate::ln::channelmanager::{self, HTLCSource, PaymentId};
14131+
use crate::ln::channelmanager::{self, FundingTxInput, HTLCSource, PaymentId};
1412714132
use crate::ln::msgs;
1412814133
use crate::ln::msgs::{ChannelUpdate, UnsignedChannelUpdate, MAX_VALUE_MSAT};
1412914134
use crate::ln::onion_utils::{AttributionData, LocalHTLCFailureReason};
@@ -15896,19 +15901,21 @@ mod tests {
1589615901

1589715902
#[cfg(splicing)]
1589815903
#[rustfmt::skip]
15899-
fn funding_input_sats(input_value_sats: u64) -> (TxIn, Transaction, Weight) {
15904+
fn funding_input_sats(input_value_sats: u64) -> FundingTxInput {
1590015905
use crate::sign::P2WPKH_WITNESS_WEIGHT;
1590115906

15902-
let input_1_prev_out = TxOut { value: Amount::from_sat(input_value_sats), script_pubkey: ScriptBuf::default() };
15903-
let input_1_prev_tx = Transaction {
15904-
input: vec![], output: vec![input_1_prev_out],
15907+
let prevout = TxOut { value: Amount::from_sat(input_value_sats), script_pubkey: ScriptBuf::default() };
15908+
let prevtx = Transaction {
15909+
input: vec![], output: vec![prevout],
1590515910
version: Version::TWO, lock_time: bitcoin::absolute::LockTime::ZERO,
1590615911
};
15907-
let input_1_txin = TxIn {
15908-
previous_output: bitcoin::OutPoint { txid: input_1_prev_tx.compute_txid(), vout: 0 },
15912+
let txin = TxIn {
15913+
previous_output: bitcoin::OutPoint { txid: prevtx.compute_txid(), vout: 0 },
1590915914
..Default::default()
1591015915
};
15911-
(input_1_txin, input_1_prev_tx, Weight::from_wu(P2WPKH_WITNESS_WEIGHT))
15916+
let witness_weight = Weight::from_wu(P2WPKH_WITNESS_WEIGHT);
15917+
15918+
FundingTxInput { txin, prevtx, witness_weight }
1591215919
}
1591315920

1591415921
#[cfg(splicing)]

lightning/src/ln/channelmanager.rs

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,9 @@ use bitcoin::hashes::{Hash, HashEngine, HmacEngine};
3030

3131
use bitcoin::secp256k1::Secp256k1;
3232
use bitcoin::secp256k1::{PublicKey, SecretKey};
33-
use bitcoin::{secp256k1, Sequence, SignedAmount};
3433
#[cfg(splicing)]
35-
use bitcoin::{ScriptBuf, TxIn, Weight};
34+
use bitcoin::ScriptBuf;
35+
use bitcoin::{secp256k1, Sequence, SignedAmount, TxIn, Weight};
3636

3737
use crate::blinded_path::message::MessageForwardNode;
3838
use crate::blinded_path::message::{AsyncPaymentsContext, OffersContext};
@@ -200,6 +200,22 @@ pub use crate::ln::outbound_payment::{
200200
};
201201
use crate::ln::script::ShutdownScript;
202202

203+
/// An input to contribute to a channel's funding transaction either when using the v2 channel
204+
/// establishment protocol or when splicing.
205+
#[derive(Clone)]
206+
pub struct FundingTxInput {
207+
/// An input for the funding transaction used to cover the channel contributions.
208+
pub txin: TxIn,
209+
210+
/// The transaction containing the unspent [`TxOut`] referenced by [`txin`].
211+
///
212+
/// [`txin`]: Self::txin
213+
pub prevtx: Transaction,
214+
215+
/// The weight of the witness that is needed to spend the [`TxOut`] referenced by [`txin`].
216+
pub witness_weight: Weight,
217+
}
218+
203219
// We hold various information about HTLC relay in the HTLC objects in Channel itself:
204220
//
205221
// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
@@ -4437,7 +4453,7 @@ where
44374453
#[rustfmt::skip]
44384454
pub fn splice_channel(
44394455
&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, our_funding_contribution_satoshis: i64,
4440-
our_funding_inputs: Vec<(TxIn, Transaction, Weight)>, change_script: Option<ScriptBuf>,
4456+
our_funding_inputs: Vec<FundingTxInput>, change_script: Option<ScriptBuf>,
44414457
funding_feerate_per_kw: u32, locktime: Option<u32>,
44424458
) -> Result<(), APIError> {
44434459
let mut res = Ok(());
@@ -4458,9 +4474,8 @@ where
44584474
#[cfg(splicing)]
44594475
fn internal_splice_channel(
44604476
&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey,
4461-
our_funding_contribution_satoshis: i64,
4462-
our_funding_inputs: Vec<(TxIn, Transaction, Weight)>, change_script: Option<ScriptBuf>,
4463-
funding_feerate_per_kw: u32, locktime: Option<u32>,
4477+
our_funding_contribution_satoshis: i64, our_funding_inputs: Vec<FundingTxInput>,
4478+
change_script: Option<ScriptBuf>, funding_feerate_per_kw: u32, locktime: Option<u32>,
44644479
) -> Result<(), APIError> {
44654480
let per_peer_state = self.per_peer_state.read().unwrap();
44664481

lightning/src/ln/dual_funding_tests.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use {
1818
},
1919
crate::ln::channel::PendingV2Channel,
2020
crate::ln::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint, RevocationBasepoint},
21+
crate::ln::channelmanager::FundingTxInput,
2122
crate::ln::functional_test_utils::*,
2223
crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, MessageSendEvent},
2324
crate::ln::msgs::{CommitmentSigned, TxAddInput, TxAddOutput, TxComplete, TxSignatures},
@@ -82,12 +83,13 @@ fn do_test_v2_channel_establishment(session: V2ChannelEstablishmentTestSession)
8283
&RevocationBasepoint::from(open_channel_v2_msg.common_fields.revocation_basepoint),
8384
);
8485

86+
let FundingTxInput { txin, prevtx, .. } = &initiator_funding_inputs[0];
8587
let tx_add_input_msg = TxAddInput {
8688
channel_id,
8789
serial_id: 2, // Even serial_id from initiator.
88-
prevtx: Some(initiator_funding_inputs[0].1.clone()),
90+
prevtx: Some(prevtx.clone()),
8991
prevtx_out: 0,
90-
sequence: initiator_funding_inputs[0].0.sequence.0,
92+
sequence: txin.sequence.0,
9193
shared_input_txid: None,
9294
};
9395
let input_value = tx_add_input_msg.prevtx.as_ref().unwrap().output

lightning/src/ln/functional_test_utils.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ use crate::events::{
2323
};
2424
use crate::ln::chan_utils::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC};
2525
use crate::ln::channelmanager::{
26-
AChannelManager, ChainParameters, ChannelManager, ChannelManagerReadArgs, PaymentId,
27-
RAACommitmentOrder, RecipientOnionFields, MIN_CLTV_EXPIRY_DELTA,
26+
AChannelManager, ChainParameters, ChannelManager, ChannelManagerReadArgs, FundingTxInput,
27+
PaymentId, RAACommitmentOrder, RecipientOnionFields, MIN_CLTV_EXPIRY_DELTA,
2828
};
2929
use crate::ln::msgs;
3030
use crate::ln::msgs::{
@@ -1440,7 +1440,7 @@ fn internal_create_funding_transaction<'a, 'b, 'c>(
14401440
/// Return the inputs (with prev tx), and the total witness weight for these inputs
14411441
pub fn create_dual_funding_utxos_with_prev_txs(
14421442
node: &Node<'_, '_, '_>, utxo_values_in_satoshis: &[u64],
1443-
) -> Vec<(TxIn, Transaction, Weight)> {
1443+
) -> Vec<FundingTxInput> {
14441444
// Ensure we have unique transactions per node by using the locktime.
14451445
let tx = Transaction {
14461446
version: TxVersion::TWO,
@@ -1462,17 +1462,17 @@ pub fn create_dual_funding_utxos_with_prev_txs(
14621462

14631463
let mut inputs = vec![];
14641464
for i in 0..utxo_values_in_satoshis.len() {
1465-
inputs.push((
1466-
TxIn {
1465+
inputs.push(FundingTxInput {
1466+
txin: TxIn {
14671467
previous_output: OutPoint { txid: tx.compute_txid(), index: i as u16 }
14681468
.into_bitcoin_outpoint(),
14691469
script_sig: ScriptBuf::new(),
14701470
sequence: Sequence::ZERO,
14711471
witness: Witness::new(),
14721472
},
1473-
tx.clone(),
1474-
Weight::from_wu(P2WPKH_WITNESS_WEIGHT),
1475-
));
1473+
prevtx: tx.clone(),
1474+
witness_weight: Weight::from_wu(P2WPKH_WITNESS_WEIGHT),
1475+
});
14761476
}
14771477

14781478
inputs

lightning/src/ln/interactivetxs.rs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ use crate::chain::chaininterface::fee_for_weight;
2323
use crate::events::bump_transaction::{BASE_INPUT_WEIGHT, EMPTY_SCRIPT_SIG_WEIGHT};
2424
use crate::ln::chan_utils::FUNDING_TRANSACTION_WITNESS_WEIGHT;
2525
use crate::ln::channel::{FundingNegotiationContext, TOTAL_BITCOIN_SUPPLY_SATOSHIS};
26+
use crate::ln::channelmanager::FundingTxInput;
2627
use crate::ln::msgs;
2728
use crate::ln::msgs::{MessageSendEvent, SerialId, TxSignatures};
2829
use crate::ln::types::ChannelId;
@@ -1884,12 +1885,12 @@ pub(super) fn calculate_change_output_value(
18841885

18851886
let mut total_input_satoshis = 0u64;
18861887
let mut our_funding_inputs_weight = 0u64;
1887-
for (txin, tx, _) in context.our_funding_inputs.iter() {
1888-
let txid = tx.compute_txid();
1888+
for FundingTxInput { txin, prevtx, .. } in context.our_funding_inputs.iter() {
1889+
let txid = prevtx.compute_txid();
18891890
if txin.previous_output.txid != txid {
18901891
return Err(AbortReason::PrevTxOutInvalid);
18911892
}
1892-
let output = tx
1893+
let output = prevtx
18931894
.output
18941895
.get(txin.previous_output.vout as usize)
18951896
.ok_or(AbortReason::PrevTxOutInvalid)?;
@@ -1937,6 +1938,7 @@ pub(super) fn calculate_change_output_value(
19371938
mod tests {
19381939
use crate::chain::chaininterface::{fee_for_weight, FEERATE_FLOOR_SATS_PER_KW};
19391940
use crate::ln::channel::{FundingNegotiationContext, TOTAL_BITCOIN_SUPPLY_SATOSHIS};
1941+
use crate::ln::channelmanager::FundingTxInput;
19401942
use crate::ln::interactivetxs::{
19411943
calculate_change_output_value, generate_holder_serial_id, AbortReason,
19421944
HandleTxCompleteValue, InteractiveTxConstructor, InteractiveTxConstructorArgs,
@@ -2954,23 +2956,23 @@ mod tests {
29542956
let inputs = input_prevouts
29552957
.iter()
29562958
.map(|txout| {
2957-
let tx = Transaction {
2959+
let prevtx = Transaction {
29582960
input: Vec::new(),
29592961
output: vec![(*txout).clone()],
29602962
lock_time: AbsoluteLockTime::ZERO,
29612963
version: Version::TWO,
29622964
};
2963-
let txid = tx.compute_txid();
2965+
let txid = prevtx.compute_txid();
29642966
let txin = TxIn {
29652967
previous_output: OutPoint { txid, vout: 0 },
29662968
script_sig: ScriptBuf::new(),
29672969
sequence: Sequence::ZERO,
29682970
witness: Witness::new(),
29692971
};
2970-
let weight = Weight::ZERO;
2971-
(txin, tx, weight)
2972+
let witness_weight = Weight::ZERO;
2973+
FundingTxInput { txin, prevtx, witness_weight }
29722974
})
2973-
.collect::<Vec<(TxIn, Transaction, Weight)>>();
2975+
.collect();
29742976
let our_contributed = 110_000;
29752977
let txout = TxOut { value: Amount::from_sat(10_000), script_pubkey: ScriptBuf::new() };
29762978
let outputs = vec![txout];

0 commit comments

Comments
 (0)