Skip to content

Commit 5681e6a

Browse files
author
Antoine Riard
committed
Remove InputDescriptors by named constants
1 parent 75fbc59 commit 5681e6a

File tree

2 files changed

+45
-118
lines changed

2 files changed

+45
-118
lines changed

lightning/src/chain/channelmonitor.rs

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
4343
use chain::transaction::{OutPoint, TransactionData};
4444
use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface};
4545
use chain::onchaintx::OnchainTxHandler;
46-
use chain::onchain_utils::{CounterpartyHTLCOutput, HolderFundingOutput, HolderHTLCOutput, InputDescriptors, PackageMalleability, PackageSolvingData, PackageTemplate, RevokedOutput};
46+
use chain::onchain_utils::{CounterpartyHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageMalleability, PackageSolvingData, PackageTemplate, RevokedOutput, WEIGHT_REVOKED_OUTPUT, WEIGHT_REVOKED_RECEIVED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC};
4747
use chain::Filter;
4848
use util::logger::Logger;
4949
use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48};
@@ -1581,7 +1581,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
15811581
// First, process non-htlc outputs (to_holder & to_counterparty)
15821582
for (idx, outp) in tx.output.iter().enumerate() {
15831583
if outp.script_pubkey == revokeable_p2wsh {
1584-
let revk_outp = RevokedOutput::build(per_commitment_point, per_commitment_key, self.counterparty_tx_cache.counterparty_delayed_payment_base_key, self.counterparty_tx_cache.counterparty_htlc_base_key, InputDescriptors::RevokedOutput, outp.value, None, self.counterparty_tx_cache.on_counterparty_tx_csv);
1584+
let revk_outp = RevokedOutput::build(per_commitment_point, per_commitment_key, self.counterparty_tx_cache.counterparty_delayed_payment_base_key, self.counterparty_tx_cache.counterparty_htlc_base_key, WEIGHT_REVOKED_OUTPUT, outp.value, None, self.counterparty_tx_cache.on_counterparty_tx_csv);
15851585
let justice_package = PackageTemplate::build_package(commitment_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp), PackageMalleability::Malleable, height + self.counterparty_tx_cache.on_counterparty_tx_csv as u32, true, 0, None, height);
15861586
claimable_outpoints.push(justice_package);
15871587
}
@@ -1595,7 +1595,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
15951595
tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
15961596
return (claimable_outpoints, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
15971597
}
1598-
let revk_outp = RevokedOutput::build(per_commitment_point, per_commitment_key, self.counterparty_tx_cache.counterparty_delayed_payment_base_key, self.counterparty_tx_cache.counterparty_htlc_base_key, if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC }, htlc.amount_msat / 1000, Some(htlc.clone()), self.counterparty_tx_cache.on_counterparty_tx_csv);
1598+
let revk_outp = RevokedOutput::build(per_commitment_point, per_commitment_key, self.counterparty_tx_cache.counterparty_delayed_payment_base_key, self.counterparty_tx_cache.counterparty_htlc_base_key, if htlc.offered { WEIGHT_REVOKED_OFFERED_HTLC } else { WEIGHT_REVOKED_RECEIVED_HTLC }, htlc.amount_msat / 1000, Some(htlc.clone()), self.counterparty_tx_cache.on_counterparty_tx_csv);
15991599
let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedOutput(revk_outp), PackageMalleability::Malleable, htlc.cltv_expiry, true, 0, None, height);
16001600
claimable_outpoints.push(justice_package);
16011601
}
@@ -1777,7 +1777,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
17771777
let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
17781778

