Skip to content

Commit bcfc7b6

Browse files
author
Antoine Riard
committed
Remove InputDescriptors by named constants
1 parent 8615401 commit bcfc7b6

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
@@ -44,7 +44,7 @@ use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
4444
use chain::transaction::{OutPoint, TransactionData};
4545
use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface};
4646
use chain::onchaintx::OnchainTxHandler;
47-
use chain::onchain_utils::{CounterpartyHTLCOutput, HolderFundingOutput, HolderHTLCOutput, InputDescriptors, PackageMalleability, PackageSolvingData, PackageTemplate, RevokedOutput};
47+
use chain::onchain_utils::{CounterpartyHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageMalleability, PackageSolvingData, PackageTemplate, RevokedOutput, WEIGHT_REVOKED_OUTPUT, WEIGHT_REVOKED_RECEIVED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC};
4848
use chain::Filter;
4949
use util::logger::Logger;
5050
use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48};
@@ -1571,7 +1571,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
15711571
// First, process non-htlc outputs (to_holder & to_counterparty)
15721572
for (idx, outp) in tx.output.iter().enumerate() {
15731573
if outp.script_pubkey == revokeable_p2wsh {
1574-
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);
1574+
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);
15751575
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);
15761576
claimable_outpoints.push(justice_package);
15771577
}
@@ -1585,7 +1585,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
15851585
tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
15861586
return (claimable_outpoints, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
15871587
}
1588-
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);
1588+
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);
15891589
let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedOutput(revk_outp), PackageMalleability::Malleable, htlc.cltv_expiry, true, 0, None, height);
15901590
claimable_outpoints.push(justice_package);
15911591
}
@@ -1767,7 +1767,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
17671767
let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
17681768

17691769
log_trace!(logger, "Counterparty HTLC broadcast {}:{}", htlc_txid, 0);
1770-
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);
1770+
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);
17711771
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);
17721772
let claimable_outpoints = vec!(justice_package);
17731773
let outputs = vec![(0, tx.output[0].clone())];
@@ -2902,8 +2902,7 @@ mod tests {
29022902
use bitcoin::network::constants::Network;
29032903
use hex;
29042904
use chain::channelmonitor::ChannelMonitor;
2905-
use chain::onchain_utils;
2906-
use chain::onchain_utils::InputDescriptors;
2905+
use chain::onchain_utils::{WEIGHT_OFFERED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_RECEIVED_HTLC, WEIGHT_REVOKED_OUTPUT};
29072906
use chain::transaction::OutPoint;
29082907
use ln::{PaymentPreimage, PaymentHash};
29092908
use ln::channelmanager::BestBlock;
@@ -3062,25 +3061,25 @@ mod tests {
30623061
let mut sum_actual_sigs = 0;
30633062

30643063
macro_rules! sign_input {
3065-
($sighash_parts: expr, $idx: expr, $amount: expr, $input_type: expr, $sum_actual_sigs: expr) => {
3064+
($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr) => {
30663065
let htlc = HTLCOutputInCommitment {
3067-
offered: if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::OfferedHTLC { true } else { false },
3066+
offered: if *$weight == WEIGHT_REVOKED_OFFERED_HTLC || *$weight == WEIGHT_OFFERED_HTLC { true } else { false },
30683067
amount_msat: 0,
30693068
cltv_expiry: 2 << 16,
30703069
payment_hash: PaymentHash([1; 32]),
30713070
transaction_output_index: Some($idx as u32),
30723071
};
3073-
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) };
3072+
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) };
30743073
let sighash = hash_to_message!(&$sighash_parts.signature_hash($idx, &redeem_script, $amount, SigHashType::All)[..]);
30753074
let sig = secp_ctx.sign(&sighash, &privkey);
30763075
$sighash_parts.access_witness($idx).push(sig.serialize_der().to_vec());
30773076
$sighash_parts.access_witness($idx)[0].push(SigHashType::All as u8);
30783077
sum_actual_sigs += $sighash_parts.access_witness($idx)[0].len();
3079-
if *$input_type == InputDescriptors::RevokedOutput {
3078+
if *$weight == WEIGHT_REVOKED_OUTPUT {
30803079
$sighash_parts.access_witness($idx).push(vec!(1));
3081-
} else if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::RevokedReceivedHTLC {
3080+
} else if *$weight == WEIGHT_REVOKED_OFFERED_HTLC || *$weight == WEIGHT_REVOKED_RECEIVED_HTLC {
30823081
$sighash_parts.access_witness($idx).push(pubkey.clone().serialize().to_vec());
3083-
} else if *$input_type == InputDescriptors::ReceivedHTLC {
3082+
} else if *$weight == WEIGHT_RECEIVED_HTLC {
30843083
$sighash_parts.access_witness($idx).push(vec![0]);
30853084
} else {
30863085
$sighash_parts.access_witness($idx).push(PaymentPreimage([1; 32]).0.to_vec());
@@ -3113,14 +3112,16 @@ mod tests {
31133112
value: 0,
31143113
});
31153114
let base_weight = claim_tx.get_weight();
3116-
let inputs_des = vec![InputDescriptors::RevokedOutput, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedReceivedHTLC];
3115+
let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_RECEIVED_HTLC];
3116+
let mut inputs_total_weight = 2; // count segwit flags
31173117
{
31183118
let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3119-
for (idx, inp) in inputs_des.iter().enumerate() {
3119+
for (idx, inp) in inputs_weight.iter().enumerate() {
31203120
sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3121+
inputs_total_weight += inp;
31213122
}
31223123
}
3123-
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));
3124+
assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
31243125

