diff --git a/Cargo.toml b/Cargo.toml index a9f4860f6a..63177a3782 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -184,7 +184,10 @@ as_ptr_cast_mut = "deny" as_underscore = "allow" big_endian_bytes = "allow" cognitive_complexity = "allow" +collapsible_else_if = "allow" +create_dir = "allow" decimal_literal_representation = "allow" +doc_markdown = "allow" doc_paragraphs_missing_punctuation = "allow" else_if_without_else = "allow" exhaustive_enums = "allow" @@ -199,6 +202,7 @@ integer_division = "allow" integer_division_remainder_used = "allow" little_endian_bytes = "allow" match_same_arms = "allow" +min_ident_chars = "allow" missing_docs_in_private_items = "allow" missing_panics_doc = "allow" missing_trait_methods = "allow" @@ -232,11 +236,7 @@ wildcard_enum_match_arm = "allow" # TODO: Maybe fix these (need to make a decision): cast_precision_loss = "allow" -collapsible_else_if = "allow" -create_dir = "allow" decimal_bitwise_operands = "allow" -default_trait_access = "allow" -empty_drop = "allow" error_impl_error = "allow" exit = "allow" field_scoped_visibility_modifiers = "allow" @@ -245,79 +245,52 @@ float_cmp = "allow" from_iter_instead_of_collect = "allow" get_unwrap = "allow" iter_over_hash_type = "allow" -impl_trait_in_params = "allow" infinite_loop = "allow" large_futures = "allow" large_stack_arrays = "allow" -large_types_passed_by_value = "allow" let_underscore_must_use = "allow" mem_forget = "allow" missing_asserts_for_indexing = "allow" missing_errors_doc = "allow" -modulo_arithmetic = "allow" must_use_candidate = "allow" option_option = "allow" panic = "allow" panic_in_result_fn = "allow" -partial_pub_fields = "allow" -pub_underscore_fields = "allow" rc_buffer = "allow" should_panic_without_expect = "allow" similar_names = "allow" +single_char_lifetime_names = "allow" stable_sort_primitive = "allow" string_slice = "allow" struct_excessive_bools = "allow" struct_field_names = "allow" -tests_outside_test_module = "allow" unimplemented = "allow" -unnecessary_box_returns = "allow" unnested_or_patterns = "allow" unused_self = "allow" unsafe_derive_deserialize = "allow" unseparated_literal_suffix = "allow" -# TODO: `.unwrap()` hould only be allowed in tests and benchmarks +# TODO: `.unwrap()` should only be allowed in tests and benchmarks, but it requires a separate file, see +# https://github.com/rust-lang/rust-clippy/issues/17201 unwrap_used = "allow" use_debug = "allow" # TODO: Fix everything below: -allow_attributes_without_reason = "allow" # TODO: It'd be nice to have this, but there is way too much code that uses it correctly that would be very unergonomic # to change. Waiting for a brave soul to do something about it eventually. arithmetic_side_effects = "allow" as_conversions = "allow" -assertions_on_result_states = "allow" -borrow_as_ptr = "allow" # TODO: It'd be nice to have this, but there is way too much code that uses it correctly that would be very unergonomic # to change. Waiting for a brave soul to do something about it eventually. cast_possible_truncation = "allow" cast_ptr_alignment = "allow" -doc_link_with_quotes = "allow" -doc_markdown = "allow" -ignore_without_reason = "allow" -ignored_unit_patterns = "allow" indexing_slicing = "allow" # TODO: Currently used for very context-specific workarounds for `generic_const_exprs` that would be awkward to rewrite items_after_statements = "allow" -many_single_char_names = "allow" -min_ident_chars = "allow" missing_assert_message = "allow" missing_inline_in_public_items = "allow" -multiple_inherent_impl = "allow" -needless_borrows_for_generic_args = "allow" -ref_patterns = "allow" return_self_not_must_use = "allow" -same_length_and_capacity = "allow" same_name_method = "allow" -# TODO: It will require either suppresing when macros are used or report upstream that macro-generated code should not -# be linted with this -semicolon_if_nothing_returned = "allow" -single_char_lifetime_names = "allow" single_call_fn = "allow" -trivially_copy_pass_by_ref = "allow" -unchecked_time_subtraction = "allow" -unused_async = "allow" -verbose_file_reads = "allow" -wildcard_imports = "allow" # TODO: False-positives that need to be fixed in Clippy # TODO: Fix once false-positives are resolved: https://github.com/rust-lang/rust-clippy/issues/16745 @@ -328,5 +301,15 @@ elidable_lifetime_names = "allow" non_zero_suggestions = "allow" # TODO: False-positives: https://github.com/rust-lang/rust-clippy/issues/17043 redundant_type_annotations = "allow" +# TODO: Waiting on https://github.com/paritytech/parity-scale-codec/pull/820 or https://github.com/rust-lang/rust-clippy/issues/17198 +ref_patterns = "allow" +# TODO: Waiting on https://github.com/paritytech/parity-scale-codec/pull/820 or https://github.com/rust-lang/rust-clippy/issues/17199 +semicolon_if_nothing_returned = "allow" +# TODO: False-positives: https://github.com/rust-lang/rust-clippy/issues/11024 +tests_outside_test_module = "allow" +# TODO: False-positives: https://github.com/rust-lang/rust-clippy/issues/17202 +unnecessary_box_returns = "allow" # TODO: Re-enable once false-positive is resolved: https://github.com/rust-lang/rust-clippy/issues/17039 unnecessary_safety_comment = "allow" +# TODO: https://github.com/rust-lang/rust-clippy/issues/5368#issuecomment-4665479346 +verbose_file_reads = "allow" diff --git a/crates/contracts/core/ab-contracts-common/src/metadata/decode.rs b/crates/contracts/core/ab-contracts-common/src/metadata/decode.rs index de3df3a70b..e08a8afc03 100644 --- a/crates/contracts/core/ab-contracts-common/src/metadata/decode.rs +++ b/crates/contracts/core/ab-contracts-common/src/metadata/decode.rs @@ -1,3 +1,9 @@ +// TODO: Remove once fixed +#![expect( + clippy::borrow_as_ptr, + reason = "https://github.com/NobodyXu/derive_destructure2/pull/6" +)] + use crate::metadata::ContractMetadataKind; use ab_io_type::metadata::{IoTypeDetails, IoTypeMetadataKind}; use core::mem::ManuallyDrop; diff --git a/crates/contracts/core/ab-contracts-macros-impl/src/contract.rs b/crates/contracts/core/ab-contracts-macros-impl/src/contract.rs index 99804fd73f..39f036e2ba 100644 --- a/crates/contracts/core/ab-contracts-macros-impl/src/contract.rs +++ b/crates/contracts/core/ab-contracts-macros-impl/src/contract.rs @@ -122,6 +122,7 @@ fn process_trait_definition(mut item_trait: ItemTrait) -> Result Result Result { )); } + // Needed for arguments + item_impl.attrs.extend([ + parse_quote! { #[expect(clippy::allow_attributes, reason = "Attribute below")] }, + parse_quote! { #[allow(clippy::trivially_copy_pass_by_ref, reason = "API requirement")] }, + ]); + let mut guest_ffis = Vec::with_capacity(item_impl.items.len()); let mut trait_ext_components = Vec::with_capacity(item_impl.items.len()); let mut contract_details = ContractDetails::default(); @@ -518,6 +525,7 @@ fn process_struct_impl(mut item_impl: ItemImpl) -> Result { #ext_trait /// FFI code generated by procedural macro + #[expect(clippy::wildcard_imports, reason = "Macro-generated")] pub mod ffi { use super::*; @@ -684,13 +692,18 @@ fn generate_extension_trait( .map(|components| &components.r#impl); quote! { + #[expect(clippy::wildcard_imports, reason = "Macro-generated")] use ffi::*; #[doc = #trait_doc] + #[automatically_derived] + #[expect(clippy::allow_attributes, reason = "Attribute below")] + #[allow(clippy::trivially_copy_pass_by_ref, reason = "API requirement")] pub trait #trait_name { #( #definitions )* } + #[automatically_derived] impl #trait_name for ::ab_contracts_macros::__private::Env<'_> { #( #impls )* } diff --git a/crates/contracts/core/ab-contracts-macros-impl/src/contract/method.rs b/crates/contracts/core/ab-contracts-macros-impl/src/contract/method.rs index 9e9f03929f..08a6c640cb 100644 --- a/crates/contracts/core/ab-contracts-macros-impl/src/contract/method.rs +++ b/crates/contracts/core/ab-contracts-macros-impl/src/contract/method.rs @@ -2,7 +2,9 @@ use crate::contract::common::{derive_ident_metadata, extract_ident_from_type}; use heck::{ToSnakeCase, ToUpperCamelCase}; use proc_macro2::{Ident, Literal, Span, TokenStream}; use quote::{format_ident, quote, quote_spanned}; +use syn::punctuated::Punctuated; use syn::spanned::Spanned; +use syn::token::Paren; use syn::{ Attribute, Error, GenericArgument, Meta, Pat, PatType, PathArguments, ReturnType, Signature, Token, Type, TypeTuple, @@ -73,8 +75,8 @@ enum MethodReturnType { impl MethodReturnType { fn unit_type() -> Type { Type::Tuple(TypeTuple { - paren_token: Default::default(), - elems: Default::default(), + paren_token: Paren::default(), + elems: Punctuated::default(), }) } @@ -983,10 +985,16 @@ impl MethodDetails { #[doc = #args_struct_doc] #[derive(::core::fmt::Debug)] #[repr(C)] + #[expect( + clippy::partial_pub_fields, + reason = "Not needed to be constructed publicly, but does need to always store \ + the lifetime" + )] + #[allow(clippy::pub_underscore_fields, reason = "Comes from user-provided arguments")] pub struct InternalArgs<'internal_args> { #( #internal_args_pointers )* - _phantom: ::core::marker::PhantomData<&'internal_args ()>, + lifetime: ::core::marker::PhantomData<&'internal_args ()>, } } }; @@ -1082,6 +1090,7 @@ impl MethodDetails { quote! { #[doc(hidden)] + #[expect(clippy::wildcard_imports, reason = "Macro-generated")] pub mod fn_pointer { use super::*; @@ -1260,9 +1269,11 @@ impl MethodDetails { #[doc = #args_struct_doc] #[derive(::core::fmt::Debug)] #[repr(C)] + #[allow(clippy::pub_underscore_fields, reason = "Comes from user-provided arguments")] pub struct #args_struct_name<'external_args> { #( #external_args_fields )* - lifetime: ::core::marker::PhantomData<&'external_args ()>, + /// Lifetime of the struct + pub _lifetime: ::core::marker::PhantomData<&'external_args ()>, } #[automatically_derived] @@ -1287,7 +1298,7 @@ impl MethodDetails { ) -> Self { Self { #( #method_args_fields )* - lifetime: ::core::marker::PhantomData, + _lifetime: ::core::marker::PhantomData, } } } @@ -1576,6 +1587,7 @@ impl MethodDetails { quote_spanned! {fn_sig.span() => #[allow(dead_code, reason = "Macro-generated")] #[allow(clippy::used_underscore_binding, reason = "Macro-generated")] + #[allow(clippy::semicolon_if_nothing_returned, reason = "Macro-generated")] fn #ext_method_name( #env_self, #method_context_arg diff --git a/crates/contracts/example/ab-example-contract-wallet/benches/example-contract-wallet.rs b/crates/contracts/example/ab-example-contract-wallet/benches/example-contract-wallet.rs index 33ff19340e..e377aca2a0 100644 --- a/crates/contracts/example/ab-example-contract-wallet/benches/example-contract-wallet.rs +++ b/crates/contracts/example/ab-example-contract-wallet/benches/example-contract-wallet.rs @@ -6,7 +6,7 @@ use ab_contracts_standards::tx_handler::TxHandler; use ab_core_primitives::address::Address; use ab_core_primitives::block::BlockRoot; use ab_core_primitives::shard::ShardIndex; -use ab_core_primitives::transaction::{Transaction, TransactionHeader, TransactionSlot}; +use ab_core_primitives::transaction::{Gas, Transaction, TransactionHeader, TransactionSlot}; use ab_example_contract_wallet::{ExampleWallet, ExampleWalletExt}; use ab_executor_native::NativeExecutor; use ab_io_type::bool::Bool; @@ -88,7 +88,7 @@ fn criterion_benchmark(c: &mut Criterion) { let header = TransactionHeader { version: 0, block_root: BlockRoot::default(), - gas_limit: Default::default(), + gas_limit: Gas::default(), contract: wallet_address, }; let payload = { diff --git a/crates/contracts/example/ab-example-contract-wallet/tests/basic.rs b/crates/contracts/example/ab-example-contract-wallet/tests/basic.rs index afb0b20add..7aff68640f 100644 --- a/crates/contracts/example/ab-example-contract-wallet/tests/basic.rs +++ b/crates/contracts/example/ab-example-contract-wallet/tests/basic.rs @@ -9,7 +9,7 @@ use ab_contracts_standards::tx_handler::TxHandler; use ab_core_primitives::address::Address; use ab_core_primitives::block::BlockRoot; use ab_core_primitives::shard::ShardIndex; -use ab_core_primitives::transaction::{Transaction, TransactionHeader, TransactionSlot}; +use ab_core_primitives::transaction::{Gas, Transaction, TransactionHeader, TransactionSlot}; use ab_example_contract_wallet::{ExampleWallet, ExampleWalletExt}; use ab_executor_native::NativeExecutor; use ab_io_type::bool::Bool; @@ -90,7 +90,7 @@ fn flip() { let header = TransactionHeader { version: 0, block_root: BlockRoot::default(), - gas_limit: Default::default(), + gas_limit: Gas::default(), contract: wallet_address, }; let payload = { diff --git a/crates/contracts/system/ab-system-contract-simple-wallet-base/src/payload.rs b/crates/contracts/system/ab-system-contract-simple-wallet-base/src/payload.rs index 3bd253627b..0e37f8f753 100644 --- a/crates/contracts/system/ab-system-contract-simple-wallet-base/src/payload.rs +++ b/crates/contracts/system/ab-system-contract-simple-wallet-base/src/payload.rs @@ -309,9 +309,7 @@ impl<'a> TransactionPayloadDecoder<'a> { map_context, } } -} -impl<'a> TransactionPayloadDecoder<'a> { /// Decode the next method (if any) in the payload #[cfg_attr(feature = "no-panic", no_panic::no_panic)] pub fn decode_next_method( diff --git a/crates/execution/ab-riscv-interpreter/src/rv32/c/zca/tests.rs b/crates/execution/ab-riscv-interpreter/src/rv32/c/zca/tests.rs index ca2937b0f1..5970acc971 100644 --- a/crates/execution/ab-riscv-interpreter/src/rv32/c/zca/tests.rs +++ b/crates/execution/ab-riscv-interpreter/src/rv32/c/zca/tests.rs @@ -1,5 +1,8 @@ use crate::rv32::test_utils::{TEST_BASE_ADDR, execute, initialize_state}; -use crate::{ExecutableInstruction, ExecutionError, ProgramCounter, RegisterFile, VirtualMemory}; +use crate::{ + ExecutableInstruction, ExecutionError, ProgramCounter, RegisterFile, Rs1Rs2OperandValues, + VirtualMemory, +}; use ab_riscv_primitives::prelude::*; // C.ADDI4SPN @@ -112,7 +115,7 @@ fn test_cjal_negative_offset() { }; let (rd, rd_value) = instruction .execute( - Default::default(), + Rs1Rs2OperandValues::default(), &mut state.regs, &mut state.ext_state, &mut state.memory, diff --git a/crates/execution/ab-riscv-interpreter/src/rv32/m.rs b/crates/execution/ab-riscv-interpreter/src/rv32/m.rs index af7f312832..2347c0dbe5 100644 --- a/crates/execution/ab-riscv-interpreter/src/rv32/m.rs +++ b/crates/execution/ab-riscv-interpreter/src/rv32/m.rs @@ -92,6 +92,10 @@ where Self::Rem { rd, rs1: _, rs2: _ } => { let dividend = rs1_value.cast_signed(); let divisor = rs2_value.cast_signed(); + #[expect( + clippy::modulo_arithmetic, + reason = "This is what the code is supposed to do" + )] let value = if divisor == 0 { dividend } else if dividend == i32::MIN && divisor == -1 { diff --git a/crates/execution/ab-riscv-interpreter/src/rv64/m.rs b/crates/execution/ab-riscv-interpreter/src/rv64/m.rs index 4a4128902b..4e08074b1a 100644 --- a/crates/execution/ab-riscv-interpreter/src/rv64/m.rs +++ b/crates/execution/ab-riscv-interpreter/src/rv64/m.rs @@ -92,6 +92,10 @@ where Self::Rem { rd, rs1: _, rs2: _ } => { let dividend = rs1_value.cast_signed(); let divisor = rs2_value.cast_signed(); + #[expect( + clippy::modulo_arithmetic, + reason = "This is what the code is supposed to do" + )] let value = if divisor == 0 { dividend } else if dividend == i64::MIN && divisor == -1 { @@ -140,6 +144,10 @@ where Self::Remw { rd, rs1: _, rs2: _ } => { let dividend = rs1_value as i32; let divisor = rs2_value as i32; + #[expect( + clippy::modulo_arithmetic, + reason = "This is what the code is supposed to do" + )] let value = if divisor == 0 { i64::from(dividend).cast_unsigned() } else if dividend == i32::MIN && divisor == -1 { diff --git a/crates/execution/ab-riscv-interpreter/src/v/zvexx/config/tests.rs b/crates/execution/ab-riscv-interpreter/src/v/zvexx/config/tests.rs index dfffd4f133..a8d56fbfa7 100644 --- a/crates/execution/ab-riscv-interpreter/src/v/zvexx/config/tests.rs +++ b/crates/execution/ab-riscv-interpreter/src/v/zvexx/config/tests.rs @@ -707,7 +707,7 @@ fn vsetvli_fails_when_vector_disabled() { state.ext_state.set_vector_allowed(false); let result = execute(&mut state); - assert!(result.is_err()); + result.unwrap_err(); } #[test] @@ -724,7 +724,7 @@ fn vsetivli_fails_when_vector_disabled() { state.ext_state.set_vector_allowed(false); let result = execute(&mut state); - assert!(result.is_err()); + result.unwrap_err(); } #[test] @@ -743,7 +743,7 @@ fn vsetvl_fails_when_vector_disabled() { state.ext_state.set_vector_allowed(false); let result = execute(&mut state); - assert!(result.is_err()); + result.unwrap_err(); } // CSR read/write via prepare_csr_read/prepare_csr_write @@ -815,7 +815,7 @@ fn prepare_csr_write_rejects_read_only_vl() { 42, &mut output, ); - assert!(result.is_err()); + result.unwrap_err(); } #[test] @@ -830,7 +830,7 @@ fn prepare_csr_write_rejects_read_only_vtype() { 42, &mut output, ); - assert!(result.is_err()); + result.unwrap_err(); } #[test] @@ -845,7 +845,7 @@ fn prepare_csr_write_rejects_read_only_vlenb() { 42, &mut output, ); - assert!(result.is_err()); + result.unwrap_err(); } #[test] diff --git a/crates/execution/ab-riscv-interpreter/src/v/zvexx/fixed_point/tests.rs b/crates/execution/ab-riscv-interpreter/src/v/zvexx/fixed_point/tests.rs index 9e1691f3ed..614d45b399 100644 --- a/crates/execution/ab-riscv-interpreter/src/v/zvexx/fixed_point/tests.rs +++ b/crates/execution/ab-riscv-interpreter/src/v/zvexx/fixed_point/tests.rs @@ -2175,7 +2175,7 @@ fn vsaddu_aligned_m4_ok() { write_elem(&mut state, VReg::V8, i, Vsew::E8, 1); write_elem(&mut state, VReg::V12, i, Vsew::E8, 2); } - let result = exec( + exec( &mut state, ZveXxFixedPointInstruction::VsadduVv { vd: VReg::V4, @@ -2185,8 +2185,8 @@ fn vsaddu_aligned_m4_ok() { rs1: Reg::Zero, rs2: Reg::Zero, }, - ); - assert!(result.is_ok()); + ) + .unwrap(); } // vs_dirty_count and vstart reset diff --git a/crates/execution/ab-riscv-interpreter/src/v/zvexx/muldiv/tests.rs b/crates/execution/ab-riscv-interpreter/src/v/zvexx/muldiv/tests.rs index ac7fba229e..2f08274fd2 100644 --- a/crates/execution/ab-riscv-interpreter/src/v/zvexx/muldiv/tests.rs +++ b/crates/execution/ab-riscv-interpreter/src/v/zvexx/muldiv/tests.rs @@ -1040,7 +1040,7 @@ fn vwmulu_mf2_no_false_overlap_rejection() { let mut state = setup(2, Vsew::E8, Vlmul::Mf2); write_elem(&mut state, VReg::V2, 0, Vsew::E8, 5); write_elem(&mut state, VReg::V4, 0, Vsew::E8, 6); - let result = exec( + exec( &mut state, ZveXxMulDivInstruction::VwmuluVv { vd: VReg::V8, @@ -1050,8 +1050,8 @@ fn vwmulu_mf2_no_false_overlap_rejection() { rs1: Reg::Zero, rs2: Reg::Zero, }, - ); - assert!(result.is_ok()); + ) + .unwrap(); assert_eq!(read_wide_elem(&state, VReg::V8, 0, Vsew::E8), 30u64); } @@ -1110,7 +1110,7 @@ fn vwmulu_m1_vs2_in_upper_dest_reg_is_legal() { write_elem(&mut state, VReg::V5, i, Vsew::E8, (i + 1) as u64); write_elem(&mut state, VReg::V2, i, Vsew::E8, 2); } - let result = exec( + exec( &mut state, ZveXxMulDivInstruction::VwmuluVv { vd: VReg::V4, @@ -1120,8 +1120,8 @@ fn vwmulu_m1_vs2_in_upper_dest_reg_is_legal() { rs1: Reg::Zero, rs2: Reg::Zero, }, - ); - assert!(result.is_ok()); + ) + .unwrap(); for i in 0..4usize { assert_eq!( read_wide_elem(&state, VReg::V4, i, Vsew::E8), @@ -1141,7 +1141,7 @@ fn vwmulu_m1_vs1_in_upper_dest_reg_is_legal() { write_elem(&mut state, VReg::V7, i, Vsew::E8, (i + 1) as u64); write_elem(&mut state, VReg::V11, i, Vsew::E8, 3); } - let result = exec( + exec( &mut state, ZveXxMulDivInstruction::VwmuluVv { vd: VReg::V10, @@ -1151,8 +1151,8 @@ fn vwmulu_m1_vs1_in_upper_dest_reg_is_legal() { rs1: Reg::Zero, rs2: Reg::Zero, }, - ); - assert!(result.is_ok()); + ) + .unwrap(); for i in 0..4usize { assert_eq!( read_wide_elem(&state, VReg::V10, i, Vsew::E8), @@ -1212,7 +1212,7 @@ fn vwmulu_m2_top_half_overlap_is_legal() { // With M2, vd=V8 occupies V8..V12. vs1=V10 occupies exactly the top half (V10+V11) of the // destination group -> legal per spec §5.2. let mut state = setup(4, Vsew::E8, Vlmul::M2); - let result = exec( + exec( &mut state, ZveXxMulDivInstruction::VwmuluVv { vd: VReg::V8, @@ -1222,8 +1222,8 @@ fn vwmulu_m2_top_half_overlap_is_legal() { rs1: Reg::Zero, rs2: Reg::Zero, }, - ); - assert!(result.is_ok()); + ) + .unwrap(); } // vwmul (signed widening) diff --git a/crates/execution/ab-riscv-interpreter/src/v/zvexx/muldiv/zvexx_muldiv_helpers.rs b/crates/execution/ab-riscv-interpreter/src/v/zvexx/muldiv/zvexx_muldiv_helpers.rs index da2399af96..3dc9942fd6 100644 --- a/crates/execution/ab-riscv-interpreter/src/v/zvexx/muldiv/zvexx_muldiv_helpers.rs +++ b/crates/execution/ab-riscv-interpreter/src/v/zvexx/muldiv/zvexx_muldiv_helpers.rs @@ -533,6 +533,10 @@ pub fn sdiv(a: u64, b: u64, sew: Vsew) -> u64 { /// - Signed overflow (MIN % −1): remainder = 0 #[inline(always)] #[doc(hidden)] +#[expect( + clippy::modulo_arithmetic, + reason = "This is what the code is supposed to do" +)] pub fn srem(a: u64, b: u64, sew: Vsew) -> u64 { let sa = sign_extend(a, sew); let sb = sign_extend(b, sew); diff --git a/crates/execution/ab-riscv-interpreter/src/zicsr/tests.rs b/crates/execution/ab-riscv-interpreter/src/zicsr/tests.rs index 47f43733bf..04db36b973 100644 --- a/crates/execution/ab-riscv-interpreter/src/zicsr/tests.rs +++ b/crates/execution/ab-riscv-interpreter/src/zicsr/tests.rs @@ -822,7 +822,7 @@ fn test_csrrw_read_only_csr_is_rejected() { let result = execute(&mut state); - assert!(result.is_err()); + result.unwrap_err(); assert_eq!(state.ext_state.read_csr(RO_CSR).unwrap(), 0x1234); } @@ -842,7 +842,7 @@ fn test_csrrwi_read_only_csr_is_rejected() { let result = execute(&mut state); - assert!(result.is_err()); + result.unwrap_err(); assert_eq!(state.ext_state.read_csr(RO_CSR).unwrap(), 0x1234); } @@ -863,7 +863,7 @@ fn test_csrrs_read_only_csr_with_nonzero_rs1_is_rejected() { let result = execute(&mut state); - assert!(result.is_err()); + result.unwrap_err(); assert_eq!(state.ext_state.read_csr(RO_CSR).unwrap(), 0x1234); } @@ -884,7 +884,7 @@ fn test_csrrc_read_only_csr_with_nonzero_rs1_is_rejected() { let result = execute(&mut state); - assert!(result.is_err()); + result.unwrap_err(); assert_eq!(state.ext_state.read_csr(RO_CSR).unwrap(), 0x1234); } @@ -904,7 +904,7 @@ fn test_csrrsi_read_only_csr_with_nonzero_zimm_is_rejected() { let result = execute(&mut state); - assert!(result.is_err()); + result.unwrap_err(); assert_eq!(state.ext_state.read_csr(RO_CSR).unwrap(), 0x1234); } @@ -924,7 +924,7 @@ fn test_csrrci_read_only_csr_with_nonzero_zimm_is_rejected() { let result = execute(&mut state); - assert!(result.is_err()); + result.unwrap_err(); assert_eq!(state.ext_state.read_csr(RO_CSR).unwrap(), 0x1234); } diff --git a/crates/execution/ab-riscv-macros/src/build/enum_definition.rs b/crates/execution/ab-riscv-macros/src/build/enum_definition.rs index a4924209ea..d8120cf2a4 100644 --- a/crates/execution/ab-riscv-macros/src/build/enum_definition.rs +++ b/crates/execution/ab-riscv-macros/src/build/enum_definition.rs @@ -1026,7 +1026,7 @@ pub(super) fn process_pending_enum_definitions( last_pending_enums_count = pending_enums.len(); for PendingEnumDefinition { original_item_enum } in pending_enums { - process_enum_definition(original_item_enum, out_dir, state)? + process_enum_definition(original_item_enum, out_dir, state)?; } } diff --git a/crates/execution/ab-riscv-macros/src/build/enum_impl.rs b/crates/execution/ab-riscv-macros/src/build/enum_impl.rs index 5d20bdff66..20a12c4510 100644 --- a/crates/execution/ab-riscv-macros/src/build/enum_impl.rs +++ b/crates/execution/ab-riscv-macros/src/build/enum_impl.rs @@ -15,6 +15,7 @@ use std::collections::{HashMap, HashSet}; use std::path::Path; use std::rc::Rc; use std::{env, fs, iter, mem}; +use syn::token::DotDot; use syn::{ Block, Expr, Fields, FnArg, Ident, ImplItem, ItemImpl, Member, Pat, PatRest, Stmt, Type, parse_file, parse_quote, parse_str, @@ -606,7 +607,7 @@ pub(super) fn process_enum_display_impl( } pat_struct.rest.replace(PatRest { attrs: vec![], - dot2_token: Default::default(), + dot2_token: DotDot::default(), }); } diff --git a/crates/execution/ab-riscv-macros/src/build/enum_impl/add_missing_fields.rs b/crates/execution/ab-riscv-macros/src/build/enum_impl/add_missing_fields.rs index 65604ebbad..cb9efbc885 100644 --- a/crates/execution/ab-riscv-macros/src/build/enum_impl/add_missing_fields.rs +++ b/crates/execution/ab-riscv-macros/src/build/enum_impl/add_missing_fields.rs @@ -1,4 +1,5 @@ use syn::punctuated::Punctuated; +use syn::token::Brace; use syn::visit_mut::VisitMut; use syn::{ Block, Expr, ExprPath, ExprStruct, Ident, Member, Path, PathArguments, PathSegment, parse_quote, @@ -99,7 +100,7 @@ fn try_convert_unit_to_struct(expr_path: &ExprPath) -> Option { attrs: expr_path.attrs.clone(), qself: None, path, - brace_token: Default::default(), + brace_token: Brace::default(), fields, dot2_token: None, rest: None, diff --git a/crates/execution/ab-riscv-macros/src/build/execution_impl/extract_matches.rs b/crates/execution/ab-riscv-macros/src/build/execution_impl/extract_matches.rs index 8186ceadef..3f1a65a220 100644 --- a/crates/execution/ab-riscv-macros/src/build/execution_impl/extract_matches.rs +++ b/crates/execution/ab-riscv-macros/src/build/execution_impl/extract_matches.rs @@ -1,6 +1,6 @@ use quote::{ToTokens, quote}; use std::{iter, mem}; -use syn::token::Semi; +use syn::token::{DotDot, Semi}; use syn::{ Arm, Block, Expr, ExprBlock, ExprMatch, Ident, Member, Pat, PatRest, PathArguments, Stmt, parse_quote, @@ -93,7 +93,7 @@ fn get_variant_ident_and_block(arm: &Arm, add_ok: bool) -> anyhow::Result<(Ident } pat_struct.rest.replace(PatRest { attrs: vec![], - dot2_token: Default::default(), + dot2_token: DotDot::default(), }); } } diff --git a/crates/farmer/ab-farmer-components/benches/auditing.rs b/crates/farmer/ab-farmer-components/benches/auditing.rs index d0e0015e1e..d289a69eda 100644 --- a/crates/farmer/ab-farmer-components/benches/auditing.rs +++ b/crates/farmer/ab-farmer-components/benches/auditing.rs @@ -20,6 +20,7 @@ use ab_farmer_components::shard_commitment::{ }; use ab_proof_of_space::Table; use ab_proof_of_space::chia::ChiaTable; +use async_lock::Mutex as AsyncMutex; use chacha20::ChaCha8Rng; use chacha20::rand_core::{Rng, SeedableRng}; use criterion::{Criterion, Throughput, criterion_group, criterion_main}; @@ -29,6 +30,7 @@ use std::fs::OpenOptions; use std::hint::black_box; use std::io::Write; use std::num::{NonZeroU16, NonZeroU64}; +use std::sync::atomic::AtomicBool; use std::{env, fs, iter, slice}; type PosTable = ChiaTable; @@ -63,10 +65,7 @@ pub fn criterion_benchmark(c: &mut Criterion) { let mut archiver = Archiver::new(ShardIndex::BEACON_CHAIN, erasure_coding.clone()); let table_generator = PosTable::generator(); let archived_history_segment = archiver - .add_block( - AsRef::<[u8]>::as_ref(input.as_ref()).to_vec(), - Default::default(), - ) + .add_block(AsRef::<[u8]>::as_ref(input.as_ref()).to_vec(), Vec::new()) .unwrap() .archived_segments .into_iter() @@ -145,9 +144,9 @@ pub fn criterion_benchmark(c: &mut Criterion) { records_encoder: &mut CpuRecordsEncoder::::new( slice::from_ref(&table_generator), &erasure_coding, - &Default::default(), + &AsyncMutex::default(), ), - abort_early: &Default::default(), + abort_early: &AtomicBool::new(false), })) .unwrap(); diff --git a/crates/farmer/ab-farmer-components/benches/plotting.rs b/crates/farmer/ab-farmer-components/benches/plotting.rs index 590cc619cb..012efbc257 100644 --- a/crates/farmer/ab-farmer-components/benches/plotting.rs +++ b/crates/farmer/ab-farmer-components/benches/plotting.rs @@ -11,12 +11,14 @@ use ab_farmer_components::sector::sector_size; use ab_farmer_components::shard_commitment::derive_shard_commitments_root; use ab_proof_of_space::Table; use ab_proof_of_space::chia::ChiaTable; +use async_lock::Mutex as AsyncMutex; use chacha20::ChaCha8Rng; use chacha20::rand_core::{Rng, SeedableRng}; use criterion::{Criterion, Throughput, criterion_group, criterion_main}; use futures::executor::block_on; use std::hint::black_box; use std::num::NonZeroU64; +use std::sync::atomic::AtomicBool; use std::{array, env}; type PosTable = ChiaTable; @@ -41,10 +43,7 @@ fn criterion_benchmark(c: &mut Criterion) { let mut archiver = Archiver::new(ShardIndex::BEACON_CHAIN, erasure_coding.clone()); let table_generators = array::repeat::<_, 8>(PosTable::generator()); let archived_history_segment = archiver - .add_block( - AsRef::<[u8]>::as_ref(input.as_ref()).to_vec(), - Default::default(), - ) + .add_block(AsRef::<[u8]>::as_ref(input.as_ref()).to_vec(), Vec::new()) .unwrap() .archived_segments .into_iter() @@ -85,9 +84,9 @@ fn criterion_benchmark(c: &mut Criterion) { records_encoder: black_box(&mut CpuRecordsEncoder::::new( &table_generators, &erasure_coding, - &Default::default(), + &AsyncMutex::default(), )), - abort_early: &Default::default(), + abort_early: &AtomicBool::new(false), })) .unwrap(); }); diff --git a/crates/farmer/ab-farmer-components/benches/proving.rs b/crates/farmer/ab-farmer-components/benches/proving.rs index fbd8c105e1..f2aa7091ac 100644 --- a/crates/farmer/ab-farmer-components/benches/proving.rs +++ b/crates/farmer/ab-farmer-components/benches/proving.rs @@ -23,6 +23,7 @@ use ab_farmer_components::shard_commitment::{ }; use ab_proof_of_space::chia::ChiaTable; use ab_proof_of_space::{Table, TableGenerator}; +use async_lock::Mutex as AsyncMutex; use chacha20::ChaCha8Rng; use chacha20::rand_core::{Rng, SeedableRng}; use criterion::{BatchSize, Criterion, Throughput, criterion_group, criterion_main}; @@ -32,6 +33,7 @@ use std::fs::OpenOptions; use std::hint::black_box; use std::io::Write; use std::num::{NonZeroU16, NonZeroU64}; +use std::sync::atomic::AtomicBool; use std::{env, fs, iter, slice}; type PosTable = ChiaTable; @@ -66,10 +68,7 @@ pub fn criterion_benchmark(c: &mut Criterion) { let mut archiver = Archiver::new(ShardIndex::BEACON_CHAIN, erasure_coding.clone()); let table_generator = PosTable::generator(); let archived_history_segment = archiver - .add_block( - AsRef::<[u8]>::as_ref(input.as_ref()).to_vec(), - Default::default(), - ) + .add_block(AsRef::<[u8]>::as_ref(input.as_ref()).to_vec(), Vec::new()) .unwrap() .archived_segments .into_iter() @@ -147,9 +146,9 @@ pub fn criterion_benchmark(c: &mut Criterion) { records_encoder: &mut CpuRecordsEncoder::::new( slice::from_ref(&table_generator), erasure_coding, - &Default::default(), + &AsyncMutex::default(), ), - abort_early: &Default::default(), + abort_early: &AtomicBool::new(false), })) .unwrap(); diff --git a/crates/farmer/ab-farmer-components/benches/reading.rs b/crates/farmer/ab-farmer-components/benches/reading.rs index 644ecd2668..e86ba0c8f6 100644 --- a/crates/farmer/ab-farmer-components/benches/reading.rs +++ b/crates/farmer/ab-farmer-components/benches/reading.rs @@ -18,6 +18,7 @@ use ab_farmer_components::shard_commitment::derive_shard_commitments_root; use ab_farmer_components::{FarmerProtocolInfo, ReadAt, ReadAtSync}; use ab_proof_of_space::Table; use ab_proof_of_space::chia::ChiaTable; +use async_lock::Mutex as AsyncMutex; use chacha20::ChaCha8Rng; use chacha20::rand_core::{Rng, SeedableRng}; use criterion::{Criterion, Throughput, criterion_group, criterion_main}; @@ -27,6 +28,7 @@ use std::fs::OpenOptions; use std::hint::black_box; use std::io::Write; use std::num::NonZeroU64; +use std::sync::atomic::AtomicBool; use std::{env, fs, slice}; type PosTable = ChiaTable; @@ -59,10 +61,7 @@ pub fn criterion_benchmark(c: &mut Criterion) { let mut archiver = Archiver::new(ShardIndex::BEACON_CHAIN, erasure_coding.clone()); let table_generator = PosTable::generator(); let archived_history_segment = archiver - .add_block( - AsRef::<[u8]>::as_ref(input.as_ref()).to_vec(), - Default::default(), - ) + .add_block(AsRef::<[u8]>::as_ref(input.as_ref()).to_vec(), Vec::new()) .unwrap() .archived_segments .into_iter() @@ -138,9 +137,9 @@ pub fn criterion_benchmark(c: &mut Criterion) { records_encoder: &mut CpuRecordsEncoder::::new( slice::from_ref(&table_generator), &erasure_coding, - &Default::default(), + &AsyncMutex::default(), ), - abort_early: &Default::default(), + abort_early: &AtomicBool::new(false), })) .unwrap(); diff --git a/crates/farmer/ab-farmer-components/src/auditing.rs b/crates/farmer/ab-farmer-components/src/auditing.rs index eb73c52433..c51b971c41 100644 --- a/crates/farmer/ab-farmer-components/src/auditing.rs +++ b/crates/farmer/ab-farmer-components/src/auditing.rs @@ -56,7 +56,7 @@ pub(crate) struct ChunkCandidate { /// This is primarily helpful in test environment, prefer [`audit_plot_sync`] for auditing real /// plots. // TODO: Struct for arguments -#[expect(clippy::too_many_arguments)] +#[expect(clippy::too_many_arguments, reason = "TODO")] pub fn audit_sector_sync<'a, Sector>( public_key_hash: &'a Blake3Hash, shard_commitments_roots_cache: &'a ShardCommitmentsRootsCache, @@ -125,7 +125,7 @@ where /// Plot is assumed to contain concatenated series of sectors as created by functions in /// [`plotting`](crate::plotting) module earlier. // TODO: Struct for arguments -#[expect(clippy::too_many_arguments)] +#[expect(clippy::too_many_arguments, reason = "TODO")] pub fn audit_plot_sync<'a, 'b, Plot>( public_key_hash: &'a Blake3Hash, shard_commitments_roots_cache: &'a ShardCommitmentsRootsCache, diff --git a/crates/farmer/ab-farmer-components/src/plotting.rs b/crates/farmer/ab-farmer-components/src/plotting.rs index ad20113ebc..ac989fdccb 100644 --- a/crates/farmer/ab-farmer-components/src/plotting.rs +++ b/crates/farmer/ab-farmer-components/src/plotting.rs @@ -442,6 +442,10 @@ where /// Mostly opaque sector encoding result ready for writing #[derive(Debug)] +#[expect( + clippy::partial_pub_fields, + reason = "Intentionally hiding some fields such that they can only be used by internal APIs" +)] pub struct EncodedSector { /// Information about sector that was plotted pub plotted_sector: PlottedSector, diff --git a/crates/farmer/ab-farmer-components/src/proving.rs b/crates/farmer/ab-farmer-components/src/proving.rs index dad4b3d7b5..41b7a53de9 100644 --- a/crates/farmer/ab-farmer-components/src/proving.rs +++ b/crates/farmer/ab-farmer-components/src/proving.rs @@ -353,7 +353,8 @@ where Sector: ReadAtSync + 'a, PosProofGenerator: (FnMut(&PosSeed) -> Box) + 'a, { - #[expect(clippy::too_many_arguments)] + // TODO: Struct for arguments + #[expect(clippy::too_many_arguments, reason = "TODO")] fn new( public_key_hash: &'a Blake3Hash, sector_id: SectorId, diff --git a/crates/farmer/ab-farmer/src/bin/ab-farmer/commands/benchmark.rs b/crates/farmer/ab-farmer/src/bin/ab-farmer/commands/benchmark.rs index 858124f9c4..9cecd05209 100644 --- a/crates/farmer/ab-farmer/src/bin/ab-farmer/commands/benchmark.rs +++ b/crates/farmer/ab-farmer/src/bin/ab-farmer/commands/benchmark.rs @@ -2,7 +2,7 @@ use crate::PosTable; use ab_core_primitives::hashes::Blake3Hash; use ab_core_primitives::pot::SlotNumber; use ab_core_primitives::shard::NumShards; -use ab_core_primitives::solutions::SolutionRange; +use ab_core_primitives::solutions::{ShardMembershipEntropy, SolutionRange}; use ab_erasure_coding::ErasureCoding; use ab_farmer::single_disk_farm::direct_io_file_wrapper::DirectIoFileWrapper; use ab_farmer::single_disk_farm::farming::rayon_files::RayonFiles; @@ -191,7 +191,7 @@ where global_challenge: Blake3Hash::from(global_challenge), // No solution will be found, pure audit solution_range: SolutionRange::MIN, - shard_membership_entropy: Default::default(), + shard_membership_entropy: ShardMembershipEntropy::default(), num_shards: NumShards::new(NonZeroU16::MIN, NonZeroU16::MIN) .expect("Values are statically known to be valid; qed"), }, @@ -226,7 +226,7 @@ where global_challenge: Blake3Hash::from(global_challenge), // No solution will be found, pure audit solution_range: SolutionRange::MIN, - shard_membership_entropy: Default::default(), + shard_membership_entropy: ShardMembershipEntropy::default(), num_shards: NumShards::new(NonZeroU16::MIN, NonZeroU16::MIN) .expect("Values are statically known to be valid; qed"), }, @@ -259,7 +259,7 @@ where global_challenge: Blake3Hash::from(global_challenge), // No solution will be found, pure audit solution_range: SolutionRange::MIN, - shard_membership_entropy: Default::default(), + shard_membership_entropy: ShardMembershipEntropy::default(), num_shards: NumShards::new(NonZeroU16::MIN, NonZeroU16::MIN) .expect("Values are statically known to be valid; qed"), }, @@ -358,7 +358,7 @@ where global_challenge: Blake3Hash::from(rand::random::<[u8; 32]>()), // Solution is guaranteed to be found solution_range: SolutionRange::MAX, - shard_membership_entropy: Default::default(), + shard_membership_entropy: ShardMembershipEntropy::default(), num_shards: NumShards::new(NonZeroU16::MIN, NonZeroU16::MIN) .expect("Values are statically known to be valid; qed"), }, @@ -406,7 +406,7 @@ where global_challenge: Blake3Hash::from(rand::random::<[u8; 32]>()), // Solution is guaranteed to be found solution_range: SolutionRange::MAX, - shard_membership_entropy: Default::default(), + shard_membership_entropy: ShardMembershipEntropy::default(), num_shards: NumShards::new(NonZeroU16::MIN, NonZeroU16::MIN) .expect("Values are statically known to be valid; qed"), }, @@ -452,7 +452,7 @@ where global_challenge: Blake3Hash::from(rand::random::<[u8; 32]>()), // Solution is guaranteed to be found solution_range: SolutionRange::MAX, - shard_membership_entropy: Default::default(), + shard_membership_entropy: ShardMembershipEntropy::default(), num_shards: NumShards::new(NonZeroU16::MIN, NonZeroU16::MIN) .expect("Values are statically known to be valid; qed"), }, diff --git a/crates/farmer/ab-farmer/src/bin/ab-farmer/commands/shared/network.rs b/crates/farmer/ab-farmer/src/bin/ab-farmer/commands/shared/network.rs index 53b55e8cbb..9f3f71b394 100644 --- a/crates/farmer/ab-farmer/src/bin/ab-farmer/commands/shared/network.rs +++ b/crates/farmer/ab-farmer/src/bin/ab-farmer/commands/shared/network.rs @@ -79,7 +79,7 @@ pub(in super::super) struct NetworkArgs { pub(in super::super) external_addresses: Vec, } -#[expect(clippy::too_many_arguments)] +#[expect(clippy::too_many_arguments, reason = "Internal API")] pub(in super::super) fn configure_network( protocol_prefix: String, base_path: &Path, diff --git a/crates/farmer/ab-farmer/src/cluster/cache.rs b/crates/farmer/ab-farmer/src/cluster/cache.rs index fa1dc00eb5..621a254b0b 100644 --- a/crates/farmer/ab-farmer/src/cluster/cache.rs +++ b/crates/farmer/ab-farmer/src/cluster/cache.rs @@ -78,7 +78,10 @@ impl Decode for ClusterCacheId { } } -#[expect(clippy::new_without_default)] +#[expect( + clippy::new_without_default, + reason = "Default has different semantics" +)] impl ClusterCacheId { /// Creates new ID #[inline] diff --git a/crates/farmer/ab-farmer/src/cluster/controller/caches.rs b/crates/farmer/ab-farmer/src/cluster/controller/caches.rs index d884691bf9..5048f95866 100644 --- a/crates/farmer/ab-farmer/src/cluster/controller/caches.rs +++ b/crates/farmer/ab-farmer/src/cluster/controller/caches.rs @@ -227,7 +227,7 @@ pub async fn maintain_caches( ); } } - _ = cache_reinitialization => { + () = cache_reinitialization => { // Nothing left to do } } diff --git a/crates/farmer/ab-farmer/src/cluster/farmer.rs b/crates/farmer/ab-farmer/src/cluster/farmer.rs index 7b1a38ce9a..484c750105 100644 --- a/crates/farmer/ab-farmer/src/cluster/farmer.rs +++ b/crates/farmer/ab-farmer/src/cluster/farmer.rs @@ -74,7 +74,10 @@ impl Decode for ClusterFarmerId { } } -#[expect(clippy::new_without_default)] +#[expect( + clippy::new_without_default, + reason = "Default has different semantics" +)] impl ClusterFarmerId { /// Create a new cluster farmer ID pub fn new() -> Self { @@ -374,9 +377,9 @@ impl ClusterFarm { }; select! { - _ = sector_updates_fut.fuse() => {} - _ = farming_notifications_fut.fuse() => {} - _ = solutions_fut.fuse() => {} + () = sector_updates_fut.fuse() => {} + () = farming_notifications_fut.fuse() => {} + () = solutions_fut.fuse() => {} } } }; @@ -516,9 +519,9 @@ where }; select! { - _ = sector_updates_fut.fuse() => {} - _ = farming_notifications_fut.fuse() => {} - _ = solutions_fut.fuse() => {} + () = sector_updates_fut.fuse() => {} + () = farming_notifications_fut.fuse() => {} + () = solutions_fut.fuse() => {} } drop(sector_updates_handler_id); diff --git a/crates/farmer/ab-farmer/src/cluster/plotter.rs b/crates/farmer/ab-farmer/src/cluster/plotter.rs index 0de76766f5..48ba74da91 100644 --- a/crates/farmer/ab-farmer/src/cluster/plotter.rs +++ b/crates/farmer/ab-farmer/src/cluster/plotter.rs @@ -56,7 +56,10 @@ pub enum ClusterPlotterId { Ulid(Ulid), } -#[expect(clippy::new_without_default)] +#[expect( + clippy::new_without_default, + reason = "Default has different semantics" +)] impl ClusterPlotterId { /// Creates new ID pub fn new() -> Self { @@ -297,7 +300,7 @@ impl ClusterPlotter { self.handlers.plotting_progress.add(callback) } - #[expect(clippy::too_many_arguments)] + #[expect(clippy::too_many_arguments, reason = "Internal API")] async fn plot_sector_internal( &self, start: Instant, @@ -558,7 +561,7 @@ enum ResponseProcessingResult { Continue, } -#[expect(clippy::too_many_arguments)] +#[expect(clippy::too_many_arguments, reason = "Internal API")] async fn process_response_notification( start: &Instant, free_instance: &str, @@ -911,10 +914,10 @@ async fn process_plot_sector_request

