diff --git a/.github/workflows/run-tests-on-push-to-main.yml b/.github/workflows/run-tests-on-push-to-main.yml index 8134915c..3b1fc934 100644 --- a/.github/workflows/run-tests-on-push-to-main.yml +++ b/.github/workflows/run-tests-on-push-to-main.yml @@ -23,6 +23,12 @@ jobs: - name: Run Format run: cargo fmt --all -- --check + - name: Run Clippy + run: | + cargo clippy \ + --package acropolis_common \ + --package acropolis_codec + - name: Run Build run: cargo build --verbose diff --git a/codec/src/map_parameters.rs b/codec/src/map_parameters.rs index 60a809cf..d757d354 100644 --- a/codec/src/map_parameters.rs +++ b/codec/src/map_parameters.rs @@ -24,7 +24,7 @@ pub fn map_network(network: addresses::Network) -> Result { match network { addresses::Network::Mainnet => Ok(AddressNetwork::Main), addresses::Network::Testnet => Ok(AddressNetwork::Test), - _ => return Err(anyhow!("Unknown network in address")), + _ => Err(anyhow!("Unknown network in address")), } } @@ -149,7 +149,7 @@ pub fn map_anchor(anchor: &conway::Anchor) -> Anchor { /// Map a Nullable Anchor to ours pub fn map_nullable_anchor(anchor: &Nullable) -> Option { - map_nullable(&map_anchor, anchor) + map_nullable(map_anchor, anchor) } pub fn map_gov_action_id(pallas_action_id: &conway::GovActionId) -> Result { @@ -167,7 +167,7 @@ pub fn map_gov_action_id(pallas_action_id: &conway::GovActionId) -> Result, ) -> Result> { - map_nullable_result(&map_gov_action_id, id) + map_nullable_result(map_gov_action_id, id) } fn map_constitution(constitution: &conway::Constitution) -> Constitution { @@ -226,7 +226,7 @@ pub fn map_certificate( alonzo::Certificate::StakeRegistration(cred) => { Ok(TxCertificate::StakeRegistration(StakeAddressWithPos { stake_address: map_stake_address(cred, network_id), - tx_index: tx_index.try_into().unwrap(), + tx_index: tx_index.into(), cert_index: cert_index.try_into().unwrap(), })) } @@ -262,7 +262,7 @@ pub fn map_certificate( }, reward_account: StakeAddress::from_binary(reward_account)?, pool_owners: pool_owners - .into_iter() + .iter() .map(|v| { StakeAddress::new( StakeAddressPayload::StakeKeyHash(v.to_vec()), @@ -270,7 +270,7 @@ pub fn map_certificate( ) }) .collect(), - relays: relays.into_iter().map(|relay| map_relay(relay)).collect(), + relays: relays.iter().map(map_relay).collect(), pool_metadata: match pool_metadata { Nullable::Some(md) => Some(PoolMetadata { url: md.url.clone(), @@ -317,7 +317,7 @@ pub fn map_certificate( InstantaneousRewardTarget::StakeAddresses( creds .iter() - .map(|(sc, v)| (map_stake_address(&sc, network_id.clone()), *v)) + .map(|(sc, v)| (map_stake_address(sc, network_id.clone()), *v)) .collect(), ) } @@ -335,7 +335,7 @@ pub fn map_certificate( conway::Certificate::StakeRegistration(cred) => { Ok(TxCertificate::StakeRegistration(StakeAddressWithPos { stake_address: map_stake_address(cred, network_id), - tx_index: tx_index.try_into().unwrap(), + tx_index: tx_index.into(), cert_index: cert_index.try_into().unwrap(), })) } @@ -380,7 +380,7 @@ pub fn map_certificate( ) }) .collect(), - relays: relays.into_iter().map(|relay| map_relay(relay)).collect(), + relays: relays.iter().map(map_relay).collect(), pool_metadata: match pool_metadata { Nullable::Some(md) => Some(PoolMetadata { url: md.url.clone(), @@ -472,7 +472,7 @@ pub fn map_certificate( conway::Certificate::ResignCommitteeCold(cold_cred, anchor) => { Ok(TxCertificate::ResignCommitteeCold(ResignCommitteeCold { cold_credential: map_stake_credential(cold_cred), - anchor: map_nullable_anchor(&anchor), + anchor: map_nullable_anchor(anchor), })) } @@ -481,7 +481,7 @@ pub fn map_certificate( reg: DRepRegistration { credential: map_stake_credential(cred), deposit: *coin, - anchor: map_nullable_anchor(&anchor), + anchor: map_nullable_anchor(anchor), }, tx_hash, cert_index: cert_index as u64, @@ -503,7 +503,7 @@ pub fn map_certificate( Ok(TxCertificate::DRepUpdate(DRepUpdateWithPos { reg: DRepUpdate { credential: map_stake_credential(cred), - anchor: map_nullable_anchor(&anchor), + anchor: map_nullable_anchor(anchor), }, tx_hash, cert_index: cert_index as u64, @@ -614,20 +614,20 @@ fn map_drep_voting_thresholds(ts: &conway::DRepVotingThresholds) -> DRepVotingTh fn map_conway_protocol_param_update(p: &conway::ProtocolParamUpdate) -> Box { Box::new(ProtocolParamUpdate { // Fields, common for Conway and Alonzo-compatible - minfee_a: p.minfee_a.clone(), - minfee_b: p.minfee_b.clone(), - max_block_body_size: p.max_block_body_size.clone(), - max_transaction_size: p.max_transaction_size.clone(), - max_block_header_size: p.max_block_header_size.clone(), - key_deposit: p.key_deposit.clone(), - pool_deposit: p.pool_deposit.clone(), - maximum_epoch: p.maximum_epoch.clone(), - desired_number_of_stake_pools: p.desired_number_of_stake_pools.clone(), + minfee_a: p.minfee_a, + minfee_b: p.minfee_b, + max_block_body_size: p.max_block_body_size, + max_transaction_size: p.max_transaction_size, + max_block_header_size: p.max_block_header_size, + key_deposit: p.key_deposit, + pool_deposit: p.pool_deposit, + maximum_epoch: p.maximum_epoch, + desired_number_of_stake_pools: p.desired_number_of_stake_pools, pool_pledge_influence: p.pool_pledge_influence.as_ref().map(&map_unit_interval), expansion_rate: p.expansion_rate.as_ref().map(&map_unit_interval), treasury_growth_rate: p.treasury_growth_rate.as_ref().map(&map_unit_interval), - min_pool_cost: p.min_pool_cost.clone(), - coins_per_utxo_byte: p.ada_per_utxo_byte.clone(), + min_pool_cost: p.min_pool_cost, + coins_per_utxo_byte: p.ada_per_utxo_byte, lovelace_per_utxo_word: None, cost_models_for_script_languages: p .cost_models_for_script_languages @@ -636,19 +636,19 @@ fn map_conway_protocol_param_update(p: &conway::ProtocolParamUpdate) -> Box Result Ok(GovernanceAction::ParameterChange(ParameterChangeAction { previous_action_id: map_nullable_gov_action_id(id)?, protocol_param_update: map_conway_protocol_param_update(protocol_update), - script_hash: map_nullable(&|x: &ScriptHash| x.to_vec(), &script), + script_hash: map_nullable(|x: &ScriptHash| x.to_vec(), script), })) } @@ -683,7 +683,7 @@ fn map_governance_action(action: &conway::GovAction) -> Result rewards: HashMap::from_iter( withdrawals.iter().map(|(account, coin)| (account.to_vec(), *coin)), ), - script_hash: map_nullable(&|x: &ScriptHash| x.to_vec(), script), + script_hash: map_nullable(|x: &ScriptHash| x.to_vec(), script), }), ), @@ -709,7 +709,7 @@ fn map_governance_action(action: &conway::GovAction) -> Result conway::GovAction::NewConstitution(id, constitution) => { Ok(GovernanceAction::NewConstitution(NewConstitutionAction { previous_action_id: map_nullable_gov_action_id(id)?, - new_constitution: map_constitution(&constitution), + new_constitution: map_constitution(constitution), })) } @@ -731,15 +731,15 @@ pub fn map_alonzo_protocol_param_update( max_block_body_size: map_u32_to_u64(p.max_block_body_size), max_transaction_size: map_u32_to_u64(p.max_transaction_size), max_block_header_size: map_u32_to_u64(p.max_block_header_size), - key_deposit: p.key_deposit.clone(), - pool_deposit: p.pool_deposit.clone(), - maximum_epoch: p.maximum_epoch.clone(), + key_deposit: p.key_deposit, + pool_deposit: p.pool_deposit, + maximum_epoch: p.maximum_epoch, desired_number_of_stake_pools: map_u32_to_u64(p.desired_number_of_stake_pools), pool_pledge_influence: p.pool_pledge_influence.as_ref().map(&map_unit_interval), expansion_rate: p.expansion_rate.as_ref().map(&map_unit_interval), treasury_growth_rate: p.treasury_growth_rate.as_ref().map(&map_unit_interval), - min_pool_cost: p.min_pool_cost.clone(), - lovelace_per_utxo_word: p.ada_per_utxo_byte.clone(), // Pre Babbage (Represents cost per 8-byte word) + min_pool_cost: p.min_pool_cost, + lovelace_per_utxo_word: p.ada_per_utxo_byte, // Pre Babbage (Represents cost per 8-byte word) coins_per_utxo_byte: None, cost_models_for_script_languages: p .cost_models_for_script_languages @@ -789,16 +789,16 @@ pub fn map_babbage_protocol_param_update( max_block_body_size: map_u32_to_u64(p.max_block_body_size), max_transaction_size: map_u32_to_u64(p.max_transaction_size), max_block_header_size: map_u32_to_u64(p.max_block_header_size), - key_deposit: p.key_deposit.clone(), - pool_deposit: p.pool_deposit.clone(), - maximum_epoch: p.maximum_epoch.clone(), + key_deposit: p.key_deposit, + pool_deposit: p.pool_deposit, + maximum_epoch: p.maximum_epoch, desired_number_of_stake_pools: map_u32_to_u64(p.desired_number_of_stake_pools), pool_pledge_influence: p.pool_pledge_influence.as_ref().map(&map_unit_interval), expansion_rate: p.expansion_rate.as_ref().map(&map_unit_interval), treasury_growth_rate: p.treasury_growth_rate.as_ref().map(&map_unit_interval), - min_pool_cost: p.min_pool_cost.clone(), + min_pool_cost: p.min_pool_cost, lovelace_per_utxo_word: None, - coins_per_utxo_byte: p.ada_per_utxo_byte.clone(), + coins_per_utxo_byte: p.ada_per_utxo_byte, cost_models_for_script_languages: p .cost_models_for_script_languages .as_ref() @@ -899,7 +899,7 @@ pub fn map_all_governance_voting_procedures( { let action_id = map_gov_action_id(pallas_action_id)?; let vp = - map_single_governance_voting_procedure(vote_index as u32, &pallas_voting_procedure); + map_single_governance_voting_procedure(vote_index as u32, pallas_voting_procedure); single_voter.voting_procedures.insert(action_id, vp); } } diff --git a/common/src/address.rs b/common/src/address.rs index 4b0269f6..984af40e 100644 --- a/common/src/address.rs +++ b/common/src/address.rs @@ -329,26 +329,29 @@ impl ShelleyAddress { let mut data = Vec::new(); + let build_header = + |variant: u8| -> u8 { network_bits | (payment_bits << 4) | (variant << 5) }; + match &self.delegation { ShelleyAddressDelegationPart::None => { - let header = network_bits | (payment_bits << 4) | (3 << 5); + let header = build_header(3); data.push(header); data.extend(payment_hash); } ShelleyAddressDelegationPart::StakeKeyHash(hash) => { - let header = network_bits | (payment_bits << 4) | (0 << 5); + let header = build_header(0); data.push(header); data.extend(payment_hash); data.extend(hash); } ShelleyAddressDelegationPart::ScriptHash(hash) => { - let header = network_bits | (payment_bits << 4) | (1 << 5); + let header = build_header(1); data.push(header); data.extend(payment_hash); data.extend(hash); } ShelleyAddressDelegationPart::Pointer(pointer) => { - let header = network_bits | (payment_bits << 4) | (2 << 5); + let header = build_header(2); data.push(header); data.extend(payment_hash); diff --git a/common/src/byte_array.rs b/common/src/byte_array.rs index 6ff5f786..048a6849 100644 --- a/common/src/byte_array.rs +++ b/common/src/byte_array.rs @@ -23,10 +23,10 @@ macro_rules! declare_byte_array_type { type Error = FromHexError; fn from_hex>(hex: T) -> Result { - Ok(match Self::try_from(Vec::::from_hex(hex)?) { + match Self::try_from(Vec::::from_hex(hex)?) { Ok(b) => Ok(b), Err(_) => Err(FromHexError::InvalidStringLength), - }?) + } } } diff --git a/common/src/cip19.rs b/common/src/cip19.rs index 57a8a8da..cbc11a29 100644 --- a/common/src/cip19.rs +++ b/common/src/cip19.rs @@ -12,6 +12,12 @@ pub struct VarIntEncoder { } /// Variable-length integer encoder +impl Default for VarIntEncoder { + fn default() -> Self { + Self::new() + } +} + impl VarIntEncoder { /// Construct pub fn new() -> Self { diff --git a/common/src/crypto.rs b/common/src/crypto.rs index acce35c1..0e66038e 100644 --- a/common/src/crypto.rs +++ b/common/src/crypto.rs @@ -6,13 +6,13 @@ use cryptoxide::hashing::blake2b::Blake2b; /// Get a Blake2b-256 hash of a key pub fn keyhash_256(key: &[u8]) -> KeyHash { let mut context = Blake2b::<256>::new(); - context.update_mut(&key); + context.update_mut(key); context.finalize().to_vec() } /// Get a Blake2b-224 hash of a key pub fn keyhash_224(key: &[u8]) -> KeyHash { let mut context = Blake2b::<224>::new(); - context.update_mut(&key); + context.update_mut(key); context.finalize().to_vec() } diff --git a/common/src/hash.rs b/common/src/hash.rs index 3b8eb3ef..ab22e961 100644 --- a/common/src/hash.rs +++ b/common/src/hash.rs @@ -14,7 +14,7 @@ impl Serialize for Hash { where S: Serializer, { - serializer.serialize_str(&hex::encode(&self.0)) + serializer.serialize_str(&hex::encode(self.0)) } } diff --git a/common/src/ledger_state.rs b/common/src/ledger_state.rs index 998e6d63..d44c1fab 100644 --- a/common/src/ledger_state.rs +++ b/common/src/ledger_state.rs @@ -75,7 +75,7 @@ impl LedgerState { let entry = entry.with_context(|| "failed to read directory entry")?; let path = entry.path(); - if path.is_file() && path.extension().map_or(false, |ext| ext == "cbor") { + if path.is_file() && path.extension().is_some_and(|ext| ext == "cbor") { self.load_cbor_file(&path) .with_context(|| format!("failed to load CBOR file: {}", path.display()))?; } diff --git a/common/src/messages.rs b/common/src/messages.rs index 24ecfafc..2cd325a6 100644 --- a/common/src/messages.rs +++ b/common/src/messages.rs @@ -277,6 +277,7 @@ pub struct SPOStateMessage { /// Cardano message enum #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[allow(clippy::large_enum_variant)] pub enum CardanoMessage { BlockAvailable(RawBlockMessage), // Block body available BlockValidation(ValidationStatus), // Result of a block validation @@ -402,6 +403,7 @@ pub enum StateQuery { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[allow(clippy::large_enum_variant)] pub enum StateQueryResponse { Accounts(AccountsStateQueryResponse), Addresses(AddressStateQueryResponse), diff --git a/common/src/protocol_params.rs b/common/src/protocol_params.rs index 3c2a0283..a1dc56a5 100644 --- a/common/src/protocol_params.rs +++ b/common/src/protocol_params.rs @@ -182,8 +182,8 @@ impl From<&ShelleyParams> for PraosParams { (security_param as u64) * active_slots_coeff.denom() / active_slots_coeff.numer() * 4; Self { - security_param: security_param, - active_slots_coeff: active_slots_coeff, + security_param, + active_slots_coeff, epoch_length: params.epoch_length, max_kes_evolutions: params.max_kes_evolutions, max_lovelace_supply: params.max_lovelace_supply, @@ -191,8 +191,8 @@ impl From<&ShelleyParams> for PraosParams { slot_length: params.slot_length, slots_per_kes_period: params.slots_per_kes_period, - stability_window: stability_window, - randomness_stabilization_window: randomness_stabilization_window, + stability_window, + randomness_stabilization_window, } } } @@ -314,15 +314,13 @@ impl Nonces { // if prev_lab is Neutral then just return candidate // this is for second shelley epoch boundary (from 208 to 209 in mainnet) match prev_lab.tag { - NonceVariant::NeutralNonce => { - return Ok(candidate.clone()); - } + NonceVariant::NeutralNonce => Ok(candidate.clone()), NonceVariant::Nonce => { let Some(prev_lab_hash) = prev_lab.hash.as_ref() else { return Err(anyhow::anyhow!("Prev lab hash is not set")); }; let mut hasher = Blake2b::::new(); - hasher.update(&[&candidate_hash.clone()[..], &prev_lab_hash.clone()[..]].concat()); + hasher.update([&(*candidate_hash)[..], &(*prev_lab_hash)[..]].concat()); let hash: NonceHash = hasher.finalize().into(); Ok(Nonce::from(hash)) } @@ -344,7 +342,7 @@ impl Nonces { match current.hash.as_ref() { Some(nonce) => { let mut hasher = Blake2b::::new(); - hasher.update(&[&nonce.clone()[..], &nonce_vrf_output_hash[..]].concat()); + hasher.update([&(*nonce)[..], &nonce_vrf_output_hash[..]].concat()); let hash: NonceHash = hasher.finalize().into(); Ok(Nonce::from(hash)) } diff --git a/common/src/queries/blocks.rs b/common/src/queries/blocks.rs index 9128e3fb..1b5c2a33 100644 --- a/common/src/queries/blocks.rs +++ b/common/src/queries/blocks.rs @@ -155,9 +155,9 @@ impl Serialize for BlockInfo { state.serialize_field("fees", &self.fees)?; state.serialize_field( "block_vrf", - &self.block_vrf.clone().and_then(|vkey| vkey.to_bech32().ok()), + &self.block_vrf.and_then(|vkey| vkey.to_bech32().ok()), )?; - state.serialize_field("op_cert", &self.op_cert.clone().map(|v| hex::encode(v)))?; + state.serialize_field("op_cert", &self.op_cert.clone().map(hex::encode))?; state.serialize_field("op_cert_counter", &self.op_cert_counter)?; state.serialize_field("previous_block", &self.previous_block)?; state.serialize_field("next_block", &self.next_block)?; diff --git a/common/src/queries/governance.rs b/common/src/queries/governance.rs index c0c3d033..56104285 100644 --- a/common/src/queries/governance.rs +++ b/common/src/queries/governance.rs @@ -27,6 +27,7 @@ pub enum GovernanceStateQuery { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[allow(clippy::large_enum_variant)] pub enum GovernanceStateQueryResponse { DRepsList(DRepsList), DRepInfoWithDelegators(DRepInfoWithDelegators), diff --git a/common/src/queries/utils.rs b/common/src/queries/utils.rs index d385f11c..20ce4f4e 100644 --- a/common/src/queries/utils.rs +++ b/common/src/queries/utils.rs @@ -19,7 +19,7 @@ where let message = Arc::try_unwrap(raw_msg).unwrap_or_else(|arc| (*arc).clone()); - Ok(extractor(message)?) + extractor(message) } /// The outer option in the extractor return value is whether the response was handled by F @@ -33,7 +33,7 @@ where F: FnOnce(Message) -> Option, anyhow::Error>>, T: Serialize, { - let result = query_state(&context, topic, request_msg, |response| { + let result = query_state(context, topic, request_msg, |response| { match extractor(response) { Some(response) => response, None => Err(anyhow::anyhow!( diff --git a/common/src/snapshot/streaming_snapshot.rs b/common/src/snapshot/streaming_snapshot.rs index 26ac7cc5..1c6760ff 100644 --- a/common/src/snapshot/streaming_snapshot.rs +++ b/common/src/snapshot/streaming_snapshot.rs @@ -811,6 +811,35 @@ pub trait SnapshotCallbacks: fn on_complete(&mut self) -> Result<()>; } +// ----------------------------------------------------------------------------- +// Internal Types +// ----------------------------------------------------------------------------- + +#[expect(dead_code)] +struct ParsedMetadata { + epoch: u64, + treasury: u64, + reserves: u64, + pools: Vec, + dreps: Vec, + accounts: Vec, + blocks_previous_epoch: Vec, + blocks_current_epoch: Vec, + utxo_position: u64, +} + +#[expect(dead_code)] +struct ParsedMetadataWithoutUtxoPosition { + epoch: u64, + treasury: u64, + reserves: u64, + pools: Vec, + dreps: Vec, + accounts: Vec, + blocks_previous_epoch: Vec, + blocks_current_epoch: Vec, +} + // ----------------------------------------------------------------------------- // Streaming Parser // ----------------------------------------------------------------------------- @@ -1145,21 +1174,8 @@ impl StreamingSnapshotParser { } /// Parse metadata and structure, returning the UTXO position (for future chunked reading) - #[allow(dead_code)] - fn parse_metadata_and_find_utxos( - &self, - buffer: &[u8], - ) -> Result<( - u64, - u64, - u64, - Vec, - Vec, - Vec, - Vec, - Vec, - u64, - )> { + #[expect(dead_code)] + fn parse_metadata_and_find_utxos(&self, buffer: &[u8]) -> Result { let mut decoder = Decoder::new(buffer); let start_pos = decoder.position(); @@ -1261,7 +1277,7 @@ impl StreamingSnapshotParser { // Current position is right before the UTXO map [3][1][1][0] let utxo_position = start_pos as u64 + decoder.position() as u64; - Ok(( + Ok(ParsedMetadata { epoch, treasury, reserves, @@ -1271,24 +1287,15 @@ impl StreamingSnapshotParser { blocks_previous_epoch, blocks_current_epoch, utxo_position, - )) + }) } /// Parse metadata and structure (everything except UTXOs) (legacy) - #[allow(dead_code)] + #[expect(dead_code)] fn parse_metadata_and_structure( &self, buffer: &[u8], - ) -> Result<( - u64, - u64, - u64, - Vec, - Vec, - Vec, - Vec, - Vec, - )> { + ) -> Result { let mut decoder = Decoder::new(buffer); // Navigate to NewEpochState root array @@ -1383,7 +1390,7 @@ impl StreamingSnapshotParser { let accounts = Self::parse_dstate(&mut decoder).context("Failed to parse DState for accounts")?; - Ok(( + Ok(ParsedMetadataWithoutUtxoPosition { epoch, treasury, reserves, @@ -1392,7 +1399,7 @@ impl StreamingSnapshotParser { accounts, blocks_previous_epoch, blocks_current_epoch, - )) + }) } /// Parse DState for accounts (extracted from original parse method) @@ -1533,11 +1540,9 @@ impl StreamingSnapshotParser { let position_before = entry_decoder.position(); // Check for indefinite map break - if map_len == u64::MAX { - if matches!(entry_decoder.datatype(), Ok(Type::Break)) { - entries_processed = map_len; // Exit outer loop - break; - } + if map_len == u64::MAX && matches!(entry_decoder.datatype(), Ok(Type::Break)) { + entries_processed = map_len; // Exit outer loop + break; } // Try to parse one UTXO entry @@ -1555,7 +1560,7 @@ impl StreamingSnapshotParser { last_good_position = bytes_consumed; // Progress reporting - less frequent for better performance - if utxo_count % 1000000 == 0 { + if utxo_count.is_multiple_of(1000000) { let buffer_usage = buffer.len(); info!( " Streamed {} UTXOs, buffer: {} MB, max entry: {} bytes", diff --git a/common/src/stake_addresses.rs b/common/src/stake_addresses.rs index b47484c1..e2bf773d 100644 --- a/common/src/stake_addresses.rs +++ b/common/src/stake_addresses.rs @@ -105,6 +105,11 @@ impl StakeAddressMap { self.inner.len() } + #[inline] + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } + #[inline] pub fn is_registered(&self, stake_address: &StakeAddress) -> bool { self.get(stake_address).map(|sas| sas.registered).unwrap_or(false) @@ -139,7 +144,7 @@ impl StakeAddressMap { } /// Get Pool's Live Stake (same order as spos) - pub fn get_pools_live_stakes(&self, spos: &Vec) -> Vec { + pub fn get_pools_live_stakes(&self, spos: &[KeyHash]) -> Vec { let mut live_stakes_map = HashMap::::new(); // Collect the SPO keys and UTXO @@ -157,7 +162,7 @@ impl StakeAddressMap { }); spos.iter() - .map(|pool_operator| live_stakes_map.get(pool_operator).map(|v| *v).unwrap_or(0)) + .map(|pool_operator| live_stakes_map.get(pool_operator).copied().unwrap_or(0)) .collect() } @@ -314,7 +319,7 @@ impl StakeAddressMap { }); // Collect into a plain BTreeMap, so that it is ordered on output - spo_stakes.iter().map(|entry| (entry.key().clone(), entry.value().clone())).collect() + spo_stakes.iter().map(|entry| (entry.key().clone(), *entry.value())).collect() } /// Dump current Stake Pool Delegation Distribution State @@ -339,7 +344,7 @@ impl StakeAddressMap { /// delegated to each DRep, including the special "abstain" and "no confidence" dreps. pub fn generate_drdd( &self, - dreps: &Vec<(DRepCredential, Lovelace)>, + dreps: &[(DRepCredential, Lovelace)], ) -> DRepDelegationDistribution { let abstain = AtomicU64::new(0); let no_confidence = AtomicU64::new(0); diff --git a/common/src/state_history.rs b/common/src/state_history.rs index 9e19a4c7..645279cb 100644 --- a/common/src/state_history.rs +++ b/common/src/state_history.rs @@ -100,6 +100,11 @@ impl StateHistory { self.history.len() } + /// Get if state history is empty + pub fn is_empty(&self) -> bool { + self.history.is_empty() + } + /// Commit new state without checking the block number /// TODO: enhance block number logic to commit state without check (for bootstrapping) pub fn commit_forced(&mut self, state: S) { diff --git a/common/src/types.rs b/common/src/types.rs index 9559476c..e82a729b 100644 --- a/common/src/types.rs +++ b/common/src/types.rs @@ -38,9 +38,19 @@ impl From for NetworkId { /// Protocol era #[derive( - Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize, + Debug, + Default, + Clone, + Copy, + PartialEq, + Eq, + PartialOrd, + Ord, + serde::Serialize, + serde::Deserialize, )] pub enum Era { + #[default] Byron, Shelley, Allegra, @@ -50,12 +60,6 @@ pub enum Era { Conway, } -impl Default for Era { - fn default() -> Era { - Era::Byron - } -} - impl From for u8 { fn from(e: Era) -> u8 { match e { @@ -230,6 +234,10 @@ impl AssetName { self.len as usize } + pub fn is_empty(&self) -> bool { + self.len == 0 + } + pub fn as_slice(&self) -> &[u8] { &self.bytes[..self.len as usize] } @@ -347,7 +355,7 @@ impl From<&Value> for ValueDelta { let nas_delta = nas .iter() .map(|na| NativeAssetDelta { - name: na.name.clone(), + name: na.name, amount: na.amount as i64, }) .collect(); @@ -633,8 +641,7 @@ impl Credential { Err(anyhow!( "Incorrect credential {}, expected scriptHash- or keyHash- prefix", credential - ) - .into()) + )) } } @@ -1552,7 +1559,7 @@ pub struct Committee { impl Committee { pub fn is_empty(&self) -> bool { - return self.members.len() == 0; + self.members.is_empty() } } @@ -1623,7 +1630,7 @@ pub enum Voter { impl Voter { pub fn to_bech32(&self, hrp: &str, buf: &[u8]) -> String { let voter_hrp: Hrp = Hrp::parse(hrp).unwrap(); - bech32::encode::(voter_hrp, &buf) + bech32::encode::(voter_hrp, buf) .unwrap_or_else(|e| format!("Cannot convert {:?} to bech32: {e}", self)) } } @@ -1631,13 +1638,13 @@ impl Voter { impl Display for Voter { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - Voter::ConstitutionalCommitteeKey(h) => write!(f, "{}", self.to_bech32("cc_hot", &h)), + Voter::ConstitutionalCommitteeKey(h) => write!(f, "{}", self.to_bech32("cc_hot", h)), Voter::ConstitutionalCommitteeScript(s) => { - write!(f, "{}", self.to_bech32("cc_hot_script", &s)) + write!(f, "{}", self.to_bech32("cc_hot_script", s)) } - Voter::DRepKey(k) => write!(f, "{}", self.to_bech32("drep", &k)), - Voter::DRepScript(s) => write!(f, "{}", self.to_bech32("drep_script", &s)), - Voter::StakePoolKey(k) => write!(f, "{}", self.to_bech32("pool", &k)), + Voter::DRepKey(k) => write!(f, "{}", self.to_bech32("drep", k)), + Voter::DRepScript(s) => write!(f, "{}", self.to_bech32("drep_script", s)), + Voter::StakePoolKey(k) => write!(f, "{}", self.to_bech32("pool", k)), } } } @@ -1889,17 +1896,12 @@ impl AddressTotals { for (policy, assets) in &delta.assets { for a in assets { if a.amount > 0 { - Self::apply_asset( - &mut self.received.assets, - *policy, - a.name.clone(), - a.amount as u64, - ); + Self::apply_asset(&mut self.received.assets, *policy, a.name, a.amount as u64); } else if a.amount < 0 { Self::apply_asset( &mut self.sent.assets, *policy, - a.name.clone(), + a.name, a.amount.unsigned_abs(), ); }