17791779
log_trace!(logger, "Counterparty HTLC broadcast {}:{}", htlc_txid, 0);
1780-
let revk_outp = RevokedOutput::build(per_commitment_point, per_commitment_key, self.counterparty_tx_cache.counterparty_delayed_payment_base_key, self.counterparty_tx_cache.counterparty_htlc_base_key, InputDescriptors::RevokedOutput, tx.output[0].value, None, self.counterparty_tx_cache.on_counterparty_tx_csv);
1780+
let revk_outp = RevokedOutput::build(per_commitment_point, per_commitment_key, self.counterparty_tx_cache.counterparty_delayed_payment_base_key, self.counterparty_tx_cache.counterparty_htlc_base_key, WEIGHT_REVOKED_OUTPUT, tx.output[0].value, None, self.counterparty_tx_cache.on_counterparty_tx_csv);
17811781
let justice_package = PackageTemplate::build_package(htlc_txid, 0, PackageSolvingData::RevokedOutput(revk_outp), PackageMalleability::Malleable, height + self.counterparty_tx_cache.on_counterparty_tx_csv as u32, true, 0, None, height);
17821782
let claimable_outpoints = vec!(justice_package);
17831783
let outputs = vec![(0, tx.output[0].clone())];
@@ -2889,8 +2889,7 @@ mod tests {
28892889
use bitcoin::network::constants::Network;
28902890
use hex;
28912891
use chain::channelmonitor::ChannelMonitor;
2892-
use chain::onchain_utils;
2893-
use chain::onchain_utils::InputDescriptors;
2892+
use chain::onchain_utils::{WEIGHT_OFFERED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_RECEIVED_HTLC, WEIGHT_REVOKED_OUTPUT};
28942893
use chain::transaction::OutPoint;
28952894
use ln::channelmanager::{BestBlock, PaymentPreimage, PaymentHash};
28962895
use ln::chan_utils;
@@ -3048,25 +3047,25 @@ mod tests {
30483047
let mut sum_actual_sigs = 0;
30493048

30503049
macro_rules! sign_input {
3051-
($sighash_parts: expr, $idx: expr, $amount: expr, $input_type: expr, $sum_actual_sigs: expr) => {
3050+
($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr) => {
30523051
let htlc = HTLCOutputInCommitment {
3053-
offered: if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::OfferedHTLC { true } else { false },
3052+
offered: if *$weight == WEIGHT_REVOKED_OFFERED_HTLC || *$weight == WEIGHT_OFFERED_HTLC { true } else { false },
30543053
amount_msat: 0,
30553054
cltv_expiry: 2 << 16,
30563055
payment_hash: PaymentHash([1; 32]),
30573056
transaction_output_index: Some($idx as u32),
30583057
};
3059-
let redeem_script = if *$input_type == InputDescriptors::RevokedOutput { chan_utils::get_revokeable_redeemscript(&pubkey, 256, &pubkey) } else { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &pubkey, &pubkey, &pubkey) };
3058+
let redeem_script = if *$weight == WEIGHT_REVOKED_OUTPUT { chan_utils::get_revokeable_redeemscript(&pubkey, 256, &pubkey) } else { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &pubkey, &pubkey, &pubkey) };
30603059
let sighash = hash_to_message!(&$sighash_parts.signature_hash($idx, &redeem_script, $amount, SigHashType::All)[..]);
30613060
let sig = secp_ctx.sign(&sighash, &privkey);
30623061
$sighash_parts.access_witness($idx).push(sig.serialize_der().to_vec());
30633062
$sighash_parts.access_witness($idx)[0].push(SigHashType::All as u8);
30643063
sum_actual_sigs += $sighash_parts.access_witness($idx)[0].len();
3065-
if *$input_type == InputDescriptors::RevokedOutput {
3064+
if *$weight == WEIGHT_REVOKED_OUTPUT {
30663065
$sighash_parts.access_witness($idx).push(vec!(1));
3067-
} else if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::RevokedReceivedHTLC {
3066+
} else if *$weight == WEIGHT_REVOKED_OFFERED_HTLC || *$weight == WEIGHT_REVOKED_RECEIVED_HTLC {
30683067
$sighash_parts.access_witness($idx).push(pubkey.clone().serialize().to_vec());
3069-
} else if *$input_type == InputDescriptors::ReceivedHTLC {
3068+
} else if *$weight == WEIGHT_RECEIVED_HTLC {
30703069
$sighash_parts.access_witness($idx).push(vec![0]);
30713070
} else {
30723071
$sighash_parts.access_witness($idx).push(PaymentPreimage([1; 32]).0.to_vec());
@@ -3099,14 +3098,16 @@ mod tests {
30993098
value: 0,
31003099
});
31013100
let base_weight = claim_tx.get_weight();
3102-
let inputs_des = vec![InputDescriptors::RevokedOutput, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedReceivedHTLC];
3101+
let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_RECEIVED_HTLC];
3102+
let mut inputs_total_weight = 2; // count segwit flags
31033103
{
31043104
let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3105-
for (idx, inp) in inputs_des.iter().enumerate() {
3105+
for (idx, inp) in inputs_weight.iter().enumerate() {
31063106
sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3107+
inputs_total_weight += inp;
31073108
}
31083109
}
3109-
assert_eq!(base_weight + onchain_utils::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
3110+
assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
31103111

31113112
// Claim tx with 1 offered HTLCs, 3 received HTLCs
31123113
claim_tx.input.clear();
@@ -3123,14 +3124,16 @@ mod tests {
31233124
});
31243125
}
31253126
let base_weight = claim_tx.get_weight();
3126-
let inputs_des = vec![InputDescriptors::OfferedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC];
3127+
let inputs_weight = vec![WEIGHT_OFFERED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_RECEIVED_HTLC];
3128+
let mut inputs_total_weight = 2; // count segwit flags
31273129
{
31283130
let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3129-
for (idx, inp) in inputs_des.iter().enumerate() {
3131+
for (idx, inp) in inputs_weight.iter().enumerate() {
31303132
sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3133+
inputs_total_weight += inp;
31313134
}
31323135
}
3133-
assert_eq!(base_weight + onchain_utils::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
3136+
assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
31343137

31353138
// Justice tx with 1 revoked HTLC-Success tx output
31363139
claim_tx.input.clear();
@@ -3145,14 +3148,16 @@ mod tests {
31453148
witness: Vec::new(),
31463149
});
31473150
let base_weight = claim_tx.get_weight();
3148-
let inputs_des = vec![InputDescriptors::RevokedOutput];
3151+
let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
3152+
let mut inputs_total_weight = 2; // count segwit flags
31493153
{
31503154
let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3151-
for (idx, inp) in inputs_des.iter().enumerate() {
3155+
for (idx, inp) in inputs_weight.iter().enumerate() {
31523156
sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3157+
inputs_total_weight += inp;
31533158
}
31543159
}
3155-
assert_eq!(base_weight + onchain_utils::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
3160+
assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_weight.len() - sum_actual_sigs));
31563161
}
31573162

31583163
// Further testing is done in the ChannelManager integration tests.

lightning/src/chain/onchain_utils.rs

Lines changed: 19 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -36,94 +36,16 @@ use std::ops::Deref;
3636
const MAX_ALLOC_SIZE: usize = 64*1024;
3737

3838

39-
/// witnessScript markers used to compute the expected witness weight.
40-
#[derive(PartialEq, Clone, Copy)]
41-
pub(crate) enum InputDescriptors {
42-
RevokedOfferedHTLC,
43-
RevokedReceivedHTLC,
44-
OfferedHTLC,
45-
ReceivedHTLC,
46-
RevokedOutput, // either a revoked to_holder output on commitment tx, a revoked HTLC-Timeout output or a revoked HTLC-Success output
47-
}
48-
49-
impl Writeable for InputDescriptors {
50-
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
51-
match self {
52-
&InputDescriptors::RevokedOfferedHTLC => {
53-
writer.write_all(&[0; 1])?;
54-
},
55-
&InputDescriptors::RevokedReceivedHTLC => {
56-
writer.write_all(&[1; 1])?;
57-
},
58-
&InputDescriptors::OfferedHTLC => {
59-
writer.write_all(&[2; 1])?;
60-
},
61-
&InputDescriptors::ReceivedHTLC => {
62-
writer.write_all(&[3; 1])?;
63-
}
64-
&InputDescriptors::RevokedOutput => {
65-
writer.write_all(&[4; 1])?;
66-
}
67-
}
68-
Ok(())
69-
}
70-
}
71-
72-
impl Readable for InputDescriptors {
73-
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
74-
let input_descriptor = match <u8 as Readable>::read(reader)? {
75-
0 => {
76-
InputDescriptors::RevokedOfferedHTLC
77-
},
78-
1 => {
79-
InputDescriptors::RevokedReceivedHTLC
80-
},
81-
2 => {
82-
InputDescriptors::OfferedHTLC
83-
},
84-
3 => {
85-
InputDescriptors::ReceivedHTLC
86-
},
87-
4 => {
88-
InputDescriptors::RevokedOutput
89-
}
90-
_ => return Err(DecodeError::InvalidValue),
91-
};
92-
Ok(input_descriptor)
93-
}
94-
}
95-
96-
/// Sum up witnesses weight of a set of given inputs. Inputs might belong to differing descriptors.
97-
/// Weights should be compliant with BOLT 3 Appendix A.
98-
pub(crate) fn get_witnesses_weight(inputs: &[InputDescriptors]) -> usize {
99-
let mut tx_weight = 2; // count segwit flags
100-
for inp in inputs {
101-
// We use expected weight (and not actual) as signatures and time lock delays may vary
102-
tx_weight += match inp {
103-
// number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
104-
&InputDescriptors::RevokedOfferedHTLC => {
105-
1 + 1 + 73 + 1 + 33 + 1 + 133
106-
},
107-
// number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
108-
&InputDescriptors::RevokedReceivedHTLC => {
109-
1 + 1 + 73 + 1 + 33 + 1 + 139
110-
},
111-
// number_of_witness_elements + sig_length + counterpartyhtlc_sig + preimage_length + preimage + witness_script_length + witness_script
112-
&InputDescriptors::OfferedHTLC => {
113-
1 + 1 + 73 + 1 + 32 + 1 + 133
114-
},
115-
// number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
116-
&InputDescriptors::ReceivedHTLC => {
117-
1 + 1 + 73 + 1 + 1 + 1 + 139
118-
},
119-
// number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
120-
&InputDescriptors::RevokedOutput => {
121-
1 + 1 + 73 + 1 + 1 + 1 + 77
122-
},
123-
};
124-
}
125-
tx_weight
126-
}
39+
// number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
40+
pub(crate) const WEIGHT_REVOKED_OFFERED_HTLC: u64 = 1 + 1 + 73 + 1 + 33 + 1 + 133;
41+
// number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
42+
pub(crate) const WEIGHT_REVOKED_RECEIVED_HTLC: u64 = 1 + 1 + 73 + 1 + 33 + 1 + 139;
43+
// number_of_witness_elements + sig_length + counterpartyhtlc_sig + preimage_length + preimage + witness_script_length + witness_script
44+
pub(crate) const WEIGHT_OFFERED_HTLC: u64 = 1 + 1 + 73 + 1 + 32 + 1 + 133;
45+
// number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
46+
pub(crate) const WEIGHT_RECEIVED_HTLC: u64 = 1 + 1 + 73 + 1 + 1 + 1 + 139;
47+
// number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
48+
pub(crate) const WEIGHT_REVOKED_OUTPUT: u64 = 1 + 1 + 73 + 1 + 1 + 1 + 77;
12749

12850
/// A struct to describe a revoked output and corresponding informations to generate a solving
12951
/// witness.
@@ -141,20 +63,20 @@ pub(crate) struct RevokedOutput {
14163
counterparty_delayed_payment_base_key: PublicKey,
14264
counterparty_htlc_base_key: PublicKey,
14365
per_commitment_key: SecretKey,
144-
input_descriptor: InputDescriptors,
66+
weight: u64,
14567
amount: u64,
14668
htlc: Option<HTLCOutputInCommitment>,
14769
on_counterparty_tx_csv: u16,
14870
}
14971

15072
impl RevokedOutput {
151-
pub(crate) fn build(per_commitment_point: PublicKey, per_commitment_key: SecretKey, counterparty_delayed_payment_base_key: PublicKey, counterparty_htlc_base_key: PublicKey, input_descriptor: InputDescriptors, amount: u64, htlc: Option<HTLCOutputInCommitment>, on_counterparty_tx_csv: u16) -> Self {
73+
pub(crate) fn build(per_commitment_point: PublicKey, per_commitment_key: SecretKey, counterparty_delayed_payment_base_key: PublicKey, counterparty_htlc_base_key: PublicKey, weight: u64, amount: u64, htlc: Option<HTLCOutputInCommitment>, on_counterparty_tx_csv: u16) -> Self {
15274
RevokedOutput {
15375
per_commitment_point,
15476
counterparty_delayed_payment_base_key,
15577
counterparty_htlc_base_key,
15678
per_commitment_key,
157-
input_descriptor,
79+
weight,
15880
amount,
15981
htlc,
16082
on_counterparty_tx_csv
@@ -168,7 +90,7 @@ impl Writeable for RevokedOutput {
16890
self.counterparty_delayed_payment_base_key.write(writer)?;
16991
self.counterparty_htlc_base_key.write(writer)?;
17092
writer.write_all(&self.per_commitment_key[..])?;
171-
self.input_descriptor.write(writer)?;
93+
writer.write_all(&byte_utils::be64_to_array(self.weight))?;
17294
writer.write_all(&byte_utils::be64_to_array(self.amount))?;
17395
self.htlc.write(writer)?;
17496
self.on_counterparty_tx_csv.write(writer)?;
@@ -182,7 +104,7 @@ impl Readable for RevokedOutput {
182104
let counterparty_delayed_payment_base_key = Readable::read(reader)?;
183105
let counterparty_htlc_base_key = Readable::read(reader)?;
184106
let per_commitment_key = Readable::read(reader)?;
185-
let input_descriptor = Readable::read(reader)?;
107+
let weight = Readable::read(reader)?;
186108
let amount = Readable::read(reader)?;
187109
let htlc = Readable::read(reader)?;
188110
let on_counterparty_tx_csv = Readable::read(reader)?;
@@ -191,7 +113,7 @@ impl Readable for RevokedOutput {
191113
counterparty_delayed_payment_base_key,
192114
counterparty_htlc_base_key,
193115
per_commitment_key,
194-
input_descriptor,
116+
weight,
195117
amount,
196118
htlc,
197119
on_counterparty_tx_csv
@@ -347,8 +269,8 @@ impl PackageSolvingData {
347269
}
348270
fn weight(&self) -> usize {
349271
let weight = match self {
350-
PackageSolvingData::RevokedOutput(ref outp) => { get_witnesses_weight(&[outp.input_descriptor]) },
351-
PackageSolvingData::CounterpartyHTLCOutput(ref outp) => { get_witnesses_weight(if outp.preimage.is_some() { &[InputDescriptors::OfferedHTLC] } else { &[InputDescriptors::ReceivedHTLC]}) },
272+
PackageSolvingData::RevokedOutput(ref outp) => { outp.weight as usize },
273+
PackageSolvingData::CounterpartyHTLCOutput(ref outp) => { if outp.preimage.is_some() { WEIGHT_OFFERED_HTLC as usize } else { WEIGHT_RECEIVED_HTLC as usize } },
352274
// Note: Currently, weights of holder outputs spending witnesses aren't used
353275
// as we can't malleate spending package to increase their feerate. This
354276
// should change with the remaining anchor output patchset.
@@ -650,7 +572,7 @@ impl PackageTemplate {
650572
}
651573
pub(crate) fn package_weight(&self, destination_script: &Script) -> usize {
652574
let mut input = Vec::new();
653-
let mut witnesses_weight = 0;
575+
let mut witnesses_weight = 2; // count segwit flags
654576
for (outpoint, outp) in self.inputs.iter() {
655577
input.push(TxIn {
656578
previous_output: *outpoint,

0 commit comments

Comments
 (0)