Skip to content

Commit c3354b7

Browse files
committed
Clean up calculate_our_funding_satoshis()
1 parent 0b28784 commit c3354b7

File tree

3 files changed

+29
-119
lines changed

3 files changed

+29
-119
lines changed

lightning/src/ln/channel.rs

+14-91
Original file line numberDiff line numberDiff line change
@@ -4472,7 +4472,7 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
44724472
/// Estimate our part of the fee of the new funding transaction.
44734473
/// input_count: Number of contributed inputs.
44744474
/// witness_weight: The witness weight for contributed inputs.
4475-
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
4475+
#[allow(dead_code)] // TODO(dual_funding): TODO(splicing): Remove allow once used.
44764476
fn estimate_v2_funding_transaction_fee(
44774477
is_initiator: bool, input_count: usize, witness_weight: Weight,
44784478
funding_feerate_sat_per_1000_weight: u32,
@@ -4498,33 +4498,6 @@ fn estimate_v2_funding_transaction_fee(
44984498
fee_for_weight(funding_feerate_sat_per_1000_weight, weight)
44994499
}
45004500

4501-
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
4502-
pub(super) fn calculate_our_funding_satoshis(
4503-
is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
4504-
total_witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32,
4505-
holder_dust_limit_satoshis: u64,
4506-
) -> Result<u64, APIError> {
4507-
let estimated_fee = estimate_v2_funding_transaction_fee(is_initiator, funding_inputs.len(), total_witness_weight, funding_feerate_sat_per_1000_weight);
4508-
4509-
let mut total_input_satoshis = 0u64;
4510-
for (idx, input) in funding_inputs.iter().enumerate() {
4511-
if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
4512-
total_input_satoshis = total_input_satoshis.saturating_add(output.value.to_sat());
4513-
} else {
4514-
return Err(APIError::APIMisuseError {
4515-
err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs[{}]",
4516-
input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
4517-
}
4518-
}
4519-
4520-
let funding_satoshis = total_input_satoshis.saturating_sub(estimated_fee);
4521-
if funding_satoshis < holder_dust_limit_satoshis {
4522-
Ok(0)
4523-
} else {
4524-
Ok(funding_satoshis)
4525-
}
4526-
}
4527-
45284501
/// Context for dual-funded channels.
45294502
pub(super) struct DualFundingChannelContext {
45304503
/// The amount in satoshis we will be contributing to the channel.
@@ -9262,27 +9235,23 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
92629235

92639236
/// Creates a new dual-funded channel from a remote side's request for one.
92649237
/// Assumes chain_hash has already been checked and corresponds with what we expect!
9238+
/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
92659239
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
92669240
pub fn new_inbound<ES: Deref, F: Deref, L: Deref>(
92679241
fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
92689242
holder_node_id: PublicKey, counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures,
92699243
their_features: &InitFeatures, msg: &msgs::OpenChannelV2,
9270-
funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>, total_witness_weight: Weight,
92719244
user_id: u128, config: &UserConfig, current_chain_height: u32, logger: &L,
92729245
) -> Result<Self, ChannelError>
92739246
where ES::Target: EntropySource,
92749247
F::Target: FeeEstimator,
92759248
L::Target: Logger,
92769249
{
9277-
let funding_satoshis = calculate_our_funding_satoshis(
9278-
false, &funding_inputs, total_witness_weight, msg.funding_feerate_sat_per_1000_weight,
9279-
msg.common_fields.dust_limit_satoshis
9280-
).map_err(|_| ChannelError::Close(
9281-
(
9282-
"Failed to accept channel".to_string(),
9283-
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
9284-
)))?;
9285-
let channel_value_satoshis = funding_satoshis.saturating_add(msg.common_fields.funding_satoshis);
9250+
// TODO(dual_funding): Take these as input once supported
9251+
let our_funding_satoshis = 0u64;
9252+
let our_funding_inputs = Vec::new();
9253+
9254+
let channel_value_satoshis = our_funding_satoshis.saturating_add(msg.common_fields.funding_satoshis);
92869255
let counterparty_selected_channel_reserve_satoshis = get_v2_channel_reserve_satoshis(
92879256
channel_value_satoshis, msg.common_fields.dust_limit_satoshis);
92889257
let holder_selected_channel_reserve_satoshis = get_v2_channel_reserve_satoshis(
@@ -9316,7 +9285,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
93169285
logger,
93179286
false,
93189287

9319-
funding_satoshis,
9288+
our_funding_satoshis,
93209289

93219290
counterparty_pubkeys,
93229291
channel_type,
@@ -9331,10 +9300,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
93319300
context.channel_id = channel_id;
93329301

93339302
let dual_funding_context = DualFundingChannelContext {
9334-
our_funding_satoshis: funding_satoshis,
9303+
our_funding_satoshis: our_funding_satoshis,
93359304
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
93369305
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
9337-
our_funding_inputs: funding_inputs.clone(),
9306+
our_funding_inputs: our_funding_inputs.clone(),
93389307
};
93399308

93409309
let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
@@ -9346,7 +9315,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
93469315
feerate_sat_per_kw: dual_funding_context.funding_feerate_sat_per_1000_weight,
93479316
funding_tx_locktime: dual_funding_context.funding_tx_locktime,
93489317
is_initiator: false,
9349-
inputs_to_contribute: funding_inputs,
9318+
inputs_to_contribute: our_funding_inputs,
93509319
outputs_to_contribute: Vec::new(),
93519320
expected_remote_shared_funding_output: Some((context.get_funding_redeemscript().to_p2wsh(), context.channel_value_satoshis)),
93529321
}
@@ -10479,7 +10448,7 @@ mod tests {
1047910448
use bitcoin::amount::Amount;
1048010449
use bitcoin::constants::ChainHash;
1048110450
use bitcoin::script::{ScriptBuf, Builder};
10482-
use bitcoin::transaction::{Transaction, TxIn, TxOut, Version};
10451+
use bitcoin::transaction::{Transaction, TxOut, Version};
1048310452
use bitcoin::opcodes;
1048410453
use bitcoin::network::Network;
1048510454
use crate::ln::onion_utils::INVALID_ONION_BLINDING;
@@ -10501,7 +10470,7 @@ mod tests {
1050110470
use crate::routing::router::{Path, RouteHop};
1050210471
use crate::util::config::UserConfig;
1050310472
use crate::util::errors::APIError;
10504-
use crate::util::ser::{ReadableArgs, TransactionU16LenLimited, Writeable};
10473+
use crate::util::ser::{ReadableArgs, Writeable};
1050510474
use crate::util::test_utils;
1050610475
use crate::util::test_utils::{OnGetShutdownScriptpubkey, TestKeysInterface};
1050710476
use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
@@ -12253,7 +12222,7 @@ mod tests {
1225312222
}
1225412223

1225512224
#[test]
12256-
fn test_estimate_v2_funding_transaction_fee() {
12225+
fn test_estimate_v2_unding_transaction_fee() {
1225712226
use crate::ln::channel::estimate_v2_funding_transaction_fee;
1225812227
use bitcoin::Weight;
1225912228

@@ -12287,50 +12256,4 @@ mod tests {
1228712256
320
1228812257
);
1228912258
}
12290-
12291-
fn funding_input_sats(input_value_sats: u64) -> (TxIn, TransactionU16LenLimited) {
12292-
let input_1_prev_out = TxOut { value: Amount::from_sat(input_value_sats), script_pubkey: ScriptBuf::default() };
12293-
let input_1_prev_tx = Transaction {
12294-
input: vec![], output: vec![input_1_prev_out],
12295-
version: Version::TWO, lock_time: bitcoin::absolute::LockTime::ZERO,
12296-
};
12297-
let input_1_txin = TxIn {
12298-
previous_output: bitcoin::OutPoint { txid: input_1_prev_tx.compute_txid(), vout: 0 },
12299-
..Default::default()
12300-
};
12301-
(input_1_txin, TransactionU16LenLimited::new(input_1_prev_tx).unwrap())
12302-
}
12303-
12304-
#[test]
12305-
fn test_calculate_our_funding_satoshis() {
12306-
use crate::ln::channel::calculate_our_funding_satoshis;
12307-
use bitcoin::Weight;
12308-
12309-
// normal use case, output is less than the available inputs
12310-
assert_eq!(
12311-
calculate_our_funding_satoshis(
12312-
true,
12313-
&[
12314-
funding_input_sats(200_000),
12315-
funding_input_sats(100_000),
12316-
],
12317-
Weight::from_wu(300),
12318-
2000,
12319-
1000,
12320-
).unwrap(),
12321-
298332
12322-
);
12323-
12324-
// below dust limit
12325-
assert_eq!(
12326-
calculate_our_funding_satoshis(
12327-
true,
12328-
&[funding_input_sats(20_000)],
12329-
Weight::from_wu(300),
12330-
2000,
12331-
20_000,
12332-
).unwrap(),
12333-
0
12334-
);
12335-
}
1233612259
}

lightning/src/ln/channelmanager.rs

+8-9
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
//! imply it needs to fail HTLCs/payments/channels it manages).
1919

2020
use bitcoin::block::Header;
21-
use bitcoin::transaction::{Transaction, TxIn};
21+
use bitcoin::transaction::Transaction;
2222
use bitcoin::constants::ChainHash;
2323
use bitcoin::key::constants::SECRET_KEY_SIZE;
2424
use bitcoin::network::Network;
@@ -30,7 +30,7 @@ use bitcoin::hash_types::{BlockHash, Txid};
3030

3131
use bitcoin::secp256k1::{SecretKey,PublicKey};
3232
use bitcoin::secp256k1::Secp256k1;
33-
use bitcoin::{secp256k1, Sequence, Weight};
33+
use bitcoin::{secp256k1, Sequence};
3434

3535
use crate::events::FundingInfo;
3636
use crate::blinded_path::message::{AsyncPaymentsContext, MessageContext, OffersContext};
@@ -83,7 +83,6 @@ use crate::util::wakers::{Future, Notifier};
8383
use crate::util::scid_utils::fake_scid;
8484
use crate::util::string::UntrustedString;
8585
use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
86-
use crate::util::ser::TransactionU16LenLimited;
8786
use crate::util::logger::{Level, Logger, WithContext};
8887
use crate::util::errors::APIError;
8988
#[cfg(async_payments)] use {
@@ -7647,7 +7646,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
76477646
/// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
76487647
/// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
76497648
pub fn accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
7650-
self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id, vec![], Weight::from_wu(0))
7649+
self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
76517650
}
76527651

76537652
/// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
@@ -7669,13 +7668,13 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
76697668
/// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
76707669
/// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
76717670
pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
7672-
self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id, vec![], Weight::from_wu(0))
7671+
self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
76737672
}
76747673

7674+
/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
76757675
fn do_accept_inbound_channel(
76767676
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool,
7677-
user_channel_id: u128, _funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
7678-
_total_witness_weight: Weight,
7677+
user_channel_id: u128,
76797678
) -> Result<(), APIError> {
76807679
let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(*temporary_channel_id), None);
76817680
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
@@ -7725,7 +7724,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
77257724
&self.fee_estimator, &self.entropy_source, &self.signer_provider,
77267725
self.get_our_node_id(), *counterparty_node_id,
77277726
&self.channel_type_features(), &peer_state.latest_features,
7728-
&open_channel_msg, _funding_inputs, _total_witness_weight,
7727+
&open_channel_msg,
77297728
user_channel_id, &self.default_configuration, best_block_height,
77307729
&self.logger,
77317730
).map_err(|_| MsgHandleErrInternal::from_chan_no_close(
@@ -8011,7 +8010,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
80118010
let channel = PendingV2Channel::new_inbound(
80128011
&self.fee_estimator, &self.entropy_source, &self.signer_provider,
80138012
self.get_our_node_id(), *counterparty_node_id, &self.channel_type_features(),
8014-
&peer_state.latest_features, msg, vec![], Weight::from_wu(0), user_channel_id,
8013+
&peer_state.latest_features, msg, user_channel_id,
80158014
&self.default_configuration, best_block_height, &self.logger,
80168015
).map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.common_fields.temporary_channel_id))?;
80178016
let message_send_event = events::MessageSendEvent::SendAcceptChannelV2 {

lightning/src/ln/dual_funding_tests.rs

+7-19
Original file line numberDiff line numberDiff line change
@@ -11,30 +11,28 @@
1111
1212
#[cfg(dual_funding)]
1313
use {
14-
crate::chain::chaininterface::{ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator},
14+
crate::chain::chaininterface::{ConfirmationTarget, LowerBoundedFeeEstimator},
1515
crate::events::{Event, MessageSendEvent, MessageSendEventsProvider},
1616
crate::ln::chan_utils::{
1717
make_funding_redeemscript, ChannelPublicKeys, ChannelTransactionParameters,
1818
CounterpartyChannelTransactionParameters,
1919
},
20-
crate::ln::channel::{
21-
calculate_our_funding_satoshis, PendingV2Channel, MIN_CHAN_DUST_LIMIT_SATOSHIS,
22-
},
20+
crate::ln::channel::PendingV2Channel,
2321
crate::ln::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint, RevocationBasepoint},
2422
crate::ln::functional_test_utils::*,
2523
crate::ln::msgs::ChannelMessageHandler,
2624
crate::ln::msgs::{CommitmentSigned, TxAddInput, TxAddOutput, TxComplete},
2725
crate::ln::types::ChannelId,
2826
crate::prelude::*,
29-
crate::sign::{ChannelSigner as _, P2WPKH_WITNESS_WEIGHT},
27+
crate::sign::ChannelSigner as _,
3028
crate::util::ser::TransactionU16LenLimited,
3129
crate::util::test_utils,
32-
bitcoin::Weight,
3330
};
3431

3532
#[cfg(dual_funding)]
3633
// Dual-funding: V2 Channel Establishment Tests
3734
struct V2ChannelEstablishmentTestSession {
35+
funding_input_sats: u64,
3836
initiator_input_value_satoshis: u64,
3937
}
4038

@@ -60,17 +58,7 @@ fn do_test_v2_channel_establishment(
6058
.collect();
6159

6260
// Alice creates a dual-funded channel as initiator.
63-
let funding_feerate = node_cfgs[0]
64-
.fee_estimator
65-
.get_est_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
66-
let funding_satoshis = calculate_our_funding_satoshis(
67-
true,
68-
&initiator_funding_inputs[..],
69-
Weight::from_wu(P2WPKH_WITNESS_WEIGHT),
70-
funding_feerate,
71-
MIN_CHAN_DUST_LIMIT_SATOSHIS,
72-
)
73-
.unwrap();
61+
let funding_satoshis = session.funding_input_sats;
7462
let mut channel = PendingV2Channel::new_outbound(
7563
&LowerBoundedFeeEstimator(node_cfgs[0].fee_estimator),
7664
&nodes[0].node.entropy_source,
@@ -260,12 +248,12 @@ fn do_test_v2_channel_establishment(
260248
fn test_v2_channel_establishment() {
261249
// Only initiator contributes, no persist pending
262250
do_test_v2_channel_establishment(
263-
V2ChannelEstablishmentTestSession { initiator_input_value_satoshis: 100_000 },
251+
V2ChannelEstablishmentTestSession { funding_input_sats: 100_000, initiator_input_value_satoshis: 150_000 },
264252
false,
265253
);
266254
// Only initiator contributes, persist pending
267255
do_test_v2_channel_establishment(
268-
V2ChannelEstablishmentTestSession { initiator_input_value_satoshis: 100_000 },
256+
V2ChannelEstablishmentTestSession { funding_input_sats: 100_000, initiator_input_value_satoshis: 150_000 },
269257
true,
270258
);
271259
}

0 commit comments

Comments
 (0)