31253126
// Claim tx with 1 offered HTLCs, 3 received HTLCs
31263127
claim_tx.input.clear();
@@ -3137,14 +3138,16 @@ mod tests {
31373138
});
31383139
}
31393140
let base_weight = claim_tx.get_weight();
3140-
let inputs_des = vec![InputDescriptors::OfferedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC];
3141+
let inputs_weight = vec![WEIGHT_OFFERED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_RECEIVED_HTLC];
3142+
let mut inputs_total_weight = 2; // count segwit flags
31413143
{
31423144
let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3143-
for (idx, inp) in inputs_des.iter().enumerate() {
3145+
for (idx, inp) in inputs_weight.iter().enumerate() {
31443146
sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3147+
inputs_total_weight += inp;
31453148
}
31463149
}
3147-
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));
3150+
assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
31483151

31493152
// Justice tx with 1 revoked HTLC-Success tx output
31503153
claim_tx.input.clear();
@@ -3159,14 +3162,16 @@ mod tests {
31593162
witness: Vec::new(),
31603163
});
31613164
let base_weight = claim_tx.get_weight();
3162-
let inputs_des = vec![InputDescriptors::RevokedOutput];
3165+
let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
3166+
let mut inputs_total_weight = 2; // count segwit flags
31633167
{
31643168
let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3165-
for (idx, inp) in inputs_des.iter().enumerate() {
3169+
for (idx, inp) in inputs_weight.iter().enumerate() {
31663170
sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3171+
inputs_total_weight += inp;
31673172
}
31683173
}
3169-
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));
3174+
assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_weight.len() - sum_actual_sigs));
31703175
}
31713176

31723177
// 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
@@ -360,8 +282,8 @@ impl PackageSolvingData {
360282
}
361283
fn weight(&self) -> usize {
362284
let weight = match self {
363-
PackageSolvingData::RevokedOutput(ref outp) => { get_witnesses_weight(&[outp.input_descriptor]) },
364-
PackageSolvingData::CounterpartyHTLCOutput(ref outp) => { get_witnesses_weight(if outp.preimage.is_some() { &[InputDescriptors::OfferedHTLC] } else { &[InputDescriptors::ReceivedHTLC]}) },
285+
PackageSolvingData::RevokedOutput(ref outp) => { outp.weight as usize },
286+
PackageSolvingData::CounterpartyHTLCOutput(ref outp) => { if outp.preimage.is_some() { WEIGHT_OFFERED_HTLC as usize } else { WEIGHT_RECEIVED_HTLC as usize } },
365287
// Note: Currently, weights of holder outputs spending witnesses aren't used
366288
// as we can't malleate spending package to increase their feerate. This
367289
// should change with the remaining anchor output patchset.
@@ -663,7 +585,7 @@ impl PackageTemplate {
663585
}
664586
pub(crate) fn package_weight(&self, destination_script: &Script) -> usize {
665587
let mut input = Vec::new();
666-
let mut witnesses_weight = 0;
588+
let mut witnesses_weight = 2; // count segwit flags
667589
for (outpoint, outp) in self.inputs.iter() {
668590
input.push(TxIn {
669591
previous_output: *outpoint,

0 commit comments

Comments
 (0)