Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/consensus/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,12 @@ impl Config {

pub fn get_validator_set_config(&self, shard_id: u32) -> Vec<ValidatorSetConfig> {
if let Some(sets) = &self.validator_sets {
assert!(sets.len() > 0);
assert!(!sets.is_empty());
return sets.to_vec();
}

if let Some(addresses) = &self.validator_addresses {
assert!(addresses.len() > 0);
assert!(!addresses.is_empty());
return vec![ValidatorSetConfig {
effective_at: 0,
validator_public_keys: addresses.clone(),
Expand Down
2 changes: 1 addition & 1 deletion src/consensus/malachite/read_sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ impl State {
return false;
}

if self.sync.peers.len() == 0 {
if self.sync.peers.is_empty() {
return false;
}

Expand Down
2 changes: 1 addition & 1 deletion src/core/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,7 @@ impl informalsystems_malachitebft_core_types::Context for SnapchainValidatorCont
height: Self::Height,
round: Round,
) -> &'a Self::Validator {
assert!(validator_set.validators.len() > 0);
assert!(!validator_set.validators.is_empty());
assert!(round != Round::Nil && round.as_i64() >= 0);

let proposer_index = {
Expand Down
10 changes: 5 additions & 5 deletions src/core/validations/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ fn validate_bytes_as_string(
max_length: u64,
required: bool,
) -> Result<(), ValidationError> {
if required && byte_array.len() == 0 {
if required && byte_array.is_empty() {
return Err(ValidationError::MissingString);
}
if byte_array.len() as u64 > max_length {
Expand Down Expand Up @@ -95,7 +95,7 @@ pub fn validate_message(
let message_data;
if message.data_bytes.is_some() {
data_bytes = message.data_bytes.as_ref().unwrap().clone();
if data_bytes.len() == 0 {
if data_bytes.is_empty() {
return Err(ValidationError::MissingData);
}
match MessageData::decode(message.data_bytes.as_ref().unwrap().as_slice()) {
Expand Down Expand Up @@ -255,7 +255,7 @@ fn validate_signature(
return Err(ValidationError::InvalidSignatureScheme);
}

if signature.len() == 0 {
if signature.is_empty() {
return Err(ValidationError::MissingSignature);
}

Expand All @@ -279,7 +279,7 @@ pub fn validate_message_hash(
return Err(ValidationError::InvalidHashScheme);
}

if data_bytes.len() == 0 {
if data_bytes.is_empty() {
return Err(ValidationError::MissingData);
}

Expand All @@ -291,7 +291,7 @@ pub fn validate_message_hash(
}

pub fn validate_fname(input: &String) -> Result<(), ValidationError> {
if input.len() == 0 {
if input.is_empty() {
return Err(ValidationError::FnameIsMissing);
}

Expand Down
4 changes: 2 additions & 2 deletions src/mempool/block_receiver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub struct BlockReceiver {

impl BlockReceiver {
fn validate_block_events(&self, block: &Block) -> bool {
if block.events.len() == 0 {
if block.events.is_empty() {
return true;
}

Expand Down Expand Up @@ -188,7 +188,7 @@ impl BlockReceiver {
height = block.header.as_ref().unwrap().height.unwrap().block_number,
"Received block"
);
if block.events.len() == 0 {
if block.events.is_empty() {
continue;
}
// The db is the source of truth, it's possible to read this out of the events_rx channel but delivery over that channel is not reliable (it's a broadcast channel) we may not have the most up to date state.
Expand Down
4 changes: 2 additions & 2 deletions src/network/gossip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ impl SnapchainGossip {
fc_network: FarcasterNetwork,
config: &Config,
) -> Result<String, reqwest::Error> {
if config.announce_rpc_address.len() > 0 {
if !config.announce_rpc_address.is_empty() {
return Ok(config.announce_rpc_address.clone());
}

Expand All @@ -387,7 +387,7 @@ impl SnapchainGossip {
}

async fn get_announce_gossip_address(fc_network: FarcasterNetwork, config: &Config) -> String {
if config.announce_address.len() > 0 {
if !config.announce_address.is_empty() {
return config.announce_address.clone();
}

Expand Down
2 changes: 1 addition & 1 deletion src/network/http_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ mod serdebase64opt {

pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<u8>>, D::Error> {
let base64 = String::deserialize(d)?.replace(" ", "+");
if base64.len() == 0 {
if base64.is_empty() {
Ok(None)
} else {
let decoded = BASE64_STANDARD
Expand Down
8 changes: 4 additions & 4 deletions src/perf/perftest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,10 +224,10 @@ pub async fn run() -> Result<(), Box<dyn Error>> {
}
}
time = stats_calculation_timer.tick() => {
let avg_time_to_confirmation = if time_to_confirmation.len() > 0 {time_to_confirmation.iter().sum::<u64>() as f64 / time_to_confirmation.len() as f64} else {0f64};
let max_time_to_confirmation = if time_to_confirmation.len() > 0 {time_to_confirmation.clone().into_iter().max().unwrap()} else {0};
let avg_block_time = if block_times.len() > 0 {block_times.iter().sum::<u64>() as f64 / block_times.len() as f64} else {0f64};
let max_block_time = if block_times.len() > 0 {block_times.clone().into_iter().max().unwrap()} else {0};
let avg_time_to_confirmation = if !time_to_confirmation.is_empty() {time_to_confirmation.iter().sum::<u64>() as f64 / time_to_confirmation.len() as f64} else {0f64};
let max_time_to_confirmation = if !time_to_confirmation.is_empty() {time_to_confirmation.clone().into_iter().max().unwrap()} else {0};
let avg_block_time = if !block_times.is_empty() {block_times.iter().sum::<u64>() as f64 / block_times.len() as f64} else {0f64};
let max_block_time = if !block_times.is_empty() {block_times.clone().into_iter().max().unwrap()} else {0};
let time_elapsed = time.duration_since(start).as_secs();
let confirmed_msgs_per_sec = num_messages_confirmed as f64 / cfg.stats_calculation_interval.as_secs_f64();
let submitted_msgs_per_sec = num_messages_submitted as f64 / cfg.stats_calculation_interval.as_secs_f64();
Expand Down
3 changes: 2 additions & 1 deletion src/storage/store/account/block_event_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::storage::db::{PageOptions, RocksDB, RocksDbTransactionBatch, RocksdbE
use prost::Message;
use std::sync::Arc;
use thiserror::Error;
use tracing::error;
Comment thread
manan19 marked this conversation as resolved.
Outdated

#[derive(Error, Debug)]
pub enum BlockEventStorageError {
Expand Down Expand Up @@ -79,7 +80,7 @@ fn get_block_page_by_prefix(
)
.map_err(|_| BlockEventStorageError::TooManyBlocksInResult)?; // TODO: Return the right error

let next_page_token = if last_key.len() > 0 {
let next_page_token = if !last_key.is_empty() {
Some(last_key)
} else {
None
Expand Down
4 changes: 2 additions & 2 deletions src/storage/store/account/cast_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@ impl CastStore {
)?;

let messages = get_many_messages(store.db().borrow(), message_keys)?;
let next_page_token = if last_key.len() > 0 {
let next_page_token = if !last_key.is_empty() {
Some(last_key.to_vec())
} else {
None
Expand Down Expand Up @@ -525,7 +525,7 @@ impl CastStore {
)?;

let messages_bytes = get_many_messages(store.db().borrow(), message_keys)?;
let next_page_token = if last_key.len() > 0 {
let next_page_token = if !last_key.is_empty() {
Some(last_key.to_vec())
} else {
None
Expand Down
2 changes: 1 addition & 1 deletion src/storage/store/account/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ impl HubEventStorageExt for HubEvent {

Ok(EventsPage {
events,
next_page_token: if last_key.len() > 0 {
next_page_token: if !last_key.is_empty() {
Some(last_key)
} else {
None
Expand Down
20 changes: 6 additions & 14 deletions src/storage/store/account/link_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ impl LinkStore {
)?;

let messages = get_many_messages(store.db().borrow(), message_keys)?;
let next_page_token = if last_key.len() > 0 {
let next_page_token = if !last_key.is_empty() {
Some(last_key.to_vec())
} else {
None
Expand Down Expand Up @@ -244,17 +244,13 @@ impl LinkStore {
/// * `link_body` - body of link that contains type of link created and target ID of the object
/// being reacted to
fn link_add_key(fid: u64, link_body: &LinkBody) -> Result<Vec<u8>, HubError> {
if link_body.target.is_some()
&& (link_body.r#type.is_empty() || link_body.r#type.len() == 0)
{
if link_body.target.is_some() && link_body.r#type.is_empty() {
return Err(HubError::validation_failure(
"targetId provided without type",
));
}

if !link_body.r#type.is_empty()
&& (link_body.r#type.len() > Self::LINK_TYPE_BYTE_SIZE || link_body.r#type.len() == 0)
{
if !link_body.r#type.is_empty() && link_body.r#type.len() > Self::LINK_TYPE_BYTE_SIZE {
return Err(HubError::validation_failure(
"link type invalid - non-empty link type found with invalid length",
));
Expand Down Expand Up @@ -291,17 +287,13 @@ impl LinkStore {
/// * `link_body` - body of link that contains type of link created and target ID of the object
/// being reacted to
fn link_remove_key(fid: u64, link_body: &LinkBody) -> Result<Vec<u8>, HubError> {
if link_body.target.is_some()
&& (link_body.r#type.is_empty() || link_body.r#type.len() == 0)
{
if link_body.target.is_some() && link_body.r#type.is_empty() {
return Err(HubError::validation_failure(
"targetID provided without type",
Comment thread
manan19 marked this conversation as resolved.
Outdated
));
}

if !link_body.r#type.is_empty()
&& (link_body.r#type.len() > Self::LINK_TYPE_BYTE_SIZE || link_body.r#type.len() == 0)
{
if !link_body.r#type.is_empty() && link_body.r#type.len() > Self::LINK_TYPE_BYTE_SIZE {
return Err(HubError::validation_failure(
"link type invalid - non-empty link type found with invalid length",
));
Expand Down Expand Up @@ -375,7 +367,7 @@ impl LinkStore {
fid: u64,
ts_hash: Option<&[u8; TS_HASH_LENGTH]>,
) -> Result<Vec<u8>, HubError> {
if fid != 0 && (ts_hash.is_none() || ts_hash.is_some_and(|tsh| tsh.len() == 0)) {
if fid != 0 && ts_hash.is_none() {
return Err(HubError::validation_failure(
"fid provided without timestamp hash",
));
Expand Down
114 changes: 114 additions & 0 deletions src/storage/store/account/link_store_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2144,4 +2144,118 @@ mod tests {
.unwrap();
assert_eq!(result3, add3);
}

// Regression tests for link_add_key / link_remove_key error branches.
// These cover the paths simplified when `.len() == 0 || .is_empty()` duplication was removed.

fn make_link_add_with(fid: u64, link_type: &str, target: Option<Target>) -> message::Message {
let mut msg = messages_factory::links::create_link_add(fid, link_type, 0, None, None);
if let Some(data) = msg.data.as_mut() {
if let Some(message::message_data::Body::LinkBody(body)) = data.body.as_mut() {
body.r#type = link_type.to_string();
body.target = target;
}
}
msg
}

fn make_link_remove_with(
fid: u64,
link_type: &str,
target: Option<Target>,
) -> message::Message {
let mut msg = messages_factory::links::create_link_remove(fid, link_type, 0, None, None);
if let Some(data) = msg.data.as_mut() {
if let Some(message::message_data::Body::LinkBody(body)) = data.body.as_mut() {
body.r#type = link_type.to_string();
body.target = target;
}
}
msg
}

#[test]
fn test_make_add_key_rejects_empty_type_with_target() {
let msg = make_link_add_with(FID_FOR_TEST, "", Some(Target::TargetFid(TARGET_FID)));
let result = LinkStore::make_add_key(&msg);
assert!(result.is_err(), "empty type with target should be rejected");
assert!(
result
.unwrap_err()
.message
.contains("targetId provided without type"),
"expected targetId-without-type error"
);
}

#[test]
fn test_make_remove_key_rejects_empty_type_with_target() {
let msg = make_link_remove_with(FID_FOR_TEST, "", Some(Target::TargetFid(TARGET_FID)));
let result = LinkStore::make_remove_key(&msg);
assert!(result.is_err(), "empty type with target should be rejected");
assert!(
result
.unwrap_err()
.message
.contains("targetID provided without type"),
"expected targetID-without-type error"
Comment thread
manan19 marked this conversation as resolved.
Outdated
);
}

#[test]
fn test_make_add_key_rejects_overlong_type() {
// LINK_TYPE_BYTE_SIZE is 8; "xxxxxxxxx" is 9 bytes
let msg = make_link_add_with(
FID_FOR_TEST,
"xxxxxxxxx",
Some(Target::TargetFid(TARGET_FID)),
);
let result = LinkStore::make_add_key(&msg);
assert!(
result.is_err(),
"type longer than 8 bytes should be rejected"
);
assert!(
result.unwrap_err().message.contains("link type invalid"),
"expected link-type-invalid error"
);
}

#[test]
fn test_make_remove_key_rejects_overlong_type() {
let msg = make_link_remove_with(
FID_FOR_TEST,
"xxxxxxxxx",
Some(Target::TargetFid(TARGET_FID)),
);
let result = LinkStore::make_remove_key(&msg);
assert!(
result.is_err(),
"type longer than 8 bytes should be rejected"
);
assert!(
result.unwrap_err().message.contains("link type invalid"),
"expected link-type-invalid error"
);
}

#[test]
fn test_make_add_key_accepts_valid_type() {
let msg = make_link_add_with(
FID_FOR_TEST,
LINK_TYPE_FOLLOW,
Some(Target::TargetFid(TARGET_FID)),
);
assert!(LinkStore::make_add_key(&msg).is_ok());
}

#[test]
fn test_make_remove_key_accepts_valid_type() {
let msg = make_link_remove_with(
FID_FOR_TEST,
LINK_TYPE_FOLLOW,
Some(Target::TargetFid(TARGET_FID)),
);
assert!(LinkStore::make_remove_key(&msg).is_ok());
}
}
6 changes: 3 additions & 3 deletions src/storage/store/account/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ where
},
)?;

let next_page_token = if last_key.len() > 0 {
let next_page_token = if !last_key.is_empty() {
Some(last_key.to_vec())
} else {
None
Expand All @@ -287,7 +287,7 @@ where

#[inline]
pub fn message_encode(message: &MessageProto) -> Vec<u8> {
if message.data_bytes.is_some() && message.data_bytes.as_ref().unwrap().len() > 0 {
if message.data_bytes.as_ref().is_some_and(|b| !b.is_empty()) {
// Clone the message
let mut cloned = message.clone();
cloned.data = None;
Expand All @@ -300,7 +300,7 @@ pub fn message_encode(message: &MessageProto) -> Vec<u8> {

#[inline]
pub fn message_bytes_decode(msg: &mut MessageProto) {
if msg.data_bytes.is_some() && msg.data_bytes.as_ref().unwrap().len() > 0 {
if msg.data_bytes.as_ref().is_some_and(|b| !b.is_empty()) {
if let Ok(msg_data) = MessageData::decode(msg.data_bytes.as_ref().unwrap().as_slice()) {
msg.data = Some(msg_data);
} else {
Expand Down
Loading
Loading