( }; select! { - _ = progress_proxy_fut.fuse() => { + () = progress_proxy_fut.fuse() => { // Done } - _ = ping_fut.fuse() => { + () = ping_fut.fuse() => { unreachable!("Ping loop never ends"); } } diff --git a/crates/farmer/ab-farmer/src/farm.rs b/crates/farmer/ab-farmer/src/farm.rs index e09ce4b562..cab5171c43 100644 --- a/crates/farmer/ab-farmer/src/farm.rs +++ b/crates/farmer/ab-farmer/src/farm.rs @@ -100,7 +100,10 @@ impl Decode for PieceCacheId { } } -#[expect(clippy::new_without_default)] +#[expect( + clippy::new_without_default, + reason = "Default has different semantics" +)] impl PieceCacheId { /// Creates new ID #[inline] @@ -535,7 +538,10 @@ impl Decode for FarmId { } } -#[expect(clippy::new_without_default)] +#[expect( + clippy::new_without_default, + reason = "Default has different semantics" +)] impl FarmId { /// Creates new ID #[inline] diff --git a/crates/farmer/ab-farmer/src/node_client/caching_proxy_node_client.rs b/crates/farmer/ab-farmer/src/node_client/caching_proxy_node_client.rs index 02a2e5a8d0..91e9a73246 100644 --- a/crates/farmer/ab-farmer/src/node_client/caching_proxy_node_client.rs +++ b/crates/farmer/ab-farmer/src/node_client/caching_proxy_node_client.rs @@ -273,9 +273,9 @@ where let background_task = tokio::spawn(async move { select! { - _ = slot_info_proxy_fut.fuse() => {}, - _ = super_segment_headers_maintenance_fut.fuse() => {}, - _ = block_sealing_proxy_fut.fuse() => {}, + () = slot_info_proxy_fut.fuse() => {}, + () = super_segment_headers_maintenance_fut.fuse() => {}, + () = block_sealing_proxy_fut.fuse() => {}, } }); diff --git a/crates/farmer/ab-farmer/src/plotter.rs b/crates/farmer/ab-farmer/src/plotter.rs index 722cec7fcb..f9fdc2596a 100644 --- a/crates/farmer/ab-farmer/src/plotter.rs +++ b/crates/farmer/ab-farmer/src/plotter.rs @@ -89,7 +89,7 @@ pub trait Plotter: fmt::Debug { /// /// Future returns once plotting is successfully scheduled (for backpressure purposes). // TODO: Struct for arguments - #[expect(clippy::too_many_arguments)] + #[expect(clippy::too_many_arguments, reason = "TODO")] async fn plot_sector( &self, public_key: Ed25519PublicKey, @@ -106,7 +106,7 @@ pub trait Plotter: fmt::Debug { /// Returns `true` if plotting started successfully and `false` if there is no capacity to start /// plotting immediately. // TODO: Struct for arguments - #[expect(clippy::too_many_arguments)] + #[expect(clippy::too_many_arguments, reason = "TODO")] async fn try_plot_sector( &self, public_key: Ed25519PublicKey, diff --git a/crates/farmer/ab-farmer/src/plotter/cpu.rs b/crates/farmer/ab-farmer/src/plotter/cpu.rs index 8618ccfe60..1ca5ea1c80 100644 --- a/crates/farmer/ab-farmer/src/plotter/cpu.rs +++ b/crates/farmer/ab-farmer/src/plotter/cpu.rs @@ -228,7 +228,7 @@ where self.handlers.plotting_progress.add(callback) } - #[expect(clippy::too_many_arguments)] + #[expect(clippy::too_many_arguments, reason = "Internal API")] async fn plot_sector_internal( &self, start: Instant, diff --git a/crates/farmer/ab-farmer/src/plotter/gpu.rs b/crates/farmer/ab-farmer/src/plotter/gpu.rs index b72b24657b..d9a3298eb1 100644 --- a/crates/farmer/ab-farmer/src/plotter/gpu.rs +++ b/crates/farmer/ab-farmer/src/plotter/gpu.rs @@ -220,7 +220,7 @@ where self.handlers.plotting_progress.add(callback) } - #[expect(clippy::too_many_arguments)] + #[expect(clippy::too_many_arguments, reason = "Internal API")] async fn plot_sector_internal( &self, start: Instant, diff --git a/crates/farmer/ab-farmer/src/single_disk_farm.rs b/crates/farmer/ab-farmer/src/single_disk_farm.rs index 61804ca3b9..699e7358b9 100644 --- a/crates/farmer/ab-farmer/src/single_disk_farm.rs +++ b/crates/farmer/ab-farmer/src/single_disk_farm.rs @@ -613,21 +613,21 @@ impl FromStr for ScrubTarget { } impl ScrubTarget { - fn metadata(&self) -> bool { + fn metadata(self) -> bool { match self { Self::All | Self::Metadata | Self::Plot => true, Self::Cache => false, } } - fn plot(&self) -> bool { + fn plot(self) -> bool { match self { Self::All | Self::Plot => true, Self::Metadata | Self::Cache => false, } } - fn cache(&self) -> bool { + fn cache(self) -> bool { match self { Self::All | Self::Cache => true, Self::Metadata | Self::Plot => false, @@ -1185,7 +1185,7 @@ impl SingleDiskFarm { move || { Handle::current().block_on(async { select! { - _ = reading_fut.fuse() => { + () = reading_fut.fuse() => { // Nothing, just exit } _ = stop_receiver.recv().fuse() => { diff --git a/crates/farmer/ab-farmer/src/single_disk_farm/block_sealing.rs b/crates/farmer/ab-farmer/src/single_disk_farm/block_sealing.rs index 5b3d1b0d5b..6d86ed3042 100644 --- a/crates/farmer/ab-farmer/src/single_disk_farm/block_sealing.rs +++ b/crates/farmer/ab-farmer/src/single_disk_farm/block_sealing.rs @@ -39,7 +39,7 @@ where }) .await { - Ok(_) => { + Ok(()) => { info!( "Successfully sealed block pre-seal hash {}", hex::encode(pre_seal_hash) diff --git a/crates/farmer/ab-farmer/src/single_disk_farm/farming.rs b/crates/farmer/ab-farmer/src/single_disk_farm/farming.rs index 2a0a4cea09..75ef03cdbb 100644 --- a/crates/farmer/ab-farmer/src/single_disk_farm/farming.rs +++ b/crates/farmer/ab-farmer/src/single_disk_farm/farming.rs @@ -122,7 +122,10 @@ where } /// Audit this plot - #[expect(clippy::type_complexity)] + #[expect( + clippy::type_complexity, + reason = "Probably not worth creating type aliases" + )] pub fn audit<'b, PosTable>( &'a self, options: PlotAuditOptions<'a, 'b, PosTable>, diff --git a/crates/farmer/ab-farmer/src/single_disk_farm/piece_reader.rs b/crates/farmer/ab-farmer/src/single_disk_farm/piece_reader.rs index e19dff1fea..d0e7dce1e9 100644 --- a/crates/farmer/ab-farmer/src/single_disk_farm/piece_reader.rs +++ b/crates/farmer/ab-farmer/src/single_disk_farm/piece_reader.rs @@ -50,7 +50,7 @@ impl DiskPieceReader { /// /// NOTE: Background future is async, but does blocking operations and should be running in /// dedicated thread. - #[expect(clippy::too_many_arguments)] + #[expect(clippy::too_many_arguments, reason = "Internal API")] pub(super) fn new( public_key_hash: Blake3Hash, shard_commitments_roots_cache: ShardCommitmentsRootsCache, @@ -109,7 +109,7 @@ impl DiskPieceReader { } } -#[expect(clippy::too_many_arguments)] +#[expect(clippy::too_many_arguments, reason = "Internal API")] async fn read_pieces( public_key_hash: Blake3Hash, shard_commitments_roots_cache: ShardCommitmentsRootsCache, diff --git a/crates/farmer/ab-farmer/src/single_disk_farm/plotting.rs b/crates/farmer/ab-farmer/src/single_disk_farm/plotting.rs index 45a3110094..f8a46d24f2 100644 --- a/crates/farmer/ab-farmer/src/single_disk_farm/plotting.rs +++ b/crates/farmer/ab-farmer/src/single_disk_farm/plotting.rs @@ -552,7 +552,7 @@ where /// Outer error is used to indicate irrecoverable plotting errors, while inner result is for /// recoverable errors -#[expect(clippy::too_many_arguments)] +#[expect(clippy::too_many_arguments, reason = "Internal API")] async fn plot_single_sector_internal( sector_index: SectorIndex, sector_size: usize, @@ -841,7 +841,7 @@ struct SectorToReplot { expires_at: SegmentIndex, } -#[expect(clippy::too_many_arguments)] +#[expect(clippy::too_many_arguments, reason = "Internal API")] async fn send_plotting_notifications( public_key_hash: Blake3Hash, shard_commitments_roots_cache: &ShardCommitmentsRootsCache, diff --git a/crates/farmer/ab-farmer/src/utils/tests.rs b/crates/farmer/ab-farmer/src/utils/tests.rs index 166740861a..d687bfa4bf 100644 --- a/crates/farmer/ab-farmer/src/utils/tests.rs +++ b/crates/farmer/ab-farmer/src/utils/tests.rs @@ -101,11 +101,11 @@ fn test_parse_cpu_cores_sets() { assert_eq!(cores[1].cores, vec![4, 5, 6, 7]); } - assert!(parse_cpu_cores_sets("").is_err()); - assert!(parse_cpu_cores_sets("a").is_err()); - assert!(parse_cpu_cores_sets("0,").is_err()); - assert!(parse_cpu_cores_sets("0,a").is_err()); - assert!(parse_cpu_cores_sets("0 a").is_err()); + parse_cpu_cores_sets("").unwrap_err(); + parse_cpu_cores_sets("a").unwrap_err(); + parse_cpu_cores_sets("0,").unwrap_err(); + parse_cpu_cores_sets("0,a").unwrap_err(); + parse_cpu_cores_sets("0 a").unwrap_err(); } #[test] diff --git a/crates/farmer/ab-proof-of-space-gpu/src/shader/compute_f1.rs b/crates/farmer/ab-proof-of-space-gpu/src/shader/compute_f1.rs index a88f45bfd0..b73de089b9 100644 --- a/crates/farmer/ab-proof-of-space-gpu/src/shader/compute_f1.rs +++ b/crates/farmer/ab-proof-of-space-gpu/src/shader/compute_f1.rs @@ -15,15 +15,13 @@ use spirv_std::glam::{UVec3, UVec4}; use spirv_std::memory::{Scope, Semantics}; use spirv_std::spirv; -const fn gcd(a: u32, b: u32) -> u32 { - let mut x = a; - let mut y = b; - while y != 0 { - let t = y; - y = x % y; - x = t; +const fn gcd(mut a: u32, mut b: u32) -> u32 { + while b != 0 { + let t = b; + b = a % b; + a = t; } - x + a } const fn lcm(a: u32, b: u32) -> u32 { diff --git a/crates/farmer/ab-proof-of-space-gpu/src/shader/compute_f1/gpu_tests.rs b/crates/farmer/ab-proof-of-space-gpu/src/shader/compute_f1/gpu_tests.rs index d35d9d8edd..eff420d6a1 100644 --- a/crates/farmer/ab-proof-of-space-gpu/src/shader/compute_f1/gpu_tests.rs +++ b/crates/farmer/ab-proof-of-space-gpu/src/shader/compute_f1/gpu_tests.rs @@ -11,9 +11,10 @@ use wgpu::util::{BufferInitDescriptor, DeviceExt}; use wgpu::{ Adapter, BackendOptions, Backends, BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingType, BufferAddress, BufferBindingType, - BufferDescriptor, BufferUsages, CommandEncoderDescriptor, ComputePipelineDescriptor, - DeviceDescriptor, Instance, InstanceDescriptor, InstanceFlags, MapMode, MemoryBudgetThresholds, - PipelineCompilationOptions, PipelineLayoutDescriptor, PollType, ShaderStages, + BufferDescriptor, BufferUsages, CommandEncoderDescriptor, ComputePassDescriptor, + ComputePipelineDescriptor, DeviceDescriptor, Instance, InstanceDescriptor, InstanceFlags, + MapMode, MemoryBudgetThresholds, PipelineCompilationOptions, PipelineLayoutDescriptor, + PollType, ShaderStages, }; #[test] @@ -232,7 +233,7 @@ async fn compute_f1_adapter( let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor { label: None }); { - let mut cpass = encoder.begin_compute_pass(&Default::default()); + let mut cpass = encoder.begin_compute_pass(&ComputePassDescriptor::default()); cpass.set_bind_group(0, &bind_group, &[]); cpass.set_pipeline(&compute_pipeline); cpass.dispatch_workgroups( diff --git a/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f2.rs b/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f2.rs index 78a16c0287..88a0c7d4ab 100644 --- a/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f2.rs +++ b/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f2.rs @@ -81,7 +81,10 @@ unsafe fn compute_f2_into_buckets_inner( let mut right_position_or_skip = positions_offset; // TODO: More idiomatic version currently doesn't compile: // https://github.com/Rust-GPU/rust-gpu/issues/241#issuecomment-3005693043 - #[expect(clippy::needless_range_loop)] + #[expect( + clippy::needless_range_loop, + reason = "Intentional workaround for rust-gpu" + )] for offset in 0..REDUCED_BUCKET_SIZE { let position_r = bucket_scratch[offset]; if position_r.r.get() == r_target { diff --git a/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f2/gpu_tests.rs b/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f2/gpu_tests.rs index f146db8f0c..b4521e0552 100644 --- a/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f2/gpu_tests.rs +++ b/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f2/gpu_tests.rs @@ -15,9 +15,10 @@ use wgpu::util::{BufferInitDescriptor, DeviceExt}; use wgpu::{ Adapter, BackendOptions, Backends, BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingType, BufferAddress, BufferBindingType, - BufferDescriptor, BufferUsages, CommandEncoderDescriptor, ComputePipelineDescriptor, - DeviceDescriptor, Instance, InstanceDescriptor, InstanceFlags, MapMode, MemoryBudgetThresholds, - PipelineCompilationOptions, PipelineLayoutDescriptor, PollType, ShaderStages, + BufferDescriptor, BufferUsages, CommandEncoderDescriptor, ComputePassDescriptor, + ComputePipelineDescriptor, DeviceDescriptor, Instance, InstanceDescriptor, InstanceFlags, + MapMode, MemoryBudgetThresholds, PipelineCompilationOptions, PipelineLayoutDescriptor, + PollType, ShaderStages, }; #[test] @@ -391,7 +392,7 @@ async fn find_matches_and_compute_f2_adapter( let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor { label: None }); { - let mut cpass = encoder.begin_compute_pass(&Default::default()); + let mut cpass = encoder.begin_compute_pass(&ComputePassDescriptor::default()); cpass.set_bind_group(0, &bind_group, &[]); cpass.set_pipeline(&compute_pipeline); cpass.dispatch_workgroups(NUM_MATCH_BUCKETS as u32, 1, 1); diff --git a/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f7.rs b/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f7.rs index ea6721d7ed..125ab2d301 100644 --- a/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f7.rs +++ b/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f7.rs @@ -147,7 +147,10 @@ unsafe fn compute_f7_into_buckets_inner( let mut right_position_or_skip = positions_offset; // TODO: More idiomatic version currently doesn't compile: // https://github.com/Rust-GPU/rust-gpu/issues/241#issuecomment-3005693043 - #[expect(clippy::needless_range_loop)] + #[expect( + clippy::needless_range_loop, + reason = "Intentional workaround for rust-gpu" + )] for offset in 0..REDUCED_BUCKET_SIZE { let position_r = bucket_scratch[offset]; if position_r.r.get() == r_target { diff --git a/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f7/gpu_tests.rs b/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f7/gpu_tests.rs index d0f8de6a37..c0d61d0110 100644 --- a/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f7/gpu_tests.rs +++ b/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_f7/gpu_tests.rs @@ -18,9 +18,10 @@ use wgpu::util::{BufferInitDescriptor, DeviceExt}; use wgpu::{ Adapter, BackendOptions, Backends, BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingType, BufferAddress, BufferBindingType, - BufferDescriptor, BufferUsages, CommandEncoderDescriptor, ComputePipelineDescriptor, - DeviceDescriptor, Instance, InstanceDescriptor, InstanceFlags, MapMode, MemoryBudgetThresholds, - PipelineCompilationOptions, PipelineLayoutDescriptor, PollType, ShaderStages, + BufferDescriptor, BufferUsages, CommandEncoderDescriptor, ComputePassDescriptor, + ComputePipelineDescriptor, DeviceDescriptor, Instance, InstanceDescriptor, InstanceFlags, + MapMode, MemoryBudgetThresholds, PipelineCompilationOptions, PipelineLayoutDescriptor, + PollType, ShaderStages, }; #[test] @@ -349,7 +350,7 @@ async fn find_matches_and_compute_f7_adapter( let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor { label: None }); { - let mut cpass = encoder.begin_compute_pass(&Default::default()); + let mut cpass = encoder.begin_compute_pass(&ComputePassDescriptor::default()); cpass.set_bind_group(0, &bind_group, &[]); cpass.set_pipeline(&compute_pipeline); cpass.dispatch_workgroups(NUM_MATCH_BUCKETS as u32, 1, 1); diff --git a/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_fn.rs b/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_fn.rs index 9af84b2a14..d0b44cbc01 100644 --- a/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_fn.rs +++ b/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_and_compute_fn.rs @@ -83,7 +83,10 @@ unsafe fn compute_fn_into_buckets_inner( let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor { label: None }); { - let mut cpass = encoder.begin_compute_pass(&Default::default()); + let mut cpass = encoder.begin_compute_pass(&ComputePassDescriptor::default()); cpass.set_bind_group(0, &bind_group, &[]); cpass.set_pipeline(&compute_pipeline); cpass.dispatch_workgroups(NUM_MATCH_BUCKETS as u32, 1, 1); diff --git a/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_in_buckets/gpu_tests.rs b/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_in_buckets/gpu_tests.rs index 56cb557bdb..1e07a4daa6 100644 --- a/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_in_buckets/gpu_tests.rs +++ b/crates/farmer/ab-proof-of-space-gpu/src/shader/find_matches_in_buckets/gpu_tests.rs @@ -11,9 +11,10 @@ use wgpu::util::{BufferInitDescriptor, DeviceExt}; use wgpu::{ Adapter, BackendOptions, Backends, BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingType, BufferAddress, BufferBindingType, - BufferDescriptor, BufferUsages, CommandEncoderDescriptor, ComputePipelineDescriptor, - DeviceDescriptor, Instance, InstanceDescriptor, InstanceFlags, MapMode, MemoryBudgetThresholds, - PipelineCompilationOptions, PipelineLayoutDescriptor, PollType, ShaderStages, + BufferDescriptor, BufferUsages, CommandEncoderDescriptor, ComputePassDescriptor, + ComputePipelineDescriptor, DeviceDescriptor, Instance, InstanceDescriptor, InstanceFlags, + MapMode, MemoryBudgetThresholds, PipelineCompilationOptions, PipelineLayoutDescriptor, + PollType, ShaderStages, }; const NUM_BUCKETS: usize = 3; @@ -247,7 +248,7 @@ async fn find_matches_in_buckets_adapter( let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor { label: None }); { - let mut cpass = encoder.begin_compute_pass(&Default::default()); + let mut cpass = encoder.begin_compute_pass(&ComputePassDescriptor::default()); cpass.set_bind_group(0, &bind_group, &[]); cpass.set_pipeline(&compute_pipeline); cpass.dispatch_workgroups(NUM_MATCH_BUCKETS as u32, 1, 1); diff --git a/crates/farmer/ab-proof-of-space-gpu/src/shader/find_proofs/gpu_tests.rs b/crates/farmer/ab-proof-of-space-gpu/src/shader/find_proofs/gpu_tests.rs index 5dea5d0408..a1d8d74a82 100644 --- a/crates/farmer/ab-proof-of-space-gpu/src/shader/find_proofs/gpu_tests.rs +++ b/crates/farmer/ab-proof-of-space-gpu/src/shader/find_proofs/gpu_tests.rs @@ -17,9 +17,10 @@ use wgpu::util::{BufferInitDescriptor, DeviceExt}; use wgpu::{ Adapter, BackendOptions, Backends, BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingType, BufferAddress, BufferBindingType, - BufferDescriptor, BufferUsages, CommandEncoderDescriptor, ComputePipelineDescriptor, - DeviceDescriptor, Instance, InstanceDescriptor, InstanceFlags, MapMode, MemoryBudgetThresholds, - PipelineCompilationOptions, PipelineLayoutDescriptor, PollType, ShaderStages, + BufferDescriptor, BufferUsages, CommandEncoderDescriptor, ComputePassDescriptor, + ComputePipelineDescriptor, DeviceDescriptor, Instance, InstanceDescriptor, InstanceFlags, + MapMode, MemoryBudgetThresholds, PipelineCompilationOptions, PipelineLayoutDescriptor, + PollType, ShaderStages, }; fn generate_positions( @@ -475,7 +476,7 @@ async fn find_proofs_adapter( let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor { label: None }); { - let mut cpass = encoder.begin_compute_pass(&Default::default()); + let mut cpass = encoder.begin_compute_pass(&ComputePassDescriptor::default()); cpass.set_bind_group(0, &bind_group, &[]); cpass.set_pipeline(&compute_pipeline); cpass.dispatch_workgroups(NUM_S_BUCKETS as u32 / WORKGROUP_SIZE, 1, 1); diff --git a/crates/farmer/ab-proof-of-space-gpu/src/shader/sort_buckets/gpu_tests.rs b/crates/farmer/ab-proof-of-space-gpu/src/shader/sort_buckets/gpu_tests.rs index 7b74c6c401..230b461f03 100644 --- a/crates/farmer/ab-proof-of-space-gpu/src/shader/sort_buckets/gpu_tests.rs +++ b/crates/farmer/ab-proof-of-space-gpu/src/shader/sort_buckets/gpu_tests.rs @@ -10,9 +10,10 @@ use wgpu::util::{BufferInitDescriptor, DeviceExt}; use wgpu::{ Adapter, BackendOptions, Backends, BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingType, BufferAddress, BufferBindingType, - BufferDescriptor, BufferUsages, CommandEncoderDescriptor, ComputePipelineDescriptor, - DeviceDescriptor, Instance, InstanceDescriptor, InstanceFlags, MapMode, MemoryBudgetThresholds, - PipelineCompilationOptions, PipelineLayoutDescriptor, PollType, ShaderStages, + BufferDescriptor, BufferUsages, CommandEncoderDescriptor, ComputePassDescriptor, + ComputePipelineDescriptor, DeviceDescriptor, Instance, InstanceDescriptor, InstanceFlags, + MapMode, MemoryBudgetThresholds, PipelineCompilationOptions, PipelineLayoutDescriptor, + PollType, ShaderStages, }; #[test] @@ -221,7 +222,7 @@ async fn sort_buckets_adapter( let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor { label: None }); { - let mut cpass = encoder.begin_compute_pass(&Default::default()); + let mut cpass = encoder.begin_compute_pass(&ComputePassDescriptor::default()); cpass.set_bind_group(0, &bind_group, &[]); cpass.set_pipeline(&compute_pipeline); cpass.dispatch_workgroups(NUM_BUCKETS as u32, 1, 1); diff --git a/crates/farmer/ab-proof-of-space-gpu/src/shader/types.rs b/crates/farmer/ab-proof-of-space-gpu/src/shader/types.rs index ae46e89139..ccc37a6cd6 100644 --- a/crates/farmer/ab-proof-of-space-gpu/src/shader/types.rs +++ b/crates/farmer/ab-proof-of-space-gpu/src/shader/types.rs @@ -159,7 +159,7 @@ impl R { /// Get the inner stored value #[inline(always)] - pub(super) fn get(&self) -> u32 { + pub(super) fn get(self) -> u32 { self.0 } } @@ -239,7 +239,7 @@ impl Match { /// Returns `(bucket_offset, r_target, positions_offset)` #[inline(always)] - pub(super) fn split(&self) -> (u32, u32, u32) { + pub(super) fn split(self) -> (u32, u32, u32) { // TODO: `const {}` is a workaround for https://github.com/Rust-GPU/rust-gpu/issues/322 and // shouldn't be necessary otherwise ( @@ -251,7 +251,7 @@ impl Match { /// Extracts a key that can be used for sorting matches #[inline(always)] - pub(super) fn cmp_key(&self) -> u32 { + pub(super) fn cmp_key(self) -> u32 { self.0 } } diff --git a/crates/node/ab-client-database/src/lib.rs b/crates/node/ab-client-database/src/lib.rs index 66a1b310c1..19c9cc9de3 100644 --- a/crates/node/ab-client-database/src/lib.rs +++ b/crates/node/ab-client-database/src/lib.rs @@ -820,6 +820,7 @@ where } } +#[expect(clippy::empty_drop, reason = "Not implemented yet")] impl Drop for ClientDatabase where Block: GenericOwnedBlock, diff --git a/crates/node/ab-client-proof-of-time/src/source/timekeeper.rs b/crates/node/ab-client-proof-of-time/src/source/timekeeper.rs index 73d284e310..690d44d9a7 100644 --- a/crates/node/ab-client-proof-of-time/src/source/timekeeper.rs +++ b/crates/node/ab-client-proof-of-time/src/source/timekeeper.rs @@ -132,7 +132,7 @@ impl Timekeeper { return Ok(()); } - slot_duration.as_duration() - duration + slot_duration.as_duration().saturating_sub(duration) }; loop { diff --git a/crates/node/ab-node-rpc-server/src/lib.rs b/crates/node/ab-node-rpc-server/src/lib.rs index ec5a19ba32..76f1a7d12f 100644 --- a/crates/node/ab-node-rpc-server/src/lib.rs +++ b/crates/node/ab-node-rpc-server/src/lib.rs @@ -347,27 +347,27 @@ where loop { select! { - _ = server_fut => {} + () = server_fut => {} maybe_new_slot_notification = self.new_slot_notification_receiver.next() => { let Some(new_slot_notification) = maybe_new_slot_notification else { break; }; - self.handle_new_slot_notification(new_slot_notification).await; + self.handle_new_slot_notification(new_slot_notification); } maybe_block_sealing_notification = self.block_sealing_notification_receiver.next() => { let Some(block_sealing_notification) = maybe_block_sealing_notification else { break; }; - self.handle_block_sealing_notification(block_sealing_notification).await; + self.handle_block_sealing_notification(block_sealing_notification); } maybe_new_super_segment = self.new_super_segment_notification_receiver.next() => { let Some(new_super_segment) = maybe_new_super_segment else { break; }; - self.handle_new_super_segment(new_super_segment).await; + self.handle_new_super_segment(new_super_segment); } _ = archived_segment_cache_cleanup_interval.tick().fuse() => { if let Some(mut maybe_cached_archived_segment) = self.cached_archived_segment.try_lock() @@ -381,7 +381,7 @@ where } } - async fn handle_new_slot_notification(&mut self, new_slot_notification: NewSlotNotification) { + fn handle_new_slot_notification(&mut self, new_slot_notification: NewSlotNotification) { let NewSlotNotification { new_slot_info, solution_sender, @@ -435,7 +435,7 @@ where }); } - async fn handle_block_sealing_notification( + fn handle_block_sealing_notification( &mut self, block_sealing_notification: BlockSealNotification, ) { @@ -485,7 +485,7 @@ where }); } - async fn handle_new_super_segment(&mut self, super_segment: SuperSegment) { + fn handle_new_super_segment(&mut self, super_segment: SuperSegment) { // This will be sent to the farmer let super_segment_header = serde_json::value::to_raw_value(&super_segment.header) .expect("Serialization of super segment info never fails; qed"); diff --git a/crates/node/ab-node/src/cli/run/chain_spec.rs b/crates/node/ab-node/src/cli/run/chain_spec.rs index 01662453f4..f28d2eca38 100644 --- a/crates/node/ab-node/src/cli/run/chain_spec.rs +++ b/crates/node/ab-node/src/cli/run/chain_spec.rs @@ -5,6 +5,7 @@ use ab_core_primitives::block::header::{ }; use ab_core_primitives::block::owned::OwnedBeaconChainBlock; use ab_core_primitives::block::{BlockNumber, BlockRoot, BlockTimestamp}; +use ab_core_primitives::ed25519::{Ed25519PublicKey, Ed25519Signature}; use ab_core_primitives::hashes::Blake3Hash; use ab_core_primitives::pot::{PotOutput, SlotDuration, SlotNumber}; use ab_core_primitives::segments::HistorySize; @@ -122,8 +123,8 @@ impl ChainSpec { ) .expect("Values of the genesis block are valid; qed") .with_seal(BlockHeaderSeal::Ed25519(&BlockHeaderEd25519Seal { - public_key: Default::default(), - signature: Default::default(), + public_key: Ed25519PublicKey::default(), + signature: Ed25519Signature::default(), })) } } diff --git a/crates/shared/ab-archiving/benches/archiving.rs b/crates/shared/ab-archiving/benches/archiving.rs index 2aabde9b3f..07988de862 100644 --- a/crates/shared/ab-archiving/benches/archiving.rs +++ b/crates/shared/ab-archiving/benches/archiving.rs @@ -21,7 +21,7 @@ fn criterion_benchmark(c: &mut Criterion) { b.iter(|| { archiver .clone() - .add_block(black_box(input.clone()), black_box(Default::default())); + .add_block(black_box(input.clone()), black_box(Vec::new())); }); }); @@ -29,7 +29,7 @@ fn criterion_benchmark(c: &mut Criterion) { b.iter(|| { let mut archiver = archiver.clone(); for chunk in input.chunks(SMALL_BLOCK_SIZE) { - archiver.add_block(black_box(chunk.to_vec()), black_box(Default::default())); + archiver.add_block(black_box(chunk.to_vec()), black_box(Vec::new())); } }); }); diff --git a/crates/shared/ab-archiving/tests/integration/archiver.rs b/crates/shared/ab-archiving/tests/integration/archiver.rs index 44e59b06e3..cba2ca67dc 100644 --- a/crates/shared/ab-archiving/tests/integration/archiver.rs +++ b/crates/shared/ab-archiving/tests/integration/archiver.rs @@ -635,8 +635,8 @@ fn object_on_the_edge_of_segment() { // Segment header segment item - SegmentItem::ParentSegmentHeader(SegmentHeader { index: LocalSegmentIndex::ZERO.into(), - root: Default::default(), - prev_segment_header_hash: Default::default(), + root: SegmentRoot::default(), + prev_segment_header_hash: Blake3Hash::default(), last_archived_block: LastArchivedBlock { number: BlockNumber::ZERO.into(), archived_progress: ArchivedBlockProgress::new_complete(), diff --git a/crates/shared/ab-archiving/tests/integration/piece_reconstruction.rs b/crates/shared/ab-archiving/tests/integration/piece_reconstruction.rs index 968afe8939..3807af6a5d 100644 --- a/crates/shared/ab-archiving/tests/integration/piece_reconstruction.rs +++ b/crates/shared/ab-archiving/tests/integration/piece_reconstruction.rs @@ -8,6 +8,7 @@ use chacha20::ChaCha8Rng; use chacha20::rand_core::{Rng, SeedableRng}; #[cfg(feature = "parallel")] use rayon::prelude::*; +use std::assert_matches; const TEST_SHARD_INDEX: ShardIndex = ShardIndex::new(ShardIndex::MAX_SHARD_INDEX - 1).unwrap(); @@ -131,14 +132,10 @@ fn segment_reconstruction_fails() { let pieces = vec![None]; let result = reconstructor.reconstruct_segment(&pieces); - assert!(result.is_err()); - - if let Err(error) = result { - assert!(matches!( - error, - ReconstructorError::NotEnoughShards { num_shards: 1 } - )); - } + assert_matches!( + result.unwrap_err(), + ReconstructorError::NotEnoughShards { num_shards: 1 } + ); } #[test] @@ -149,12 +146,8 @@ fn piece_reconstruction_fails() { let pieces = vec![None]; let result = reconstructor.reconstruct_piece(&pieces, PiecePosition::from(0)); - assert!(result.is_err()); - - if let Err(error) = result { - assert!(matches!( - error, - ReconstructorError::NotEnoughShards { num_shards: 1 } - )); - } + assert_matches!( + result.unwrap_err(), + ReconstructorError::NotEnoughShards { num_shards: 1 } + ); } diff --git a/crates/shared/ab-chacha8/src/lib.rs b/crates/shared/ab-chacha8/src/lib.rs index f4ab637381..eb7ced3a0a 100644 --- a/crates/shared/ab-chacha8/src/lib.rs +++ b/crates/shared/ab-chacha8/src/lib.rs @@ -99,10 +99,13 @@ impl ChaCha8State { // TODO: More idiomatic version currently doesn't compile: // https://github.com/Rust-GPU/rust-gpu/issues/241#issuecomment-3005693043 - #[expect(clippy::needless_range_loop)] // for (d, initial) in self.data.iter_mut().zip(initial) { // *d = d.wrapping_add(initial); // } + #[expect( + clippy::needless_range_loop, + reason = "Intentional workaround for rust-gpu" + )] for i in 0..16 { self.data[i] = self.data[i].wrapping_add(initial[i]); } diff --git a/crates/shared/ab-core-primitives/src/block/body.rs b/crates/shared/ab-core-primitives/src/block/body.rs index 19a1c69b41..69f21ee7d6 100644 --- a/crates/shared/ab-core-primitives/src/block/body.rs +++ b/crates/shared/ab-core-primitives/src/block/body.rs @@ -119,6 +119,10 @@ impl OwnSegments<'_> { /// Information about intermediate shard block #[derive(Debug, Clone)] +#[expect( + clippy::partial_pub_fields, + reason = "Intentionally exposing immediately decoded fields above and hiding the rest of the implementation" +)] pub struct IntermediateShardBlockInfo<'a> { /// A block header that corresponds to an intermediate shard pub header: IntermediateShardHeader<'a>, diff --git a/crates/shared/ab-core-primitives/src/checksum/tests.rs b/crates/shared/ab-core-primitives/src/checksum/tests.rs index 699aab5e9f..34c823b509 100644 --- a/crates/shared/ab-core-primitives/src/checksum/tests.rs +++ b/crates/shared/ab-core-primitives/src/checksum/tests.rs @@ -29,7 +29,7 @@ fn basic() { assert_eq!(random_bytes, decoded_random_bytes); // Non-checksummed encoding fails to decode - assert!(Blake3Checksummed::<[u8; 64]>::decode(&mut plain_encoding.as_slice()).is_err()); + Blake3Checksummed::<[u8; 64]>::decode(&mut plain_encoding.as_slice()).unwrap_err(); // Incorrectly checksummed data fails to decode - assert!(Blake3Checksummed::<[u8; 32]>::decode(&mut random_bytes.as_ref()).is_err()); + Blake3Checksummed::<[u8; 32]>::decode(&mut random_bytes.as_ref()).unwrap_err(); } diff --git a/crates/shared/ab-core-primitives/src/pieces.rs b/crates/shared/ab-core-primitives/src/pieces.rs index 4c8b87cf22..0a1e4d28c3 100644 --- a/crates/shared/ab-core-primitives/src/pieces.rs +++ b/crates/shared/ab-core-primitives/src/pieces.rs @@ -1218,18 +1218,3 @@ impl InnerPiece { unsafe { mem::transmute(value) } } } - -#[cfg(feature = "alloc")] -impl From> for Vec { - fn from(value: Box) -> Self { - let mut value = mem::ManuallyDrop::new(value); - // SAFETY: Always contains fixed allocation of bytes - unsafe { - Vec::from_raw_parts( - value.as_bytes_mut().as_mut_ptr(), - InnerPiece::SIZE, - InnerPiece::SIZE, - ) - } - } -} diff --git a/crates/shared/ab-core-primitives/src/pieces/flat_pieces.rs b/crates/shared/ab-core-primitives/src/pieces/flat_pieces.rs index 31661da738..7f6c04e807 100644 --- a/crates/shared/ab-core-primitives/src/pieces/flat_pieces.rs +++ b/crates/shared/ab-core-primitives/src/pieces/flat_pieces.rs @@ -132,12 +132,10 @@ impl FlatPieces { CowBytes::Owned(bytes) => CowBytes::Shared(bytes.freeze()), }) } -} -#[cfg(feature = "parallel")] -impl FlatPieces { /// Parallel iterator over source pieces (even indices) #[inline] + #[cfg(feature = "parallel")] pub fn par_source(&self) -> impl IndexedParallelIterator + '_ { self.par_iter() .take(RecordedHistorySegment::NUM_RAW_RECORDS) @@ -145,6 +143,7 @@ impl FlatPieces { /// Mutable parallel iterator over source pieces (even indices) #[inline] + #[cfg(feature = "parallel")] pub fn par_source_mut( &mut self, ) -> impl IndexedParallelIterator + '_ { @@ -154,6 +153,7 @@ impl FlatPieces { /// Parallel iterator over parity pieces (odd indices) #[inline] + #[cfg(feature = "parallel")] pub fn par_parity(&self) -> impl IndexedParallelIterator + '_ { self.par_iter() .skip(RecordedHistorySegment::NUM_RAW_RECORDS) @@ -161,6 +161,7 @@ impl FlatPieces { /// Mutable parallel iterator over parity pieces (odd indices) #[inline] + #[cfg(feature = "parallel")] pub fn par_parity_mut( &mut self, ) -> impl IndexedParallelIterator + '_ { diff --git a/crates/shared/ab-core-primitives/src/segments.rs b/crates/shared/ab-core-primitives/src/segments.rs index 429c8470db..2956d86e82 100644 --- a/crates/shared/ab-core-primitives/src/segments.rs +++ b/crates/shared/ab-core-primitives/src/segments.rs @@ -541,38 +541,6 @@ impl SegmentIndex { #[repr(C)] pub struct SegmentRoot([u8; SegmentRoot::SIZE]); -impl SegmentRoot { - /// Check whether a segment root is a part of the super segment - pub fn is_valid( - &self, - shard_index: ShardIndex, - local_segment_index: LocalSegmentIndex, - segment_position: SegmentPosition, - segment_proof: &SegmentProof, - num_segments: u32, - super_segment_root: &SuperSegmentRoot, - ) -> bool { - let shard_segment_root = ShardSegmentRootWithPosition { - shard_index, - segment_position, - local_segment_index, - segment_root: *self, - }; - // The proof is fixed size and contains zero padding elements, which must be skipped for - // verification purposes - let segment_proof = segment_proof - .split_once(|hash| hash == &[0; _]) - .map_or(segment_proof.as_slice(), |(before, _after)| before); - UnbalancedMerkleTree::verify( - super_segment_root, - segment_proof, - u64::from(segment_position), - shard_segment_root.hash(), - u64::from(num_segments), - ) - } -} - impl fmt::Debug for SegmentRoot { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for byte in self.0 { @@ -660,6 +628,36 @@ impl SegmentRoot { // SAFETY: `SegmentRoot` is `#[repr(C)]` and guaranteed to have the same memory layout unsafe { mem::transmute(value) } } + + /// Check whether a segment root is a part of the super segment + pub fn is_valid( + &self, + shard_index: ShardIndex, + local_segment_index: LocalSegmentIndex, + segment_position: SegmentPosition, + segment_proof: &SegmentProof, + num_segments: u32, + super_segment_root: &SuperSegmentRoot, + ) -> bool { + let shard_segment_root = ShardSegmentRootWithPosition { + shard_index, + segment_position, + local_segment_index, + segment_root: *self, + }; + // The proof is fixed size and contains zero padding elements, which must be skipped for + // verification purposes + let segment_proof = segment_proof + .split_once(|hash| hash == &[0; _]) + .map_or(segment_proof.as_slice(), |(before, _after)| before); + UnbalancedMerkleTree::verify( + super_segment_root, + segment_proof, + u64::from(segment_position), + shard_segment_root.hash(), + u64::from(num_segments), + ) + } } /// Size of blockchain history in segments diff --git a/crates/shared/ab-core-primitives/src/solutions.rs b/crates/shared/ab-core-primitives/src/solutions.rs index cb37658ad3..7227d6704d 100644 --- a/crates/shared/ab-core-primitives/src/solutions.rs +++ b/crates/shared/ab-core-primitives/src/solutions.rs @@ -850,9 +850,9 @@ impl Solution { Self { public_key_hash: Ed25519PublicKey::default().hash(), shard_commitment: SolutionShardCommitment { - root: Default::default(), - proof: [Default::default(); _], - leaf: Default::default(), + root: ShardCommitmentHash::default(), + proof: [ShardCommitmentHash::default(); _], + leaf: ShardCommitmentHash::default(), }, piece_local_segment_index: LocalSegmentIndex::ZERO, piece_super_segment_index: SuperSegmentIndex::ZERO, diff --git a/crates/shared/ab-networking/src/behavior.rs b/crates/shared/ab-networking/src/behavior.rs index d3a3203314..737aafde91 100644 --- a/crates/shared/ab-networking/src/behavior.rs +++ b/crates/shared/ab-networking/src/behavior.rs @@ -104,10 +104,9 @@ impl Behavior { } } -#[expect(clippy::large_enum_variant)] #[derive(Debug, From)] pub(crate) enum Event { - Identify(IdentifyEvent), + Identify(Box), Kademlia(KademliaEvent), Gossipsub(GossipsubEvent), Ping(PingEvent), @@ -124,3 +123,9 @@ impl From for Event { unreachable!() } } + +impl From for Event { + fn from(event: IdentifyEvent) -> Self { + Self::Identify(Box::new(event)) + } +} diff --git a/crates/shared/ab-networking/src/behavior/persistent_parameters.rs b/crates/shared/ab-networking/src/behavior/persistent_parameters.rs index a4d5e8bd6a..4460d3e1ac 100644 --- a/crates/shared/ab-networking/src/behavior/persistent_parameters.rs +++ b/crates/shared/ab-networking/src/behavior/persistent_parameters.rs @@ -1,7 +1,7 @@ use crate::utils::{AsyncJoinOnDrop, Handler, HandlerFn}; use ab_core_primitives::hashes::Blake3Hash; use async_trait::async_trait; -use event_listener_primitives::HandlerId; +use event_listener_primitives::{Bag, HandlerId}; use fs4::FileExt; use futures::FutureExt; use futures::future::{Fuse, pending}; @@ -275,7 +275,7 @@ impl Default for KnownPeersManagerConfig { Self { enable_known_peers_source: true, cache_size: KNOWN_PEERS_CACHE_SIZE, - ignore_peer_list: Default::default(), + ignore_peer_list: HashSet::new(), path: None, failed_address_cache_removal_interval: REMOVE_KNOWN_PEERS_GRACE_PERIOD, failed_address_kademlia_removal_interval: REMOVE_KNOWN_PEERS_GRACE_PERIOD_FOR_KADEMLIA, @@ -474,7 +474,7 @@ impl KnownPeersManager { known_peers, networking_parameters_save_delay: Self::default_delay(), known_peers_slots, - address_removed: Default::default(), + address_removed: Bag::default(), config, }) } diff --git a/crates/shared/ab-networking/src/behavior/tests.rs b/crates/shared/ab-networking/src/behavior/tests.rs index b8a10a062c..5774c8a094 100644 --- a/crates/shared/ab-networking/src/behavior/tests.rs +++ b/crates/shared/ab-networking/src/behavior/tests.rs @@ -11,6 +11,7 @@ use libp2p::{Multiaddr, PeerId}; use parity_scale_codec::{Decode, Encode}; use parking_lot::Mutex; use schnellru::{ByLength, LruMap}; +use std::collections::HashSet; use std::future::Future; use std::pin::Pin; use std::str::FromStr; @@ -289,7 +290,7 @@ async fn test_known_peers_removal_address_after_specified_interval() { let config = KnownPeersManagerConfig { enable_known_peers_source: false, cache_size: 100, - ignore_peer_list: Default::default(), + ignore_peer_list: HashSet::new(), path: None, failed_address_cache_removal_interval: Duration::from_millis(100), ..Default::default() diff --git a/crates/shared/ab-networking/src/node_runner.rs b/crates/shared/ab-networking/src/node_runner.rs index cbfeb5b03a..4221d41444 100644 --- a/crates/shared/ab-networking/src/node_runner.rs +++ b/crates/shared/ab-networking/src/node_runner.rs @@ -236,7 +236,7 @@ impl NodeRunner { loop { futures::select! { - _ = &mut self.random_query_timeout => { + () = &mut self.random_query_timeout => { self.handle_random_query_interval(); // Increase interval 2x, but to at most 1 minute. self.random_query_timeout = @@ -259,11 +259,11 @@ impl NodeRunner { break; } }, - _ = self.known_peers_registry.run().fuse() => { + () = self.known_peers_registry.run().fuse() => { trace!("Network parameters registry runner exited"); }, - _ = &mut self.periodical_tasks_interval => { - self.handle_periodical_tasks().await; + () = &mut self.periodical_tasks_interval => { + self.handle_periodical_tasks(); self.periodical_tasks_interval = Box::pin(tokio::time::sleep(Duration::from_secs(5)).fuse()); @@ -379,7 +379,7 @@ impl NodeRunner { } /// Handles periodical tasks. - async fn handle_periodical_tasks(&mut self) { + fn handle_periodical_tasks(&mut self) { // Log current connections. let network_info = self.swarm.network_info(); let connections = network_info.connection_counters(); @@ -454,9 +454,10 @@ impl NodeRunner { } async fn handle_swarm_event(&mut self, swarm_event: SwarmEvent) { + #[expect(clippy::ref_patterns, reason = "Much less awkward this way")] match swarm_event { SwarmEvent::Behaviour(Event::Identify(event)) => { - self.handle_identify_event(event); + self.handle_identify_event(*event); } SwarmEvent::Behaviour(Event::Kademlia(event)) => { self.handle_kademlia_event(event); @@ -929,7 +930,7 @@ impl NodeRunner { sender, peer.peer_id, "GetClosestPeersOk", - &id, + id, ) || cancelled; } } @@ -946,7 +947,7 @@ impl NodeRunner { sender, peer.peer_id, "GetClosestPeersError::Timeout", - &id, + id, ) || cancelled; } } @@ -980,7 +981,7 @@ impl NodeRunner { sender, rec, "GetRecordOk", - &id, + id, ) || cancelled; } Ok(GetRecordOk::FinishedWithNoAdditionalRecord { .. }) => { @@ -1029,7 +1030,7 @@ impl NodeRunner { sender, provider, "GetProvidersOk", - &id, + id, ) || cancelled; } } @@ -1075,7 +1076,7 @@ impl NodeRunner { sender, (), "PutRecordOk", - &id, + id, ) || cancelled; } Err(error) => { @@ -1113,7 +1114,7 @@ impl NodeRunner { sender, (), "Bootstrap", - &id, + id, ) || cancelled; } Err(error) => { @@ -1137,13 +1138,13 @@ impl NodeRunner { sender: &mpsc::UnboundedSender, value: T, channel: &'static str, - id: &QueryId, + id: QueryId, ) -> bool { if sender.unbounded_send(value).is_err() { debug!("{} channel was dropped", channel); // Cancel query - if let Some(mut query) = kademlia.query_mut(id) { + if let Some(mut query) = kademlia.query_mut(&id) { query.finish(); } true @@ -1525,7 +1526,7 @@ impl NodeRunner { metrics.record(ping_event); } SwarmEvent::Behaviour(Event::Identify(identify_event)) => { - metrics.record(identify_event); + metrics.record(identify_event.as_ref()); } SwarmEvent::Behaviour(Event::Kademlia(kademlia_event)) => { metrics.record(kademlia_event); diff --git a/crates/shared/ab-networking/src/protocols/autonat_wrapper.rs b/crates/shared/ab-networking/src/protocols/autonat_wrapper.rs index 405093dbf6..7c51087196 100644 --- a/crates/shared/ab-networking/src/protocols/autonat_wrapper.rs +++ b/crates/shared/ab-networking/src/protocols/autonat_wrapper.rs @@ -44,7 +44,7 @@ impl Behaviour { Self { inner, private_ips_enabled: !config.inner_config.only_global_ips, - listen_addresses: Default::default(), + listen_addresses: HashSet::new(), } } diff --git a/crates/shared/ab-networking/src/protocols/request_response/handlers/cached_piece_by_index/tests.rs b/crates/shared/ab-networking/src/protocols/request_response/handlers/cached_piece_by_index/tests.rs index 77b31bf731..0be1b94d66 100644 --- a/crates/shared/ab-networking/src/protocols/request_response/handlers/cached_piece_by_index/tests.rs +++ b/crates/shared/ab-networking/src/protocols/request_response/handlers/cached_piece_by_index/tests.rs @@ -52,7 +52,7 @@ fn closest_peers_encoding() { (peer_id, addresses) }]); - assert!(ClosestPeers::decode(&mut closest_peers.encode().as_ref()).is_err()); + ClosestPeers::decode(&mut closest_peers.encode().as_ref()).unwrap_err(); } // Addresses must end with correct `/p2p` @@ -69,13 +69,13 @@ fn closest_peers_encoding() { (peer_id, addresses) }]); - assert!(ClosestPeers::decode(&mut closest_peers.encode().as_ref()).is_err()); + ClosestPeers::decode(&mut closest_peers.encode().as_ref()).unwrap_err(); } // Addresses list must not be empty { let closest_peers = ClosestPeers::from(vec![(PeerId::random(), vec![])]); - assert!(ClosestPeers::decode(&mut closest_peers.encode().as_ref()).is_err()); + ClosestPeers::decode(&mut closest_peers.encode().as_ref()).unwrap_err(); } } diff --git a/crates/shared/ab-networking/src/protocols/request_response/request_response_factory.rs b/crates/shared/ab-networking/src/protocols/request_response/request_response_factory.rs index 56643ccd04..abf2573f1e 100644 --- a/crates/shared/ab-networking/src/protocols/request_response/request_response_factory.rs +++ b/crates/shared/ab-networking/src/protocols/request_response/request_response_factory.rs @@ -29,8 +29,8 @@ //! - Requests have a certain time limit before they time out. This time includes the time it takes //! to send/receive the request and response. //! -//! - If provided, a ["requests processing"](ProtocolConfig::inbound_queue) channel is used to -//! handle incoming requests. +//! - If provided, a [requests processing](ProtocolConfig::inbound_queue) channel is used to handle +//! incoming requests. //! //! Original file commit: @@ -40,6 +40,7 @@ mod tests; use async_trait::async_trait; use futures::channel::{mpsc, oneshot}; use futures::prelude::*; +use futures::stream::FuturesUnordered; use libp2p::StreamProtocol; use libp2p::core::transport::PortUse; use libp2p::core::{Endpoint, Multiaddr}; @@ -330,10 +331,10 @@ struct RequestProcessingOutcome { impl RequestResponseFactoryBehaviour { /// Creates a new behaviour. Must be passed a list of supported protocols. Returns an error if /// the same protocol is passed twice. - pub fn new( - list: impl IntoIterator>, - max_concurrent_streams: usize, - ) -> Result { + pub fn new(list: List, max_concurrent_streams: usize) -> Result + where + List: IntoIterator>, + { let mut protocols = HashMap::new(); let mut request_handlers = Vec::new(); for mut handler in list { @@ -371,8 +372,8 @@ impl RequestResponseFactoryBehaviour { Ok(Self { protocols, - pending_requests: Default::default(), - pending_responses: Default::default(), + pending_requests: HashMap::new(), + pending_responses: FuturesUnordered::new(), message_request: None, request_handlers, }) diff --git a/crates/shared/ab-networking/src/protocols/request_response/request_response_factory/tests.rs b/crates/shared/ab-networking/src/protocols/request_response/request_response_factory/tests.rs index 288307aa2f..9481aa815e 100644 --- a/crates/shared/ab-networking/src/protocols/request_response/request_response_factory/tests.rs +++ b/crates/shared/ab-networking/src/protocols/request_response/request_response_factory/tests.rs @@ -190,7 +190,7 @@ async fn max_response_size_exceeded() { if let SwarmEvent::Behaviour(Event::InboundRequest { result, .. }) = swarm_0.select_next_some().await { - assert!(result.is_ok()); + result.unwrap_err(); } } }); @@ -211,7 +211,7 @@ async fn max_response_size_exceeded() { if let SwarmEvent::Behaviour(Event::RequestFinished { result, .. }) = swarm_1.select_next_some().await { - assert!(result.is_err()); + result.unwrap_err(); break; } } diff --git a/crates/shared/ab-networking/src/protocols/reserved_peers.rs b/crates/shared/ab-networking/src/protocols/reserved_peers.rs index 2aa62f28cc..b032b49920 100644 --- a/crates/shared/ab-networking/src/protocols/reserved_peers.rs +++ b/crates/shared/ab-networking/src/protocols/reserved_peers.rs @@ -212,7 +212,7 @@ impl NetworkBehaviour for Behaviour { &mut self, _: PeerId, _: ConnectionId, - _: THandlerOutEvent, + (): THandlerOutEvent, ) { } diff --git a/crates/shared/ab-networking/src/protocols/reserved_peers/tests.rs b/crates/shared/ab-networking/src/protocols/reserved_peers/tests.rs index 66b21f9c11..33d29dbe13 100644 --- a/crates/shared/ab-networking/src/protocols/reserved_peers/tests.rs +++ b/crates/shared/ab-networking/src/protocols/reserved_peers/tests.rs @@ -15,7 +15,7 @@ const DIALING_INTERVAL_IN_SECS: Duration = Duration::from_secs(1); // TODO: Un-ignore once test doesn't take forever to run #[tokio::test] -#[ignore] +#[ignore = "Very slow"] async fn test_connection_breaks_after_timeout_without_reservation() { let connection_timeout = Duration::from_millis(300); let long_delay = Duration::from_secs(12); @@ -48,7 +48,7 @@ async fn test_connection_breaks_after_timeout_without_reservation() { select! { _ = peer1.select_next_some().fuse() => {}, _ = peer2.select_next_some().fuse() => {}, - _ = sleep(long_delay).fuse() => { + () = sleep(long_delay).fuse() => { break; } } @@ -61,7 +61,7 @@ async fn test_connection_breaks_after_timeout_without_reservation() { // TODO: Un-ignore once test doesn't take forever to run #[tokio::test] -#[ignore] +#[ignore = "Very slow"] async fn test_connection_reservation() { let connection_timeout = Duration::from_millis(300); let long_delay = Duration::from_secs(12); @@ -98,7 +98,7 @@ async fn test_connection_reservation() { select! { _ = peer1.select_next_some().fuse() => {}, _ = peer2.select_next_some().fuse() => {}, - _ = sleep(long_delay).fuse() => { + () = sleep(long_delay).fuse() => { break; } } @@ -111,7 +111,7 @@ async fn test_connection_reservation() { // TODO: Un-ignore once test doesn't take forever to run #[tokio::test] -#[ignore] +#[ignore = "Very slow"] async fn test_connection_reservation_symmetry() { let connection_timeout = Duration::from_millis(300); let long_delay = Duration::from_secs(12); @@ -146,7 +146,7 @@ async fn test_connection_reservation_symmetry() { select! { _ = peer1.select_next_some().fuse() => {}, _ = peer2.select_next_some().fuse() => {}, - _ = sleep(long_delay).fuse() => { + () = sleep(long_delay).fuse() => { break; } } @@ -185,7 +185,7 @@ async fn test_reserved_peers_dial_event() { assert_eq!(peer_id, Some(peer2_id)); } }, - _ = sleep(long_delay).fuse() => { + () = sleep(long_delay).fuse() => { panic!("No reserved peers dialing."); } } diff --git a/crates/shared/ab-networking/src/utils/piece_provider.rs b/crates/shared/ab-networking/src/utils/piece_provider.rs index 15efd84a76..91b4c706d3 100644 --- a/crates/shared/ab-networking/src/utils/piece_provider.rs +++ b/crates/shared/ab-networking/src/utils/piece_provider.rs @@ -245,7 +245,7 @@ where Err(err) => { debug!(%piece_index, ?err, "Cannot get connected peers (DSN L1 lookup)"); - Default::default() + Vec::new() } }; @@ -833,7 +833,7 @@ struct DownloadedPieceFromPeer<'a> { /// `check_cached_pieces` contains a list of pieces for peer to filter-out according to locally /// caches pieces, `cached_pieces` and `not_cached_pieces` contain piece indices peer claims is /// known to have or not have already -#[expect(clippy::too_many_arguments)] +#[expect(clippy::too_many_arguments, reason = "Internal API")] async fn download_cached_piece_from_peer<'a, PV>( node: &'a Node, piece_validator: &'a PV, diff --git a/crates/shared/ab-proof-of-space/src/chiapos.rs b/crates/shared/ab-proof-of-space/src/chiapos.rs index 4015e5e654..5fbdc16729 100644 --- a/crates/shared/ab-proof-of-space/src/chiapos.rs +++ b/crates/shared/ab-proof-of-space/src/chiapos.rs @@ -93,7 +93,7 @@ where s_bucket: SBucket, ) -> Option<[u8; 2usize.pow(u32::from(NUM_TABLES - 1)) * usize::from(K) / u8::BITS as usize]> { - let proof_index = PosProofs::proof_index_for_s_bucket(self.found_proofs, s_bucket)?; + let proof_index = PosProofs::proof_index_for_s_bucket(&self.found_proofs, s_bucket)?; Some(self.proofs[proof_index]) } diff --git a/crates/shared/ab-proof-of-space/src/chiapos/table.rs b/crates/shared/ab-proof-of-space/src/chiapos/table.rs index 298b929f8f..7084c09fce 100644 --- a/crates/shared/ab-proof-of-space/src/chiapos/table.rs +++ b/crates/shared/ab-proof-of-space/src/chiapos/table.rs @@ -1031,16 +1031,11 @@ where ys.write_copy_of_slice(&ys_batch); } - // SAFETY: Converting a boxed array to a vector of the same size, which has the same memory - // layout, all elements were initialized - let ys = unsafe { - let ys_len = ys.len(); - let ys = Box::into_raw(ys); - Vec::from_raw_parts(ys.cast(), ys_len, ys_len) - }; + // SAFETY: All elements were initialized + let ys = unsafe { ys.assume_init_ref() }; // TODO: Try to group buckets in the process of collecting `y`s - let buckets = group_by_buckets::(&ys); + let buckets = group_by_buckets::(ys); Self::First { buckets } } @@ -1082,16 +1077,11 @@ where ys.write_copy_of_slice(&ys_batch); } - // SAFETY: Converting a boxed array to a vector of the same size, which has the same memory - // layout, all elements were initialized - let ys = unsafe { - let ys_len = ys.len(); - let ys = Box::into_raw(ys); - Vec::from_raw_parts(ys.cast(), ys_len, ys_len) - }; + // SAFETY: All elements were initialized + let ys = unsafe { ys.assume_init_ref() }; // TODO: Try to group buckets in the process of collecting `y`s - let buckets = group_by_buckets::(&ys); + let buckets = group_by_buckets::(ys); Self::First { buckets } } diff --git a/crates/shared/ab-proof-of-space/src/chiapos/table/tests.rs b/crates/shared/ab-proof-of-space/src/chiapos/table/tests.rs index 76713ec82b..b270a81ec1 100644 --- a/crates/shared/ab-proof-of-space/src/chiapos/table/tests.rs +++ b/crates/shared/ab-proof-of-space/src/chiapos/table/tests.rs @@ -84,24 +84,31 @@ fn test_compute_f1_k22() { } #[cfg(feature = "alloc")] -fn check_match(yl: usize, yr: usize) -> bool { - let yl = (yl as u64).cast_signed(); - let yr = (yr as u64).cast_signed(); - let param_b = i64::from(PARAM_B); - let param_c = i64::from(PARAM_C); - let param_bc = i64::from(PARAM_BC); +fn check_match(yl: u32, yr: u32) -> bool { + let param_b = u64::from(PARAM_B); + let param_c = u64::from(PARAM_C); + let param_bc = u64::from(PARAM_BC); + let yl = u64::from(yl); + let yr = u64::from(yr); + let bl = yl / param_bc; let br = yr / param_bc; if bl + 1 != br { // Buckets don't match return false; } + + let lp = (yl % param_bc) / param_c; + let rp = (yr % param_bc) / param_c; + let lc = (yl % param_bc) % param_c; + let rc = (yr % param_bc) % param_c; + for m in 0..(1 << PARAM_EXT) { - if (((yr % param_bc) / param_c - (yl % param_bc) / param_c) - m) % param_b == 0 { + if rp % param_b == (lp + m) % param_b { let mut c_diff = 2 * m + bl % 2; c_diff *= c_diff; - if (((yr % param_bc) % param_c - (yl % param_bc) % param_c) - c_diff) % param_c == 0 { + if rc == (lc + c_diff) % param_c { return true; } } @@ -187,10 +194,8 @@ fn test_matches() { ) }; for m in matches { - // SAFETY: All `y`s are initialized - let yl = usize::from(parent_table_ys[usize::from(m.left_position)]); - // SAFETY: All `y`s are initialized - let yr = usize::from(parent_table_ys[usize::from(m.right_position)]); + let yl = u32::from(parent_table_ys[usize::from(m.left_position)]); + let yr = u32::from(parent_table_ys[usize::from(m.right_position)]); assert!(check_match(yl, yr)); total_matches += 1; diff --git a/crates/shared/ab-proof-of-space/src/lib.rs b/crates/shared/ab-proof-of-space/src/lib.rs index a4aef14f84..b05d0a5399 100644 --- a/crates/shared/ab-proof-of-space/src/lib.rs +++ b/crates/shared/ab-proof-of-space/src/lib.rs @@ -71,14 +71,14 @@ impl PosProofs { /// directly if the use case allows. #[inline] pub fn for_s_bucket(&self, s_bucket: SBucket) -> Option { - let proof_index = Self::proof_index_for_s_bucket(self.found_proofs, s_bucket)?; + let proof_index = Self::proof_index_for_s_bucket(&self.found_proofs, s_bucket)?; Some(self.proofs[proof_index]) } #[inline(always)] fn proof_index_for_s_bucket( - found_proofs: [u8; Record::NUM_S_BUCKETS / u8::BITS as usize], + found_proofs: &[u8; Record::NUM_S_BUCKETS / u8::BITS as usize], s_bucket: SBucket, ) -> Option { let bits_offset = usize::from(s_bucket); diff --git a/crates/shared/ab-proof-of-time/src/aes/aarch64.rs b/crates/shared/ab-proof-of-time/src/aes/aarch64.rs index 92f5023381..a30ff71eef 100644 --- a/crates/shared/ab-proof-of-time/src/aes/aarch64.rs +++ b/crates/shared/ab-proof-of-time/src/aes/aarch64.rs @@ -1,5 +1,8 @@ use ab_core_primitives::pot::{PotCheckpoints, PotOutput}; -use core::arch::aarch64::*; +use core::arch::aarch64::{ + uint8x16_t, vaesdq_u8, vaeseq_u8, vaesimcq_u8, vaesmcq_u8, vceqq_u8, vdupq_n_u8, vdupq_n_u32, + veorq_u8, vgetq_lane_u32, vminvq_u8, vreinterpretq_u8_u32, vreinterpretq_u32_u8, +}; use core::simd::u8x16; use core::slice; diff --git a/crates/shared/ab-proof-of-time/src/aes/x86_64.rs b/crates/shared/ab-proof-of-time/src/aes/x86_64.rs index 6c7332b8dd..902ea0e86f 100644 --- a/crates/shared/ab-proof-of-time/src/aes/x86_64.rs +++ b/crates/shared/ab-proof-of-time/src/aes/x86_64.rs @@ -1,5 +1,13 @@ use ab_core_primitives::pot::{PotCheckpoints, PotOutput}; -use core::arch::x86_64::*; +use core::arch::x86_64::{ + __m128i, __m256i, __m512i, _mm_aesdec_si128, _mm_aesdeclast_si128, _mm_aesenc_si128, + _mm_aesenclast_si128, _mm_aesimc_si128, _mm_aeskeygenassist_si128, _mm_set1_epi8, + _mm_setzero_si128, _mm_shuffle_epi32, _mm_slli_si128, _mm_test_all_zeros, _mm_xor_si128, + _mm256_aesdec_epi128, _mm256_aesdeclast_epi128, _mm256_aesenc_epi128, _mm256_aesenclast_epi128, + _mm256_broadcastsi128_si256, _mm256_cmpeq_epi64, _mm256_set1_epi64x, _mm256_testc_si256, + _mm256_xor_si256, _mm512_aesdec_epi128, _mm512_aesdeclast_epi128, _mm512_aesenc_epi128, + _mm512_aesenclast_epi128, _mm512_broadcast_i32x4, _mm512_cmpeq_epu64_mask, _mm512_xor_si512, +}; use core::array; use core::simd::{u8x16, u8x32, u8x64};