Skip to content

Commit

Permalink
Fix new lints required by Rust 1.83 (#606)
Browse files Browse the repository at this point in the history
* cargo fix all new 1.83 lints except for static_mut_refs

* use LazyLock for CONTEXT

* allow static_mut_refs for wallet storage paths

* bump MSRV to 1.82 and use the recent is_none_or
  • Loading branch information
michaelsutton authored Nov 28, 2024
1 parent ea6b83e commit 73159f7
Show file tree
Hide file tree
Showing 55 changed files with 94 additions and 128 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ members = [
]

[workspace.package]
rust-version = "1.81.0"
rust-version = "1.82.0"
version = "0.15.3"
authors = ["Kaspa developers"]
license = "ISC"
Expand Down
10 changes: 1 addition & 9 deletions cli/src/modules/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,15 +86,7 @@ impl History {
}
};
let length = ids.size_hint().0;
let skip = if let Some(last) = last {
if last > length {
0
} else {
length - last
}
} else {
0
};
let skip = if let Some(last) = last { length.saturating_sub(last) } else { 0 };
let mut index = 0;
let page = 25;

Expand Down
2 changes: 1 addition & 1 deletion consensus/client/src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ impl Header {

impl TryCastFromJs for Header {
type Error = Error;
fn try_cast_from<'a, R>(value: &'a R) -> Result<Cast<Self>, Self::Error>
fn try_cast_from<'a, R>(value: &'a R) -> Result<Cast<'a, Self>, Self::Error>
where
R: AsRef<JsValue> + 'a,
{
Expand Down
2 changes: 1 addition & 1 deletion consensus/client/src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ impl AsRef<TransactionInput> for TransactionInput {

impl TryCastFromJs for TransactionInput {
type Error = Error;
fn try_cast_from<'a, R>(value: &'a R) -> std::result::Result<Cast<Self>, Self::Error>
fn try_cast_from<'a, R>(value: &'a R) -> std::result::Result<Cast<'a, Self>, Self::Error>
where
R: AsRef<JsValue> + 'a,
{
Expand Down
2 changes: 1 addition & 1 deletion consensus/client/src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ impl From<&TransactionOutput> for cctx::TransactionOutput {

impl TryCastFromJs for TransactionOutput {
type Error = Error;
fn try_cast_from<'a, R>(value: &'a R) -> std::result::Result<Cast<Self>, Self::Error>
fn try_cast_from<'a, R>(value: &'a R) -> std::result::Result<Cast<'a, Self>, Self::Error>
where
R: AsRef<JsValue> + 'a,
{
Expand Down
2 changes: 1 addition & 1 deletion consensus/client/src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ impl Transaction {

impl TryCastFromJs for Transaction {
type Error = Error;
fn try_cast_from<'a, R>(value: &'a R) -> std::result::Result<Cast<Self>, Self::Error>
fn try_cast_from<'a, R>(value: &'a R) -> std::result::Result<Cast<'a, Self>, Self::Error>
where
R: AsRef<JsValue> + 'a,
{
Expand Down
4 changes: 2 additions & 2 deletions consensus/client/src/utxo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ impl TryIntoUtxoEntryReferences for JsValue {

impl TryCastFromJs for UtxoEntry {
type Error = Error;
fn try_cast_from<'a, R>(value: &'a R) -> Result<Cast<Self>, Self::Error>
fn try_cast_from<'a, R>(value: &'a R) -> Result<Cast<'a, Self>, Self::Error>
where
R: AsRef<JsValue> + 'a,
{
Expand Down Expand Up @@ -405,7 +405,7 @@ impl TryFrom<JsValue> for UtxoEntries {

impl TryCastFromJs for UtxoEntryReference {
type Error = Error;
fn try_cast_from<'a, R>(value: &'a R) -> Result<Cast<Self>, Self::Error>
fn try_cast_from<'a, R>(value: &'a R) -> Result<Cast<'a, Self>, Self::Error>
where
R: AsRef<JsValue> + 'a,
{
Expand Down
5 changes: 2 additions & 3 deletions consensus/core/src/config/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub mod consensus {

/// Size of the **sampled** median time window (independent of BPS)
pub const MEDIAN_TIME_SAMPLED_WINDOW_SIZE: u64 =
((2 * NEW_TIMESTAMP_DEVIATION_TOLERANCE - 1) + PAST_MEDIAN_TIME_SAMPLE_INTERVAL - 1) / PAST_MEDIAN_TIME_SAMPLE_INTERVAL;
(2 * NEW_TIMESTAMP_DEVIATION_TOLERANCE - 1).div_ceil(PAST_MEDIAN_TIME_SAMPLE_INTERVAL);

//
// ~~~~~~~~~~~~~~~~~~~~~~~~~ Max difficulty target ~~~~~~~~~~~~~~~~~~~~~~~~~
Expand Down Expand Up @@ -71,8 +71,7 @@ pub mod consensus {
pub const DIFFICULTY_WINDOW_SAMPLE_INTERVAL: u64 = 4;

/// Size of the **sampled** difficulty window (independent of BPS)
pub const DIFFICULTY_SAMPLED_WINDOW_SIZE: u64 =
(NEW_DIFFICULTY_WINDOW_DURATION + DIFFICULTY_WINDOW_SAMPLE_INTERVAL - 1) / DIFFICULTY_WINDOW_SAMPLE_INTERVAL;
pub const DIFFICULTY_SAMPLED_WINDOW_SIZE: u64 = NEW_DIFFICULTY_WINDOW_DURATION.div_ceil(DIFFICULTY_WINDOW_SAMPLE_INTERVAL);

//
// ~~~~~~~~~~~~~~~~~~~ Finality & Pruning ~~~~~~~~~~~~~~~~~~~
Expand Down
4 changes: 2 additions & 2 deletions consensus/core/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ impl Serialize for NetworkId {

struct NetworkIdVisitor;

impl<'de> de::Visitor<'de> for NetworkIdVisitor {
impl de::Visitor<'_> for NetworkIdVisitor {
type Value = NetworkId;

fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
Expand Down Expand Up @@ -413,7 +413,7 @@ impl TryFrom<JsValue> for NetworkId {

impl TryCastFromJs for NetworkId {
type Error = NetworkIdError;
fn try_cast_from<'a, R>(value: &'a R) -> Result<Cast<Self>, Self::Error>
fn try_cast_from<'a, R>(value: &'a R) -> Result<Cast<'a, Self>, Self::Error>
where
R: AsRef<JsValue> + 'a,
{
Expand Down
6 changes: 3 additions & 3 deletions consensus/core/src/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ impl<'a, T: VerifiableTransaction> Iterator for PopulatedInputIterator<'a, T> {
}
}

impl<'a, T: VerifiableTransaction> ExactSizeIterator for PopulatedInputIterator<'a, T> {}
impl<T: VerifiableTransaction> ExactSizeIterator for PopulatedInputIterator<'_, T> {}

/// Represents a read-only referenced transaction along with fully populated UTXO entry data
pub struct PopulatedTransaction<'a> {
Expand All @@ -336,7 +336,7 @@ impl<'a> PopulatedTransaction<'a> {
}
}

impl<'a> VerifiableTransaction for PopulatedTransaction<'a> {
impl VerifiableTransaction for PopulatedTransaction<'_> {
fn tx(&self) -> &Transaction {
self.tx
}
Expand Down Expand Up @@ -368,7 +368,7 @@ impl<'a> ValidatedTransaction<'a> {
}
}

impl<'a> VerifiableTransaction for ValidatedTransaction<'a> {
impl VerifiableTransaction for ValidatedTransaction<'_> {
fn tx(&self) -> &Transaction {
self.tx
}
Expand Down
4 changes: 2 additions & 2 deletions consensus/core/src/tx/script_public_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ impl Serialize for ScriptPublicKey {
}
}

impl<'de: 'a, 'a> Deserialize<'de> for ScriptPublicKey {
impl<'de> Deserialize<'de> for ScriptPublicKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
Expand Down Expand Up @@ -374,7 +374,7 @@ impl BorshDeserialize for ScriptPublicKey {
type CastError = workflow_wasm::error::Error;
impl TryCastFromJs for ScriptPublicKey {
type Error = workflow_wasm::error::Error;
fn try_cast_from<'a, R>(value: &'a R) -> Result<Cast<Self>, Self::Error>
fn try_cast_from<'a, R>(value: &'a R) -> Result<Cast<'a, Self>, Self::Error>
where
R: AsRef<JsValue> + 'a,
{
Expand Down
1 change: 0 additions & 1 deletion consensus/src/model/services/reachability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,6 @@ impl<T: ReachabilityStoreReader + ?Sized> MTReachabilityService<T> {
/// a compromise where the lock is released every constant number of items.
///
/// TODO: decide if these alternatives require overall system benchmarking

struct BackwardChainIterator<T: ReachabilityStoreReader + ?Sized> {
store: Arc<RwLock<T>>,
current: Option<Hash>,
Expand Down
8 changes: 4 additions & 4 deletions consensus/src/model/stores/ghostdag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ impl GhostdagData {
pub fn ascending_mergeset_without_selected_parent<'a>(
&'a self,
store: &'a (impl GhostdagStoreReader + ?Sized),
) -> impl Iterator<Item = SortableBlock> + '_ {
) -> impl Iterator<Item = SortableBlock> + 'a {
self.mergeset_blues
.iter()
.skip(1) // Skip the selected parent
Expand All @@ -139,7 +139,7 @@ impl GhostdagData {
pub fn descending_mergeset_without_selected_parent<'a>(
&'a self,
store: &'a (impl GhostdagStoreReader + ?Sized),
) -> impl Iterator<Item = SortableBlock> + '_ {
) -> impl Iterator<Item = SortableBlock> + 'a {
self.mergeset_blues
.iter()
.skip(1) // Skip the selected parent
Expand Down Expand Up @@ -175,15 +175,15 @@ impl GhostdagData {
pub fn consensus_ordered_mergeset<'a>(
&'a self,
store: &'a (impl GhostdagStoreReader + ?Sized),
) -> impl Iterator<Item = Hash> + '_ {
) -> impl Iterator<Item = Hash> + 'a {
once(self.selected_parent).chain(self.ascending_mergeset_without_selected_parent(store).map(|s| s.hash))
}

/// Returns an iterator to the mergeset in topological consensus order without the selected parent
pub fn consensus_ordered_mergeset_without_selected_parent<'a>(
&'a self,
store: &'a (impl GhostdagStoreReader + ?Sized),
) -> impl Iterator<Item = Hash> + '_ {
) -> impl Iterator<Item = Hash> + 'a {
self.ascending_mergeset_without_selected_parent(store).map(|s| s.hash)
}

Expand Down
2 changes: 1 addition & 1 deletion consensus/src/model/stores/relations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ pub struct StagingRelationsStore<'a> {
children_deletions: BlockHashMap<BlockHashSet>,
}

impl<'a> ChildrenStore for StagingRelationsStore<'a> {
impl ChildrenStore for StagingRelationsStore<'_> {
fn insert_child(&mut self, _writer: impl DbWriter, parent: Hash, child: Hash) -> Result<(), StoreError> {
self.check_not_in_entry_deletions(parent)?;
self.check_not_in_children_deletions(parent, child)?; // We expect deletion to be permanent
Expand Down
1 change: 0 additions & 1 deletion consensus/src/model/stores/utxo_diffs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use rocksdb::WriteBatch;
/// blocks. However, once the diff is computed, it is permanent. This store has a relation to
/// block status, such that if a block has status `StatusUTXOValid` then it is expected to have
/// utxo diff data as well as utxo multiset data and acceptance data.

pub trait UtxoDiffsStoreReader {
fn get(&self, hash: Hash) -> Result<Arc<UtxoDiff>, StoreError>;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use crate::{
use kaspa_consensus_core::block::Block;
use kaspa_database::prelude::StoreResultExtensions;
use kaspa_hashes::Hash;
use kaspa_utils::option::OptionExtensions;
use std::sync::Arc;

impl BlockBodyProcessor {
Expand Down Expand Up @@ -45,7 +44,7 @@ impl BlockBodyProcessor {
.copied()
.filter(|parent| {
let status_option = statuses_read_guard.get(*parent).unwrap_option();
status_option.is_none_or_ex(|s| !s.has_block_body())
status_option.is_none_or(|s| !s.has_block_body())
})
.collect();
if !missing.is_empty() {
Expand Down
11 changes: 4 additions & 7 deletions consensus/src/processes/coinbase.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ impl CoinbaseManager {
// Precomputed subsidy by month table for the actual block per second rate
// Here values are rounded up so that we keep the same number of rewarding months as in the original 1 BPS table.
// In a 10 BPS network, the induced increase in total rewards is 51 KAS (see tests::calc_high_bps_total_rewards_delta())
let subsidy_by_month_table: SubsidyByMonthTable = core::array::from_fn(|i| (SUBSIDY_BY_MONTH_TABLE[i] + bps - 1) / bps);
let subsidy_by_month_table: SubsidyByMonthTable = core::array::from_fn(|i| SUBSIDY_BY_MONTH_TABLE[i].div_ceil(bps));
Self {
coinbase_payload_script_public_key_max_len,
max_coinbase_payload_len,
Expand Down Expand Up @@ -288,10 +288,7 @@ mod tests {
let total_rewards: u64 = pre_deflationary_rewards + SUBSIDY_BY_MONTH_TABLE.iter().map(|x| x * SECONDS_PER_MONTH).sum::<u64>();
let testnet_11_bps = TESTNET11_PARAMS.bps();
let total_high_bps_rewards_rounded_up: u64 = pre_deflationary_rewards
+ SUBSIDY_BY_MONTH_TABLE
.iter()
.map(|x| ((x + testnet_11_bps - 1) / testnet_11_bps * testnet_11_bps) * SECONDS_PER_MONTH)
.sum::<u64>();
+ SUBSIDY_BY_MONTH_TABLE.iter().map(|x| (x.div_ceil(testnet_11_bps) * testnet_11_bps) * SECONDS_PER_MONTH).sum::<u64>();

let cbm = create_manager(&TESTNET11_PARAMS);
let total_high_bps_rewards: u64 =
Expand All @@ -316,7 +313,7 @@ mod tests {
let cbm = create_manager(&network_id.into());
cbm.subsidy_by_month_table.iter().enumerate().for_each(|(i, x)| {
assert_eq!(
(SUBSIDY_BY_MONTH_TABLE[i] + cbm.bps() - 1) / cbm.bps(),
SUBSIDY_BY_MONTH_TABLE[i].div_ceil(cbm.bps()),
*x,
"{}: locally computed and precomputed values must match",
network_id
Expand Down Expand Up @@ -376,7 +373,7 @@ mod tests {
Test {
name: "after 32 halvings",
daa_score: params.deflationary_phase_daa_score + 32 * blocks_per_halving,
expected: ((DEFLATIONARY_PHASE_INITIAL_SUBSIDY / 2_u64.pow(32)) + cbm.bps() - 1) / cbm.bps(),
expected: (DEFLATIONARY_PHASE_INITIAL_SUBSIDY / 2_u64.pow(32)).div_ceil(cbm.bps()),
},
Test {
name: "just before subsidy depleted",
Expand Down
3 changes: 1 addition & 2 deletions consensus/src/processes/pruning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use crate::model::{
},
};
use kaspa_hashes::Hash;
use kaspa_utils::option::OptionExtensions;
use parking_lot::RwLock;

#[derive(Clone)]
Expand Down Expand Up @@ -213,7 +212,7 @@ impl<
let mut expected_pps_queue = VecDeque::new();
for current in self.reachability_service.backward_chain_iterator(hst, pruning_info.pruning_point, false) {
let current_header = self.headers_store.get_header(current).unwrap();
if expected_pps_queue.back().is_none_or_ex(|&&h| h != current_header.pruning_point) {
if expected_pps_queue.back().is_none_or(|&h| h != current_header.pruning_point) {
expected_pps_queue.push_back(current_header.pruning_point);
}
}
Expand Down
3 changes: 1 addition & 2 deletions consensus/src/processes/sync/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use kaspa_consensus_core::errors::sync::{SyncManagerError, SyncManagerResult};
use kaspa_database::prelude::StoreResultExtensions;
use kaspa_hashes::Hash;
use kaspa_math::uint::malachite_base::num::arithmetic::traits::CeilingLogBase2;
use kaspa_utils::option::OptionExtensions;
use parking_lot::RwLock;

use crate::model::{
Expand Down Expand Up @@ -191,7 +190,7 @@ impl<
}
}

if highest_with_body.is_none_or_ex(|&h| h == high) {
if highest_with_body.is_none_or(|h| h == high) {
return Ok(vec![]);
};

Expand Down
7 changes: 2 additions & 5 deletions consensus/src/test_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub fn block_from_precomputed_hash(hash: Hash, parents: Vec<Hash>) -> Block {
pub fn generate_random_utxos_from_script_public_key_pool(
rng: &mut SmallRng,
amount: usize,
script_public_key_pool: &Vec<ScriptPublicKey>,
script_public_key_pool: &[ScriptPublicKey],
) -> UtxoCollection {
let mut i = 0;
let mut collection = UtxoCollection::with_capacity(amount);
Expand All @@ -40,10 +40,7 @@ pub fn generate_random_outpoint(rng: &mut SmallRng) -> TransactionOutpoint {
TransactionOutpoint::new(generate_random_hash(rng), rng.gen::<u32>())
}

pub fn generate_random_utxo_from_script_public_key_pool(
rng: &mut SmallRng,
script_public_key_pool: &Vec<ScriptPublicKey>,
) -> UtxoEntry {
pub fn generate_random_utxo_from_script_public_key_pool(rng: &mut SmallRng, script_public_key_pool: &[ScriptPublicKey]) -> UtxoEntry {
UtxoEntry::new(
rng.gen_range(1..100_000), //we choose small amounts as to not overflow with large utxosets.
script_public_key_pool.choose(rng).expect("expected_script_public key").clone(),
Expand Down
5 changes: 2 additions & 3 deletions core/src/task/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,13 @@ impl AsyncRuntime {
}

/// Launch a tokio Runtime and run the top-level async objects

pub fn worker(self: &Arc<AsyncRuntime>, core: Arc<Core>) {
return tokio::runtime::Builder::new_multi_thread()
tokio::runtime::Builder::new_multi_thread()
.worker_threads(self.threads)
.enable_all()
.build()
.expect("Failed building the Runtime")
.block_on(async { self.worker_impl(core).await });
.block_on(async { self.worker_impl(core).await })
}

pub async fn worker_impl(self: &Arc<AsyncRuntime>, core: Arc<Core>) {
Expand Down
2 changes: 1 addition & 1 deletion crypto/addresses/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -506,7 +506,7 @@ impl<'de> Deserialize<'de> for Address {

impl TryCastFromJs for Address {
type Error = AddressError;
fn try_cast_from<'a, R>(value: &'a R) -> Result<Cast<Self>, Self::Error>
fn try_cast_from<'a, R>(value: &'a R) -> Result<Cast<'a, Self>, Self::Error>
where
R: AsRef<JsValue> + 'a,
{
Expand Down
2 changes: 1 addition & 1 deletion crypto/hashes/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ impl Hash {
type TryFromError = workflow_wasm::error::Error;
impl TryCastFromJs for Hash {
type Error = TryFromError;
fn try_cast_from<'a, R>(value: &'a R) -> Result<Cast<Self>, Self::Error>
fn try_cast_from<'a, R>(value: &'a R) -> Result<Cast<'a, Self>, Self::Error>
where
R: AsRef<JsValue> + 'a,
{
Expand Down
2 changes: 1 addition & 1 deletion crypto/muhash/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ pub struct MuHashElementBuilder<'a> {
element_hasher: MuHashElementHash,
}

impl<'a> HasherBase for MuHashElementBuilder<'a> {
impl HasherBase for MuHashElementBuilder<'_> {
fn update<A: AsRef<[u8]>>(&mut self, data: A) -> &mut Self {
self.element_hasher.write(data);
self
Expand Down
2 changes: 1 addition & 1 deletion crypto/txscript/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ impl<'a, T: VerifiableTransaction, Reused: SigHashReusedValues> TxScriptEngine<'

#[inline]
pub fn is_executing(&self) -> bool {
return self.cond_stack.is_empty() || *self.cond_stack.last().expect("Checked not empty") == OpCond::True;
self.cond_stack.is_empty() || *self.cond_stack.last().expect("Checked not empty") == OpCond::True
}

fn execute_opcode(&mut self, opcode: DynOpcodeImplementation<T, Reused>) -> Result<(), TxScriptError> {
Expand Down
Loading

1 comment on commit 73159f7

@jakingjack
Copy link

@jakingjack jakingjack commented on 73159f7 Nov 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello MS,

Thanks for your work !

In the rust 1.8.3 changelog ; they say that LLVM minimum is LLVM 18.
In the readme.md , the windows tutorial llvm version noted is 15, do we need to update to llvm 18 ?

If yes, could you update the readme ?

Thanks.

JD

Please sign in to comment.