Skip to content

Commit b9643df

Browse files
authored
chore: minor-fixes (#17)
* correct typos/grammar * fix: remove anyhow::Result from key module * remove unused rpc
1 parent 2137588 commit b9643df

36 files changed

+214
-1383
lines changed

src/chain/cache.rs

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,14 @@ use crate::{
99
use energon::kyber::tbls::SigShare;
1010
use std::collections::VecDeque;
1111

12-
/// Partials that are up to this amount of rounds more than the last
13-
/// beacon we have - it is useful for quick catchup.
12+
/// Partials that are up to this number of rounds
13+
/// beyond the last beacon we have - useful for quick catchup.
1414
pub const CACHE_LIMIT_ROUNDS: u64 = 3;
1515

1616
/// Logical errors for partial cache.
1717
#[derive(thiserror::Error, Debug)]
1818
pub enum CacheError {
19-
#[error("new stored round {latest_stored} is less then height {height}")]
19+
#[error("new stored round {latest_stored} is less than height {height}")]
2020
Height { latest_stored: u64, height: u64 },
2121
#[error("invalid structure: allowed rounds {allowed:?}, height {height}")]
2222
Structure { allowed: Vec<u64>, height: u64 },
@@ -32,8 +32,8 @@ struct PartialsUnchecked {
3232
}
3333

3434
/// Partial cache holds 2 types of shares:
35-
/// - [`PartialBeaconPacket`] unchecked BLS signature .
36-
/// - [`SigShare`] checked BLS signature .
35+
/// - [`PartialBeaconPacket`] unchecked BLS signature.
36+
/// - [`SigShare`] checked BLS signature.
3737
///
3838
/// Partial cache structure:
3939
/// n n + 1 n + 2 .. n + 2 + `CACHE_LIMIT_ROUNDS`
@@ -63,11 +63,12 @@ impl<S: Scheme> PartialCache<S> {
6363
}
6464
}
6565

66-
/// Adds packet into the corresponding round cache if the round of packet is allowed
67-
/// and signature of packet is not duplicated.
66+
/// Adds a packet to the corresponding round cache if the packet's
67+
/// round is allowed and the packet's signature is not duplicated.
6868
///
69-
/// Cache _might_ contain more than one packet with same share index for given round.
70-
/// This is possible if leaved node is not in proper state: old index collided with new index of some valid node.
69+
/// Corner case: cache _may_ contain more than one packet with the same
70+
/// share index for a given round. This is possible if leaved node is not
71+
/// in proper state and old index collided with new index of some valid node.
7172
/// Such invalid packets will be discarded at BLS signature check.
7273
pub fn add_packet(&mut self, packet: PartialBeaconPacket) -> Option<bool> {
7374
if let Some(r_cache) = self
@@ -100,7 +101,8 @@ impl<S: Scheme> PartialCache<S> {
100101
self.valid_sigs.iter().any(|s| s.index() == index)
101102
}
102103

103-
/// Adds sigshare to partial cache. Returns slice of sigshares *sorted by index* if their number hits the threshold.
104+
/// Adds sigshare to partial cache. Returns slice of sigshares *sorted by index*
105+
/// if their count reaches the threshold.
104106
///
105107
/// WARNING: bls signature validity and round value must be prechecked on caller side.
106108
pub fn add_prechecked(
@@ -125,7 +127,7 @@ impl<S: Scheme> PartialCache<S> {
125127
Some(self.valid_sigs.as_slice())
126128
}
127129

128-
/// Updates cache state if argument is bigger than cache metadata.
130+
/// Updates cache state if argument is greater than cache height.
129131
/// Returns packets to verify for `latest_stored +1` round if such packets exist.
130132
fn update(&mut self, latest_stored: u64) -> Result<Option<PartialsUnchecked>, CacheError> {
131133
#[allow(clippy::comparison_chain, reason = "exhaustive")]
@@ -146,12 +148,12 @@ impl<S: Scheme> PartialCache<S> {
146148
for _ in 0..delta {
147149
match self.rounds_cache.pop_front() {
148150
Some(packets) => {
149-
// Add corresponding entry for new allowed round
151+
// Add corresponding entry for new allowed round.
150152
self.rounds_cache.push_back(PartialsUnchecked {
151153
round: packets.round + CACHE_LIMIT_ROUNDS,
152154
packets: Vec::with_capacity(self.thr),
153155
});
154-
// Stop at wanted round to aggregate
156+
// Stop at wanted round to aggregate.
155157
if packets.round == self.height + 1 {
156158
if packets.packets.is_empty() {
157159
return Ok(None);

src/chain/epoch.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ use energon::{
1717
pub struct EpochNode<S: Scheme> {
1818
/// Node address.
1919
peer: Address,
20-
/// Node public share is computed by evaluating public sharing polynomial at the node index.
20+
/// Node public share is computed by evaluating public
21+
/// sharing polynomial at the node index.
2122
share: PubShare<S>,
2223
}
2324

@@ -27,7 +28,8 @@ impl<S: Scheme> EpochNode<S> {
2728
}
2829
}
2930

30-
/// Epoch config is representation of [`dkg::DkgOutput`] where QUAL nodes are mapped into list of [`EpochNode`].
31+
/// Epoch config is representation of [`dkg::DkgOutput`]
32+
/// where QUAL nodes are mapped into list of [`EpochNode`].
3133
pub struct EpochConfig<S: Scheme> {
3234
share: dkg::DistKeyShare<S>,
3335
remote_nodes: Vec<EpochNode<S>>,

src/chain/handler.rs

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
//! Chain logic implementation.
2+
//! Price for some abstraction boundaries is traded for speed.
13
use super::{
24
cache,
35
epoch::{EpochConfig, EpochNode},
@@ -39,6 +41,7 @@ use tokio::{
3941
use tokio_util::task::TaskTracker;
4042
use tonic::Status;
4143

44+
/// Truncated signature bytes for compact log output.
4245
const SHORT_SIG_BYTES: usize = 3;
4346

4447
#[derive(thiserror::Error, Debug)]
@@ -53,8 +56,8 @@ pub enum ChainError {
5356
TickerClosedTx,
5457
#[error("pool receiver has been closed unexpectedly")]
5558
PoolClosedRx,
56-
#[error("invalid lengh of partial: expected {expected} received {received}")]
57-
InvalidShareLenght { expected: usize, received: usize },
59+
#[error("invalid length of partial: expected {expected} received {received}")]
60+
InvalidShareLength { expected: usize, received: usize },
5861
#[error("attempt to process beacon from node of index {0}, but it was not in the group file")]
5962
UnknownIndex(u32),
6063
#[error("received partial with invalid signature")]
@@ -68,11 +71,11 @@ pub enum ChainError {
6871
#[error("recovered signature is invalid")]
6972
InvalidRecovered,
7073
#[error("chain store: {0}")]
71-
ChainStoreError(#[from] StoreError),
74+
ChainStore(#[from] StoreError),
7275
#[error("t_bls: {0}")]
7376
TBlsError(#[from] tbls::TBlsError),
7477
#[error("fs: {0}")]
75-
FileStoreError(#[from] FileStoreError),
78+
FileStore(#[from] FileStoreError),
7679
#[error("recover_unchecked: scalar is non-invertable")]
7780
NonInvertableScalar,
7881
#[error("internal error")]
@@ -85,7 +88,7 @@ pub enum ChainError {
8588
struct ChainHandler<S: Scheme, B: BeaconRepr> {
8689
/// Public information of chain.
8790
chain_info: ChainInfo<S>,
88-
/// Minimum period allowed between and subsequent partial generation.
91+
/// Minimum period allowed between subsequent partial generation.
8992
catchup_period: Duration,
9093
/// Actor handle for beacon persistent database.
9194
store: ChainStore<B>,
@@ -97,19 +100,20 @@ struct ChainHandler<S: Scheme, B: BeaconRepr> {
97100
ec: EpochConfig<S>,
98101
/// Private binding address.
99102
private_listen: String,
100-
/// Public URI Authority.
101-
our_addres: Address,
103+
/// Public URI authority.
104+
our_address: Address,
102105
log: Logger,
103106
}
104107

105108
pub enum ChainCmd {
106109
Shutdown(Callback<(), ChainError>),
107-
/// Chain is notified once DKG output is received, triggering preparation
110+
/// Notification once DKG output is received, triggers preparation
108111
/// for transition into the next epoch (see: [`wait_last_round`]).
109112
NewEpoch {
110113
first_round: u64,
111114
},
112-
/// Partial reload of the chain module during transition to update [`EpochConfig`] and logger.
115+
/// Partially reloads the chain module during transitions to update
116+
/// the [`EpochConfig`] and metadata for logger.
113117
Reload,
114118
/// Request for chain public information.
115119
ChainInfo(Callback<ChainInfoPacket, BeaconProcessError>),
@@ -151,8 +155,8 @@ pub struct ChainConfig<B: BeaconRepr> {
151155
}
152156

153157
impl<S: Scheme, B: BeaconRepr> ChainHandler<S, B> {
154-
/// This function updates the epoch configuration and logger for chain handler
155-
/// after each DKG.
158+
/// This function updates the epoch configuration and logger metadata
159+
/// for chain handler after each DKG.
156160
///
157161
/// Returns top-level components of chain module with their channels:
158162
/// - Chain configuration: [`ChainHandler`].
@@ -211,8 +215,8 @@ impl<S: Scheme, B: BeaconRepr> ChainHandler<S, B> {
211215
genesis_time,
212216
genesis_seed,
213217
};
214-
let catchup_period = Duration::from_secs(catchup_period.get_value().into());
215218

219+
let catchup_period = Duration::from_secs(catchup_period.get_value().into());
216220
let chain_handler = Self {
217221
chain_info,
218222
catchup_period,
@@ -221,12 +225,11 @@ impl<S: Scheme, B: BeaconRepr> ChainHandler<S, B> {
221225
fs,
222226
ec,
223227
private_listen,
224-
our_addres,
228+
our_address: our_addres,
225229
log,
226230
};
227231

228232
let latest_stored = chain_handler.store.last().await?;
229-
230233
let registry = Registry::new(
231234
&chain_handler.chain_info,
232235
latest_stored,
@@ -239,9 +242,6 @@ impl<S: Scheme, B: BeaconRepr> ChainHandler<S, B> {
239242
}
240243

241244
/// Adds remote nodes to connection pool for given beacon ID.
242-
///
243-
/// If some nodes are already in pool (registered for other ID),
244-
/// their connections will be reused.
245245
async fn register_in_pool(&self) -> Result<(), ChainError> {
246246
let peers = self
247247
.ec
@@ -315,7 +315,7 @@ impl<S: Scheme, B: BeaconRepr> ChainHandler<S, B> {
315315
{
316316
if let Some(thr_sigs) =
317317
reg.cache_mut()
318-
.add_prechecked(sigshare, &self.our_addres, &self.log)
318+
.add_prechecked(sigshare, &self.our_address, &self.log)
319319
{
320320
let Ok(recovered) = tbls::recover_unchecked(thr_sigs) else {
321321
return Err(ChainError::NonInvertableScalar);
@@ -403,7 +403,7 @@ impl<S: Scheme, B: BeaconRepr> ChainHandler<S, B> {
403403
// Add packet to cache if p_round hits the allowed range and signature is not duplicated.
404404
if p_round > ls_round + 1 && p_round <= ls_round + 1 + cache::CACHE_LIMIT_ROUNDS {
405405
let Some(is_added) = reg.cache_mut().add_packet(partial.packet) else {
406-
error!(&self.log, "cache_height {}: attempt to add non-allowed round {p_round}, current {c_round}, please report this.", reg.cache().height());
406+
error!(&self.log, "cache_height {}: attempt to add non-allowed round {p_round}, current {c_round}, please report this", reg.cache().height());
407407
return Err(ChainError::InvalidRound {
408408
invalid: p_round,
409409
current: c_round,
@@ -423,7 +423,7 @@ impl<S: Scheme, B: BeaconRepr> ChainHandler<S, B> {
423423
// Process packet as sigshare.
424424
} else if p_round == ls_round + 1 {
425425
let Some(idx) = cache::get_partial_index::<S>(&partial.packet.partial_sig) else {
426-
return Err(ChainError::InvalidShareLenght {
426+
return Err(ChainError::InvalidShareLength {
427427
expected: <S::Sig as energon::traits::Group>::POINT_SIZE + 2,
428428
received: partial.packet.partial_sig.len(),
429429
});
@@ -855,7 +855,7 @@ async fn run_chain<S: Scheme, B: BeaconRepr>(
855855
private_listen: h.private_listen,
856856
id: h.chain_info.beacon_id,
857857
fs: h.fs,
858-
our_addres: h.our_addres,
858+
our_addres: h.our_address,
859859
};
860860

861861
Ok(Some(config_for_next_epoch))

src/chain/info.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ use crate::{
77
use energon::{points::KeyPoint, traits::Affine};
88
use sha2::Digest;
99

10-
/// Public information that is necessary for a client to verify any beacon present in a randomness chain.
10+
/// Public information that is necessary for a client
11+
/// to verify any beacon present in a randomness chain.
1112
#[derive(Default, Clone, PartialEq)]
1213
pub struct ChainInfo<S: Scheme> {
1314
pub public_key: KeyPoint<S>,
@@ -24,7 +25,7 @@ pub enum ChainInfoError {
2425
Scheme,
2526
#[error("failed to deserialize group key")]
2627
PublicKey,
27-
#[error("genesis time can not be zero")]
28+
#[error("genesis time cannot be zero")]
2829
GenesisTime,
2930
}
3031

src/chain/registry.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use crate::{error, key::Scheme, log::Logger, net::utils::Seconds, protobuf::dran
66
use std::time::Duration;
77
use tokio::{sync::mpsc, task::JoinHandle};
88

9-
/// Registry holds actual data which might be changed per / within a round.
9+
/// Registry holds mutable state that can change each round or during a round.
1010
pub struct Registry<S: Scheme, B: BeaconRepr> {
1111
/// Latest verified and successfully stored beacon.
1212
latest_stored: B,

src/chain/time.rs

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -62,24 +62,16 @@ pub fn time_now() -> Duration {
6262
#[cfg(test)]
6363
mod test {
6464
use super::*;
65-
fn current_round_t(now: u64, period: u32, genesis: u64) -> u64 {
66-
let (next_round, _) = next_round(now, period, genesis);
67-
if next_round <= 1 {
68-
next_round
69-
} else {
70-
next_round - 1
71-
}
72-
}
7365

7466
#[test]
7567
fn time_basic() {
7668
let period = 3;
7769
let round = 22;
7870
let transition_round = round + ROUNDS_UNTIL_TRANSITION;
7971

80-
assert_eq!(round, current_round_t(1745308647, period, 1745308582));
81-
assert_eq!(round, current_round_t(1745308824, period, 1745308759));
82-
assert_eq!(round, current_round_t(1745309210, period, 1745309145));
72+
assert_eq!(round, current_round(1745308647, period, 1745308582));
73+
assert_eq!(round, current_round(1745308824, period, 1745308759));
74+
assert_eq!(round, current_round(1745309210, period, 1745309145));
8375
assert!(1745308675 == time_of_round(period, 1745308582, transition_round));
8476
assert!(1745308852 == time_of_round(period, 1745308759, transition_round));
8577
assert!(1745309238 == time_of_round(period, 1745309145, transition_round));

0 commit comments

Comments
 (0)