Skip to content

Commit c9db499

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 bd86078 commit c9db499

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
@@ -53,7 +53,7 @@ use crate::ln::channel_state::{
5353
OutboundHTLCDetails, OutboundHTLCStateDetails,
5454
};
5555
use crate::ln::channelmanager::{
56-
self, FundingConfirmedMessage, HTLCFailureMsg, HTLCSource, OpenChannelMessage,
56+
self, FundingConfirmedMessage, FundingTxInput, HTLCFailureMsg, HTLCSource, OpenChannelMessage,
5757
PaymentClaimDetails, PendingHTLCInfo, PendingHTLCStatus, RAACommitmentOrder, SentHTLCId,
5858
BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA,
5959
};
@@ -5916,10 +5916,11 @@ fn estimate_v2_funding_transaction_fee(
59165916
#[cfg(splicing)]
59175917
#[rustfmt::skip]
59185918
fn check_v2_funding_inputs_sufficient(
5919-
contribution_amount: i64, funding_inputs: &[(TxIn, Transaction, Weight)], is_initiator: bool,
5919+
contribution_amount: i64, funding_inputs: &[FundingTxInput], is_initiator: bool,
59205920
is_splice: bool, funding_feerate_sat_per_1000_weight: u32,
59215921
) -> Result<u64, ChannelError> {
5922-
let mut total_input_witness_weight = Weight::from_wu(funding_inputs.iter().map(|(_, _, w)| w.to_wu()).sum());
5922+
let mut total_input_witness_weight =
5923+
funding_inputs.iter().map(|FundingTxInput { witness_weight, .. }| witness_weight).sum();
59235924
let mut funding_inputs_len = funding_inputs.len();
59245925
if is_initiator && is_splice {
59255926
// consider the weight of the input and witness needed for spending the old funding transaction
@@ -5929,13 +5930,13 @@ fn check_v2_funding_inputs_sufficient(
59295930
let estimated_fee = estimate_v2_funding_transaction_fee(is_initiator, funding_inputs_len, total_input_witness_weight, funding_feerate_sat_per_1000_weight);
59305931

59315932
let mut total_input_sats = 0u64;
5932-
for (idx, input) in funding_inputs.iter().enumerate() {
5933-
if let Some(output) = input.1.output.get(input.0.previous_output.vout as usize) {
5933+
for (idx, FundingTxInput { txin, prevtx, .. }) in funding_inputs.iter().enumerate() {
5934+
if let Some(output) = prevtx.output.get(txin.previous_output.vout as usize) {
59345935
total_input_sats = total_input_sats.saturating_add(output.value.to_sat());
59355936
} else {
59365937
return Err(ChannelError::Warn(format!(
59375938
"Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs[{}]",
5938-
input.1.compute_txid(), input.0.previous_output.vout, idx
5939+
prevtx.compute_txid(), txin.previous_output.vout, idx
59395940
)));
59405941
}
59415942
}
@@ -5979,7 +5980,7 @@ pub(super) struct FundingNegotiationContext {
59795980
pub shared_funding_input: Option<SharedOwnedInput>,
59805981
/// The funding inputs we will be contributing to the channel.
59815982
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
5982-
pub our_funding_inputs: Vec<(TxIn, Transaction, Weight)>,
5983+
pub our_funding_inputs: Vec<FundingTxInput>,
59835984
/// The change output script. This will be used if needed or -- if not set -- generated using
59845985
/// `SignerProvider::get_destination_script`.
59855986
#[allow(dead_code)] // TODO(splicing): Remove once splicing is enabled.
@@ -6051,8 +6052,11 @@ impl FundingNegotiationContext {
60516052
}
60526053
}
60536054

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

60576061
let constructor_args = InteractiveTxConstructorArgs {
60586062
entropy_source,
@@ -10612,9 +10616,8 @@ where
1061210616
/// generated by `SignerProvider::get_destination_script`.
1061310617
#[cfg(splicing)]
1061410618
pub fn splice_channel(
10615-
&mut self, our_funding_contribution_satoshis: i64,
10616-
our_funding_inputs: Vec<(TxIn, Transaction, Weight)>, change_script: Option<ScriptBuf>,
10617-
funding_feerate_per_kw: u32, locktime: u32,
10619+
&mut self, our_funding_contribution_satoshis: i64, our_funding_inputs: Vec<FundingTxInput>,
10620+
change_script: Option<ScriptBuf>, funding_feerate_per_kw: u32, locktime: u32,
1061810621
) -> Result<msgs::SpliceInit, APIError> {
1061910622
// Check if a splice has been initiated already.
1062010623
// Note: only a single outstanding splice is supported (per spec)
@@ -10680,7 +10683,7 @@ where
1068010683
),
1068110684
})?;
1068210685

10683-
for (_, tx, _) in our_funding_inputs.iter() {
10686+
for FundingTxInput { txin, prevtx, .. } in our_funding_inputs.iter() {
1068410687
const MESSAGE_TEMPLATE: msgs::TxAddInput = msgs::TxAddInput {
1068510688
channel_id: ChannelId([0; 32]),
1068610689
serial_id: 0,
@@ -10689,7 +10692,7 @@ where
1068910692
sequence: 0,
1069010693
shared_input_txid: None,
1069110694
};
10692-
let message_len = MESSAGE_TEMPLATE.serialized_length() + tx.serialized_length();
10695+
let message_len = MESSAGE_TEMPLATE.serialized_length() + prevtx.serialized_length();
1069310696
if message_len > LN_MAX_MSG_LEN {
1069410697
return Err(APIError::APIMisuseError {
1069510698
err: format!(
@@ -12474,7 +12477,7 @@ where
1247412477
pub fn new_outbound<ES: Deref, F: Deref, L: Deref>(
1247512478
fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
1247612479
counterparty_node_id: PublicKey, their_features: &InitFeatures, funding_satoshis: u64,
12477-
funding_inputs: Vec<(TxIn, Transaction, Weight)>, user_id: u128, config: &UserConfig,
12480+
funding_inputs: Vec<FundingTxInput>, user_id: u128, config: &UserConfig,
1247812481
current_chain_height: u32, outbound_scid_alias: u64, funding_confirmation_target: ConfirmationTarget,
1247912482
logger: L,
1248012483
) -> Result<Self, APIError>
@@ -12688,8 +12691,10 @@ where
1268812691
value: Amount::from_sat(funding.get_value_satoshis()),
1268912692
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
1269012693
};
12691-
let inputs_to_contribute =
12692-
our_funding_inputs.into_iter().map(|(txin, tx, _)| (txin, tx)).collect();
12694+
let inputs_to_contribute = our_funding_inputs
12695+
.into_iter()
12696+
.map(|FundingTxInput { txin, prevtx, .. }| (txin, prevtx))
12697+
.collect();
1269312698

1269412699
let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
1269512700
InteractiveTxConstructorArgs {
@@ -14125,7 +14130,7 @@ mod tests {
1412514130
TOTAL_BITCOIN_SUPPLY_SATOSHIS,
1412614131
};
1412714132
use crate::ln::channel_keys::{RevocationBasepoint, RevocationKey};
14128-
use crate::ln::channelmanager::{self, HTLCSource, PaymentId};
14133+
use crate::ln::channelmanager::{self, FundingTxInput, HTLCSource, PaymentId};
1412914134
use crate::ln::msgs;
1413014135
use crate::ln::msgs::{ChannelUpdate, UnsignedChannelUpdate, MAX_VALUE_MSAT};
1413114136
use crate::ln::onion_utils::{AttributionData, LocalHTLCFailureReason};
@@ -15898,19 +15903,21 @@ mod tests {
1589815903

1589915904
#[cfg(splicing)]
1590015905
#[rustfmt::skip]
15901-
fn funding_input_sats(input_value_sats: u64) -> (TxIn, Transaction, Weight) {
15906+
fn funding_input_sats(input_value_sats: u64) -> FundingTxInput {
1590215907
use crate::sign::P2WPKH_WITNESS_WEIGHT;
1590315908

15904-
let input_1_prev_out = TxOut { value: Amount::from_sat(input_value_sats), script_pubkey: ScriptBuf::default() };
15905-
let input_1_prev_tx = Transaction {
15906-
input: vec![], output: vec![input_1_prev_out],
15909+
let prevout = TxOut { value: Amount::from_sat(input_value_sats), script_pubkey: ScriptBuf::default() };
15910+
let prevtx = Transaction {
15911+
input: vec![], output: vec![prevout],
1590715912
version: Version::TWO, lock_time: bitcoin::absolute::LockTime::ZERO,
1590815913
};
15909-
let input_1_txin = TxIn {
15910-
previous_output: bitcoin::OutPoint { txid: input_1_prev_tx.compute_txid(), vout: 0 },
15914+
let txin = TxIn {
15915+
previous_output: bitcoin::OutPoint { txid: prevtx.compute_txid(), vout: 0 },
1591115916
..Default::default()
1591215917
};
15913-
(input_1_txin, input_1_prev_tx, Weight::from_wu(P2WPKH_WITNESS_WEIGHT))
15918+
let witness_weight = Weight::from_wu(P2WPKH_WITNESS_WEIGHT);
15919+
15920+
FundingTxInput { txin, prevtx, witness_weight }
1591415921
}
1591515922

1591615923
#[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)