From 392424788c9b3562778dc67cb1b5bb3a03caa0f7 Mon Sep 17 00:00:00 2001 From: Dmitriy Khaustov Date: Mon, 16 Sep 2024 12:16:29 +0300 Subject: [PATCH] Fix: clang tidy issues (#2208) * refactor: Empty Signed-off-by: Dmitriy Khaustov aka xDimon * refactor: log msgs Signed-off-by: Dmitriy Khaustov aka xDimon * refactor: std::array instead C-array Signed-off-by: Dmitriy Khaustov aka xDimon * refactor: add missed todo-labels Signed-off-by: Dmitriy Khaustov aka xDimon * fix: crash in ProcessAndPipes Signed-off-by: Dmitriy Khaustov aka xDimon * fix: use requires and concepts Signed-off-by: Dmitriy Khaustov aka xDimon * fix: wrong using of movement Signed-off-by: Dmitriy Khaustov aka xDimon * fix: redundant or missed initializer Signed-off-by: Dmitriy Khaustov aka xDimon * fix: c-array warnings Signed-off-by: Dmitriy Khaustov aka xDimon * fix: enum size Signed-off-by: Dmitriy Khaustov aka xDimon * fix: clang-format-18 issues Signed-off-by: Dmitriy Khaustov aka xDimon * fix: naming Signed-off-by: Dmitriy Khaustov aka xDimon * fix: const cast warnings Signed-off-by: Dmitriy Khaustov aka xDimon * fix: static downcast warnings Signed-off-by: Dmitriy Khaustov aka xDimon * fix: reinterpret cast warnings Signed-off-by: Dmitriy Khaustov aka xDimon * fix: const or ref data members Signed-off-by: Dmitriy Khaustov aka xDimon * fix: pointers arithmetic Signed-off-by: Dmitriy Khaustov aka xDimon * fix: missed destructor Signed-off-by: Dmitriy Khaustov aka xDimon * fix: non-const globals Signed-off-by: Dmitriy Khaustov aka xDimon * fix: narrowing conversion warnings Signed-off-by: Dmitriy Khaustov aka xDimon * fix: use modern ranges algorithms Signed-off-by: Dmitriy Khaustov aka xDimon * fix: using namespace Signed-off-by: Dmitriy Khaustov aka xDimon * fix: typedef vs using Signed-off-by: Dmitriy Khaustov aka xDimon * fix: wrong rvalue and forward Signed-off-by: Dmitriy Khaustov aka xDimon * fix: else after return or break Signed-off-by: Dmitriy Khaustov aka xDimon * fix: avoid-endl warnings Signed-off-by: Dmitriy Khaustov aka xDimon * fix: avoid-do-while warnings Signed-off-by: Dmitriy Khaustov aka xDimon * fix: missing-std::forward warnings Signed-off-by: Dmitriy Khaustov aka xDimon * fix: avoid making a copy Signed-off-by: Dmitriy Khaustov aka xDimon * fix: movement of trivially-copyable types Signed-off-by: Dmitriy Khaustov aka xDimon * fix: move instead once-copy Signed-off-by: Dmitriy Khaustov aka xDimon * fix: use designated initializers Signed-off-by: Dmitriy Khaustov aka xDimon * fix: container contains Signed-off-by: Dmitriy Khaustov aka xDimon * fix: using c-vararg calls Signed-off-by: Dmitriy Khaustov aka xDimon * fix: add special member-func Signed-off-by: Dmitriy Khaustov aka xDimon * fix: return value Signed-off-by: Dmitriy Khaustov aka xDimon * fix: getting value of wrapped ref Signed-off-by: Dmitriy Khaustov aka xDimon * fix: virtual-override warnings Signed-off-by: Dmitriy Khaustov aka xDimon * fix: avoid union access Signed-off-by: Dmitriy Khaustov aka xDimon * fix: macro warnings Signed-off-by: Dmitriy Khaustov aka xDimon * fix: replace push* by emplace* Signed-off-by: Dmitriy Khaustov aka xDimon * fix: var/member init warnings Signed-off-by: Dmitriy Khaustov aka xDimon * fix: reserve before insert in loop Signed-off-by: Dmitriy Khaustov aka xDimon * fix: array element access by non-cont index Signed-off-by: Dmitriy Khaustov aka xDimon * fix: update .clang-tidy settings file Signed-off-by: Dmitriy Khaustov aka xDimon * fix: remaining various warnings Signed-off-by: Dmitriy Khaustov aka xDimon * Revert "refactor: Empty" This reverts commit 47a1133f9d308557458d1c84b6fd0a69e308ecbe. * fix: mock classes Signed-off-by: Dmitriy Khaustov aka xDimon * fix: broken author api Signed-off-by: Dmitriy Khaustov aka xDimon * fix: infinite recursion in BufferView Signed-off-by: Dmitriy Khaustov aka xDimon * fix: decoding of version Signed-off-by: Dmitriy Khaustov aka xDimon * rollback: unintended changes Signed-off-by: Dmitriy Khaustov aka xDimon * fix: review issues Signed-off-by: Dmitriy Khaustov aka xDimon * fix: CI's gcc steps Signed-off-by: Dmitriy Khaustov aka xDimon * fix: newly detected clang-tidy warnings Signed-off-by: Dmitriy Khaustov aka xDimon * hotfix Signed-off-by: Dmitriy Khaustov aka xDimon --------- Signed-off-by: Dmitriy Khaustov aka xDimon --- .clang-tidy | 51 +- .github/workflows/test.yml | 16 +- CMakeLists.txt | 6 +- cmake/Hunter/init.cmake | 6 + cmake/functions.cmake | 10 +- core/api/jrpc/jrpc_handle_batch.cpp | 7 +- core/api/jrpc/value_converter.hpp | 25 +- .../service/author/impl/author_api_impl.cpp | 18 +- core/api/service/beefy/rpc.cpp | 4 +- .../api/service/chain/impl/chain_api_impl.cpp | 2 +- .../service/chain/requests/get_block_hash.cpp | 4 +- .../child_state/impl/child_state_api_impl.cpp | 2 +- core/api/service/impl/api_service_impl.cpp | 27 +- core/api/service/mmr/rpc.cpp | 23 +- .../api/service/state/impl/state_api_impl.cpp | 13 +- core/api/transport/impl/ws/ws_session.cpp | 7 +- core/application/app_configuration.hpp | 18 +- core/application/app_state_manager.hpp | 3 +- .../impl/app_configuration_impl.cpp | 63 ++- .../impl/app_configuration_impl.hpp | 2 +- .../impl/app_state_manager_impl.cpp | 2 + core/application/impl/chain_spec_impl.cpp | 23 +- .../impl/kagome_application_impl.cpp | 5 +- .../modes/print_chain_info_mode.cpp | 5 +- core/application/sync_method.hpp | 4 +- .../protobuf/CMakeLists.txt | 10 +- .../publisher/address_publisher.cpp | 1 + core/authority_discovery/query/query_impl.cpp | 39 +- .../impl/block_builder_factory_impl.cpp | 14 +- core/authorship/impl/block_builder_impl.cpp | 2 +- core/benchmark/block_execution_benchmark.cpp | 19 +- core/blockchain/block_header_repository.hpp | 5 +- core/blockchain/block_tree.hpp | 5 +- core/blockchain/block_tree_error.hpp | 2 +- core/blockchain/impl/block_tree_impl.cpp | 52 +- core/blockchain/impl/block_tree_impl.hpp | 2 +- core/blockchain/impl/cached_tree.cpp | 12 +- core/common/blob.hpp | 8 +- core/common/buffer.hpp | 7 +- core/common/buffer_or_view.hpp | 10 +- core/common/buffer_view.hpp | 18 +- core/common/hexutil.hpp | 9 +- core/common/int_serialization.cpp | 10 +- core/common/literals.hpp | 26 +- core/common/lru_cache.hpp | 21 +- core/common/optref.hpp | 12 +- core/common/outcome_throw.hpp | 6 +- core/common/size_limited_containers.hpp | 77 ++- core/common/span_adl.hpp | 6 +- core/common/spin_lock.hpp | 2 + core/common/tagged.hpp | 7 +- core/common/unused.hpp | 4 +- core/common/uri.cpp | 35 +- core/common/wrapper.hpp | 5 +- core/consensus/babe/impl/babe.cpp | 30 +- core/consensus/babe/impl/babe.hpp | 6 +- .../babe/impl/babe_block_validator_impl.cpp | 7 +- .../babe/impl/babe_config_repository_impl.cpp | 43 +- .../consensus/babe/impl/babe_lottery_impl.hpp | 4 +- core/consensus/babe/impl/threshold_util.cpp | 3 +- .../babe/types/babe_block_header.hpp | 4 +- .../consensus/babe/types/scheduled_change.hpp | 2 +- core/consensus/beefy/impl/beefy_impl.cpp | 59 ++- core/consensus/beefy/types.hpp | 3 +- core/consensus/grandpa/ancestry_verifier.hpp | 3 +- .../grandpa/impl/authority_manager_impl.cpp | 48 +- .../grandpa/impl/environment_impl.cpp | 134 +++--- core/consensus/grandpa/impl/grandpa_impl.cpp | 65 ++- core/consensus/grandpa/impl/grandpa_impl.hpp | 2 +- .../impl/verified_justification_queue.cpp | 6 +- .../impl/verified_justification_queue.hpp | 2 +- .../grandpa/impl/voting_round_impl.cpp | 53 +- .../grandpa/impl/voting_round_impl.hpp | 7 +- .../grandpa/justification_observer.hpp | 2 +- core/consensus/grandpa/structs.hpp | 24 +- core/consensus/grandpa/types/authority.hpp | 2 +- .../grandpa/vote_graph/vote_graph_impl.cpp | 32 +- core/consensus/grandpa/voter_set.hpp | 8 +- .../timeline/impl/block_appender_base.cpp | 10 +- .../timeline/impl/block_executor_impl.cpp | 23 +- .../impl/block_header_appender_impl.cpp | 2 +- .../timeline/impl/consensus_selector_impl.cpp | 30 +- .../timeline/impl/slots_util_impl.cpp | 1 - .../consensus/timeline/impl/timeline_impl.cpp | 2 +- .../consensus/timeline/impl/timeline_impl.hpp | 2 +- core/consensus/timeline/sync_state.hpp | 4 +- core/consensus/timeline/types.hpp | 2 +- .../bandersnatch_provider_impl.cpp | 11 +- .../bandersnatch_provider_impl.hpp | 2 +- core/crypto/bandersnatch/vrf.cpp | 4 +- core/crypto/bandersnatch/vrf.hpp | 14 +- core/crypto/bandersnatch_types.hpp | 34 +- core/crypto/bip39/bip39_types.hpp | 2 +- core/crypto/bip39/dictionary.cpp | 7 +- core/crypto/bip39/dictionary.hpp | 2 +- core/crypto/bip39/entropy_accumulator.hpp | 4 +- .../crypto/bip39/impl/bip39_provider_impl.cpp | 3 +- core/crypto/bip39/mnemonic.cpp | 19 +- core/crypto/bip39/mnemonic.hpp | 2 +- core/crypto/common.hpp | 18 +- core/crypto/ecdsa/ecdsa_provider_impl.cpp | 2 +- core/crypto/ecdsa/ecdsa_provider_impl.hpp | 2 +- core/crypto/ecdsa_types.hpp | 18 +- core/crypto/ed25519/ed25519_provider_impl.cpp | 17 +- core/crypto/ed25519/ed25519_provider_impl.hpp | 2 +- core/crypto/ed25519_types.hpp | 26 +- .../elliptic_curves/elliptic_curves_impl.cpp | 5 +- core/crypto/hasher/blake2b_stream_hasher.hpp | 7 +- core/crypto/key_store.hpp | 2 +- core/crypto/key_store/key_file_storage.cpp | 3 +- core/crypto/key_store/key_file_storage.hpp | 2 +- core/crypto/key_store/key_store_impl.cpp | 10 +- core/crypto/key_store/key_type.hpp | 2 +- core/crypto/key_store/session_keys.cpp | 5 +- core/crypto/key_store/session_keys.hpp | 2 +- .../pbkdf2/impl/pbkdf2_provider_impl.cpp | 1 + core/crypto/pbkdf2/pbkdf2_provider.hpp | 2 +- .../secp256k1/secp256k1_provider_impl.hpp | 2 +- core/crypto/sr25519/sr25519_provider_impl.cpp | 11 +- core/crypto/sr25519_provider.hpp | 2 +- core/crypto/sr25519_types.hpp | 4 +- core/crypto/vrf/vrf_provider_impl.cpp | 11 +- core/dispute_coordinator/impl/batch.cpp | 14 +- core/dispute_coordinator/impl/batch.hpp | 8 +- .../impl/candidate_vote_state.cpp | 2 +- .../impl/dispute_coordinator_impl.cpp | 189 ++++---- .../impl/dispute_coordinator_impl.hpp | 3 +- .../dispute_coordinator/impl/runtime_info.cpp | 3 +- .../impl/sending_dispute.cpp | 20 +- .../impl/sending_dispute.hpp | 4 +- .../dispute_coordinator/impl/storage_impl.cpp | 4 +- .../participation/impl/participation_impl.cpp | 47 +- .../participation/impl/participation_impl.hpp | 6 +- .../participation/impl/queues_impl.cpp | 6 +- .../impl/prioritized_selection.cpp | 14 +- .../provisioner/impl/random_selection.cpp | 8 +- core/filesystem/common.hpp | 2 +- core/host_api/host_api.hpp | 2 +- .../host_api/impl/child_storage_extension.cpp | 6 +- core/host_api/impl/crypto_extension.cpp | 35 +- core/host_api/impl/host_api_impl.cpp | 3 +- core/host_api/impl/host_api_impl.hpp | 3 +- core/host_api/impl/offchain_extension.cpp | 19 +- core/host_api/impl/storage_extension.cpp | 2 +- core/host_api/impl/storage_util.cpp | 8 +- core/injector/application_injector.cpp | 28 +- core/injector/calculate_genesis_state.hpp | 17 +- core/log/configurator.cpp | 6 +- core/log/formatters/ref_and_ptr.hpp | 8 +- core/log/logger.cpp | 35 +- core/log/profiling_logger.cpp | 3 +- core/log/profiling_logger.hpp | 4 +- core/log/trace_macros.hpp | 1 + core/metrics/impl/exposer_impl.cpp | 9 +- core/metrics/impl/prometheus/handler_impl.cpp | 8 +- core/metrics/impl/prometheus/handler_impl.hpp | 2 +- .../metrics/impl/prometheus/registry_impl.cpp | 2 +- .../network/impl/grandpa_transmitter_impl.cpp | 2 + core/network/impl/peer_manager_impl.cpp | 95 ++-- core/network/impl/peer_view.cpp | 6 +- .../protocols/block_announce_protocol.cpp | 13 +- .../impl/protocols/grandpa_protocol.cpp | 20 +- core/network/impl/protocols/light.cpp | 5 +- .../propagate_transactions_protocol.cpp | 7 +- .../impl/protocols/protocol_req_collation.cpp | 9 +- .../impl/protocols/protocol_req_pov.cpp | 22 +- .../impl/protocols/state_protocol_impl.cpp | 6 +- .../impl/protocols/state_protocol_impl.hpp | 4 +- .../impl/protocols/sync_protocol_impl.cpp | 13 +- .../impl/protocols/sync_protocol_impl.hpp | 2 +- core/network/impl/router_libp2p.cpp | 50 +- .../impl/state_protocol_observer_impl.cpp | 9 +- .../impl/state_protocol_observer_impl.hpp | 2 +- core/network/impl/state_sync_request_flow.cpp | 28 +- core/network/impl/state_sync_request_flow.hpp | 8 +- core/network/impl/stream_engine.cpp | 29 +- .../impl/sync_protocol_observer_impl.cpp | 2 +- core/network/impl/synchronizer_impl.cpp | 454 +++++++++--------- core/network/impl/synchronizer_impl.hpp | 9 +- .../impl/transactions_transmitter_impl.cpp | 2 +- core/network/protobuf/CMakeLists.txt | 14 - core/network/types/block_attributes.hpp | 8 +- core/network/types/roles.hpp | 5 +- core/network/types/state_response.hpp | 2 +- core/network/warp/cache.cpp | 8 +- core/network/warp/sync.cpp | 11 +- core/offchain/impl/http_request.cpp | 15 +- core/offchain/impl/offchain_local_storage.cpp | 2 +- core/offchain/impl/offchain_local_storage.hpp | 2 +- .../impl/offchain_persistent_storage.cpp | 2 +- .../impl/offchain_persistent_storage.hpp | 2 +- core/offchain/impl/offchain_worker_impl.cpp | 5 +- core/offchain/offchain_storage.hpp | 4 +- core/offchain/types.hpp | 14 +- core/parachain/approval/approval.cpp | 7 +- .../approval/approval_distribution.cpp | 138 +++--- .../approval/approval_distribution.hpp | 7 +- .../availability/availability_chunk_index.hpp | 8 +- .../availability/fetch/fetch_impl.cpp | 8 +- core/parachain/backing/cluster.cpp | 14 +- core/parachain/backing/grid.hpp | 2 +- core/parachain/backing/grid_tracker.cpp | 21 +- core/parachain/backing/store_impl.cpp | 14 +- core/parachain/pvf/kagome_pvf_worker.cpp | 55 ++- .../pvf/kagome_pvf_worker_injector.hpp | 1 + core/parachain/pvf/module_precompiler.cpp | 14 +- core/parachain/pvf/pool.cpp | 60 +-- core/parachain/pvf/precheck.cpp | 8 +- core/parachain/pvf/pvf_impl.cpp | 33 +- core/parachain/pvf/secure_mode_precheck.cpp | 11 +- core/parachain/pvf/workers.cpp | 15 +- .../validator/backing_implicit_view.cpp | 6 +- core/parachain/validator/fragment_tree.hpp | 29 +- .../validator/impl/fragment_tree.cpp | 39 +- .../impl/parachain_observer_impl.cpp | 22 +- .../validator/impl/parachain_processor.cpp | 186 +++---- .../validator/parachain_processor.hpp | 4 +- .../validator/prospective_parachains.hpp | 16 +- core/parachain/validator/signer.cpp | 3 +- core/primitives/arithmetic_error.hpp | 8 +- core/primitives/block.hpp | 3 +- core/primitives/block_data.hpp | 6 +- core/primitives/block_header.hpp | 16 +- core/primitives/digest.hpp | 4 +- core/primitives/event_types.hpp | 24 +- core/primitives/inherent_data.hpp | 13 +- core/primitives/math.hpp | 4 +- core/primitives/runtime_dispatch_info.hpp | 8 +- core/primitives/ss58_codec.cpp | 2 +- core/primitives/ss58_codec.hpp | 5 +- core/primitives/strobe.hpp | 8 +- core/primitives/token_error.hpp | 8 +- core/primitives/transaction_validity.hpp | 18 +- core/primitives/version.cpp | 4 +- core/primitives/version.hpp | 49 +- core/runtime/CMakeLists.txt | 36 +- .../binaryen/instance_environment_factory.cpp | 10 +- core/runtime/binaryen/module/module_impl.cpp | 3 - .../binaryen/module/module_instance_impl.cpp | 12 +- .../binaryen/runtime_external_interface.cpp | 5 +- core/runtime/common/core_api_factory_impl.cpp | 6 +- core/runtime/common/executor.cpp | 2 +- core/runtime/common/memory_allocator.cpp | 2 +- core/runtime/common/memory_allocator.hpp | 2 +- core/runtime/common/memory_error.hpp | 2 +- .../runtime/common/module_repository_impl.cpp | 3 +- core/runtime/common/runtime_context.cpp | 2 - .../common/runtime_execution_error.hpp | 2 +- .../runtime/common/runtime_instances_pool.cpp | 14 +- .../common/runtime_upgrade_tracker_impl.cpp | 45 +- .../common/trie_storage_provider_impl.cpp | 27 +- .../common/uncompress_code_if_needed.cpp | 1 + core/runtime/module_instance.hpp | 4 +- core/runtime/ptr_size.hpp | 2 +- core/runtime/runtime_api/impl/beefy.cpp | 2 +- core/runtime/runtime_api/impl/lru.hpp | 10 +- .../runtime_api/impl/offchain_worker_api.cpp | 5 +- .../runtime_api/impl/parachain_host.cpp | 9 +- .../impl/parachain_host_types_serde.cpp | 4 +- .../runtime_api/impl/session_keys_api.cpp | 2 +- .../impl/tagged_transaction_queue.cpp | 2 +- .../impl/transaction_payment_api.cpp | 16 +- core/runtime/runtime_context.hpp | 17 +- core/runtime/runtime_upgrade_tracker.hpp | 4 +- core/runtime/types.hpp | 4 +- core/runtime/wabt/instrument.cpp | 19 +- core/runtime/wabt/stack_limiter.cpp | 31 +- core/runtime/wabt/version.cpp | 5 +- core/runtime/wasm_edge/CMakeLists.txt | 8 +- .../runtime/wasm_edge/module_factory_impl.cpp | 54 ++- core/runtime/wavm/module.cpp | 11 +- core/scale/big_fixed_integers.hpp | 20 +- core/scale/libp2p_types.cpp | 19 +- core/scale/std_variant.hpp | 4 +- core/scale/tie.hpp | 2 + core/storage/database_error.hpp | 2 +- core/storage/in_memory/cursor.hpp | 1 + core/storage/in_memory/in_memory_batch.hpp | 3 +- core/storage/in_memory/in_memory_storage.cpp | 2 +- core/storage/map_prefix/prefix.hpp | 2 + core/storage/predefined_keys.hpp | 2 +- core/storage/rocksdb/rocksdb.cpp | 50 +- core/storage/rocksdb/rocksdb.hpp | 1 + core/storage/rocksdb/rocksdb_batch.cpp | 2 +- core/storage/rocksdb/rocksdb_batch.hpp | 1 + core/storage/trie/child_prefix.cpp | 2 - core/storage/trie/child_prefix.hpp | 2 +- core/storage/trie/compact_decode.cpp | 7 +- core/storage/trie/compact_decode.hpp | 2 +- core/storage/trie/compact_encode.cpp | 6 +- .../trie/impl/ephemeral_trie_batch_impl.hpp | 2 +- .../trie/impl/persistent_trie_batch_impl.hpp | 4 +- .../trie/impl/topper_trie_batch_impl.cpp | 2 +- .../trie/impl/topper_trie_batch_impl.hpp | 8 +- core/storage/trie/impl/trie_batch_base.hpp | 10 +- core/storage/trie/on_read.hpp | 1 + .../polkadot_trie/polkadot_trie_cursor.hpp | 2 - .../polkadot_trie_cursor_impl.cpp | 16 +- .../polkadot_trie_cursor_impl.hpp | 3 +- .../trie/polkadot_trie/polkadot_trie_impl.cpp | 33 +- .../trie/polkadot_trie/polkadot_trie_impl.hpp | 12 +- .../storage/trie/polkadot_trie/trie_error.hpp | 2 +- core/storage/trie/polkadot_trie/trie_node.cpp | 7 +- core/storage/trie/polkadot_trie/trie_node.hpp | 6 +- core/storage/trie/raw_cursor.hpp | 2 + core/storage/trie/serialization/codec.hpp | 7 +- .../trie/serialization/polkadot_codec.cpp | 13 +- .../trie/serialization/polkadot_codec.hpp | 2 +- .../serialization/trie_serializer_impl.cpp | 9 +- core/storage/trie/trie_batches.hpp | 2 - core/storage/trie/types.hpp | 2 +- .../trie_pruner/impl/trie_pruner_impl.cpp | 36 +- .../trie_pruner/impl/trie_pruner_impl.hpp | 16 +- core/telemetry/endpoint.hpp | 2 +- core/telemetry/impl/connection_impl.cpp | 9 +- core/telemetry/impl/connection_impl.hpp | 13 +- core/telemetry/impl/message_pool.cpp | 16 +- core/telemetry/impl/service_impl.cpp | 15 +- core/telemetry/service.hpp | 2 +- .../impl/transaction_pool_impl.cpp | 21 +- core/utils/json_unquote.hpp | 2 +- core/utils/kagome_db_editor.cpp | 29 +- core/utils/non_copyable.hpp | 4 + core/utils/pool_handler.hpp | 8 +- core/utils/safe_object.hpp | 5 +- core/utils/spdlog_stderr.hpp | 2 + core/utils/storage_explorer.cpp | 71 +-- core/utils/watchdog.hpp | 11 +- housekeeping/clang-tidy-diff.sh | 18 +- node/main.cpp | 16 +- test/CMakeLists.txt | 1 + test/core/api/client/ws_client.cpp | 5 +- .../state/state_jrpc_processor_test.cpp | 14 +- test/core/blockchain/block_tree_test.cpp | 7 +- test/core/common/blob_test.cpp | 2 +- test/core/consensus/grandpa/literals.hpp | 6 +- .../consensus/grandpa/vote_tracker_test.cpp | 2 +- test/core/crypto/blake2/blake2_test.cpp | 2 +- test/core/network/rpc_libp2p_test.cpp | 8 +- test/core/runtime/executor_test.cpp | 3 +- test/external-project-test/src/main.cpp | 8 +- test/mock/core/host_api/host_api_mock.hpp | 2 +- .../offchain_persistent_storage_mock.hpp | 7 +- .../libp2p/message_read_writer_helper.cpp | 2 +- 344 files changed, 2683 insertions(+), 2320 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 6aa3e5f949..2b16f55798 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -5,9 +5,50 @@ # --- -Checks: '-*,clang-analyzer-*,clang-diagnostic-*,readability-*,modernize-*,boost-*,bugprone-*,cppcoreguidelines-*,google-*,hicpp-*,performance-*,readability-*,-google-readability-namespace-comments,-readability-inconsistent-declaration-parameter-name,-readability-braces-around-statements,-hicpp-signed-bitwise,-google-runtime-references,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-pro-bounds-array-to-pointer-decay,-readability-magic-numbers,-hicpp-explicit-conversions,-hicpp-uppercase-literal-suffix,-readability-uppercase-literal-suffix,-hicpp-no-array-decay,-hicpp-special-member-functions,-bugprone-narrowing-conversions,-modernize-use-nodiscard,-google-readability-braces-around-statements,-hicpp-braces-around-statements,-bugprone-suspicious-semicolon,-readability-named-parameter,-hicpp-named-parameter,-readability-identifier-naming,-modernize-use-trailing-return-type' -WarningsAsErrors: 'modernize-*,cppcoreguidelines-*,boost-*,performance-*,google-build-using-namespace,readability-else-after-return,google-readability-todo' -HeaderFilterRegex: '\.(hpp|h)' +Checks: "-*, + clang-analyzer-*, \ + clang-diagnostic-*, \ + -clang-diagnostic-missing-template-arg-list-after-template-kw, \ + modernize-*, \ + -modernize-use-nodiscard, \ + -modernize-use-trailing-return-type, \ + boost-*, \ + bugprone-*, \ + -bugprone-narrowing-conversions, \ + -bugprone-suspicious-semicolon, \ + cppcoreguidelines-*, \ + -cppcoreguidelines-rvalue-reference-param-not-moved, \ + -cppcoreguidelines-avoid-magic-numbers, \ + -cppcoreguidelines-pro-bounds-array-to-pointer-decay, \ + google-*, \ + -google-readability-namespace-comments, \ + -google-readability-braces-around-statements, \ + -google-runtime-references, \ + hicpp-*, \ + -hicpp-explicit-conversions, \ + -hicpp-uppercase-literal-suffix, \ + -hicpp-signed-bitwise, \ + -hicpp-no-array-decay, \ + -hicpp-special-member-functions, \ + -hicpp-braces-around-statements, \ + -hicpp-named-parameter, \ + performance-*, \ + readability-*, \ + -readability-magic-numbers, \ + -readability-named-parameter, \ + -readability-identifier-naming, \ + -readability-uppercase-literal-suffix, \ + -readability-inconsistent-declaration-parameter-name, \ + -readability-braces-around-statements" +WarningsAsErrors: "modernize-*, \ + cppcoreguidelines-*, \ + boost-*, \ + performance-*, \ + google-build-using-namespace, \ + readability-else-after-return, \ + readability-container-contains, \ + google-readability-todo" +HeaderFilterRegex: '\(hpp|h|pb\.h)' FormatStyle: .clang-format User: bogdan CheckOptions: @@ -53,6 +94,8 @@ CheckOptions: value: '0' - key: bugprone-unused-return-value.CheckedFunctions value: '::std::async;::std::launder;::std::remove;::std::remove_if;::std::unique;::std::unique_ptr::release;::std::basic_string::empty;::std::vector::empty' + - key: cppcoreguidelines-avoid-do-while.IgnoreMacros + value: '1' - key: cppcoreguidelines-no-malloc.Allocations value: '::malloc;::calloc' - key: cppcoreguidelines-no-malloc.Deallocations @@ -243,6 +286,8 @@ CheckOptions: value: '4294967295' - key: readability-identifier-naming.IgnoreFailedSplit value: '0' + - key: readability-identifier-length.Missing + value: '(it|cb|db|id|in|ts|tx|i|n|s)' - key: readability-implicit-bool-conversion.AllowIntegerConditions value: '0' - key: readability-implicit-bool-conversion.AllowPointerConditions diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 493c6809d3..efca05ab0c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -64,12 +64,12 @@ jobs: env: KAGOME_IN_DOCKER: 0 KAGOME_MAC_CI: 1 - - + + Linux: if: false # Need to fix - # ${{ - # !(github.ref == 'refs/heads/master' || + # ${{ + # !(github.ref == 'refs/heads/master' || # startsWith( github.ref, 'refs/tags/' )) }} strategy: fail-fast: false @@ -196,7 +196,7 @@ jobs: kagome_dev_docker_build_tidy: runs-on: ubuntu-latest - timeout-minutes: 180 + timeout-minutes: 600 # TODO(xDimon): revert after merge PR#2208 name: "Linux: clang-tidy" steps: @@ -346,7 +346,7 @@ jobs: KAGOME_PACKAGE_VERSION=${{ env.package_version }} \ DOCKER_REGISTRY_PATH=${DOCKER_REGISTRY_PATH} \ BUILD_TYPE=${{ matrix.options.build_type }} - + - name: "Push Docker Image to GCR" if: env.package_exist == 'False' working-directory: ./housekeeping/docker/kagome-dev @@ -364,7 +364,7 @@ jobs: with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_TOKEN }} - + - name: "Push Docker Image to Docker Hub" if: ${{ (env.package_exist == 'False') && @@ -388,7 +388,7 @@ jobs: with: path: ${{ env.CACHE_PATH }} key: ${{ steps.cache-restore.outputs.cache-primary-key }} - + - name: "Versions Info" if: always() run: | diff --git a/CMakeLists.txt b/CMakeLists.txt index 890ca074ae..0fffa3021d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -36,7 +36,7 @@ set(CMAKE_TOOLCHAIN_FILE CACHE FILEPATH "Default toolchain") # SHA1 hash of the WasmEdge repository archive. -# Required to separate cached runtimes +# Required to separate cached runtimes # compiled with different WasmEdge versions. set(WASMEDGE_ID 58aea400de9179ad3e314c7e84fd4da345b8a643) @@ -195,7 +195,9 @@ include(GNUInstallDirs) include(cmake/install.cmake) include_directories($ - $) + $ + $ # for generated file +) add_subdirectory(core) diff --git a/cmake/Hunter/init.cmake b/cmake/Hunter/init.cmake index 9a9e64516a..22361f6bde 100644 --- a/cmake/Hunter/init.cmake +++ b/cmake/Hunter/init.cmake @@ -32,5 +32,11 @@ set(HUNTER_CACHE_SERVERS # CACHE STRING "Disable binary cache" # ) +# https://hunter.readthedocs.io/en/latest/reference/user-variables.html#hunter-status-debug +# set( +# HUNTER_STATUS_DEBUG ON +# CACHE STRING "Enable output lot of info for debugging" +# ) + include(${CMAKE_CURRENT_LIST_DIR}/HunterGate.cmake) include(${CMAKE_CURRENT_LIST_DIR}/hunter-gate-url.cmake) diff --git a/cmake/functions.cmake b/cmake/functions.cmake index 8ec02e606f..c9fb7b6c4a 100644 --- a/cmake/functions.cmake +++ b/cmake/functions.cmake @@ -96,10 +96,6 @@ function(compile_proto_to_cpp PROTO_LIBRARY_NAME PB_H PB_CC PROTO) set(${PB_CC} ${SCHEMA_OUT_DIR}/${SCHEMA_REL}/${GEN_PB} PARENT_SCOPE) endfunction() -add_custom_target(generated - COMMENT "Building generated files..." - ) - function(add_proto_library NAME) set(SOURCES "") foreach(PROTO IN ITEMS ${ARGN}) @@ -119,8 +115,14 @@ function(add_proto_library NAME) # required for compiling proto targets $ ) + kagome_install(${NAME}) disable_clang_tidy(${NAME}) + if (NOT TARGET generated) + add_custom_target(generated + COMMENT "Building generated files..." + ) + endif() add_dependencies(generated ${NAME}) endfunction() diff --git a/core/api/jrpc/jrpc_handle_batch.cpp b/core/api/jrpc/jrpc_handle_batch.cpp index 9be7a05bca..8919e146d9 100644 --- a/core/api/jrpc/jrpc_handle_batch.cpp +++ b/core/api/jrpc/jrpc_handle_batch.cpp @@ -15,7 +15,7 @@ namespace kagome::api { */ template struct Parser { - Cb cb; + std::remove_reference_t cb; rapidjson::MemoryStream stream{nullptr, 0}; size_t level = 0; @@ -85,6 +85,7 @@ namespace kagome::api { --level; if (level == 1) { const size_t end = stream.Tell(); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) std::string_view request(stream.begin_ + begin, end - begin); cb(request); } @@ -96,7 +97,7 @@ namespace kagome::api { std::string_view request) { std::string request_string; if (!request.empty() && request[0] == '[') { - const auto cb = [&](std::string_view request) { + auto cb = [&](std::string_view request) { request_string = request; auto formatted = handler.HandleRequest(request_string); if (formatted->GetSize() == 0) { @@ -109,7 +110,7 @@ namespace kagome::api { } batch_.append(formatted->GetData(), formatted->GetSize()); }; - Parser parser{cb}; + Parser parser{.cb = std::move(cb)}; if (parser.parse(request)) { if (!batch_.empty()) { batch_.push_back(']'); diff --git a/core/api/jrpc/value_converter.hpp b/core/api/jrpc/value_converter.hpp index f292c74064..1bb78fe30e 100644 --- a/core/api/jrpc/value_converter.hpp +++ b/core/api/jrpc/value_converter.hpp @@ -206,15 +206,13 @@ namespace kagome::api { data["stateVersion"] = makeValue(val.state_version); jArray apis; - std::transform(val.apis.begin(), - val.apis.end(), - std::back_inserter(apis), - [](const auto &api) { - jArray api_data; - api_data.emplace_back(hex_lower_0x(api.first)); - api_data.emplace_back(makeValue(api.second)); - return api_data; - }); + std::ranges::transform( + val.apis, std::back_inserter(apis), [](const auto &api) { + jArray api_data; + api_data.emplace_back(hex_lower_0x(api.first)); + api_data.emplace_back(makeValue(api.second)); + return api_data; + }); data["apis"] = std::move(apis); return data; @@ -313,11 +311,10 @@ namespace kagome::api { -> jsonrpc::Value { jArray peers; peers.resize(params.peers.size()); - std::transform( - params.peers.begin(), - params.peers.end(), - peers.begin(), - [](const auto &peer_id) { return makeValue(peer_id.toHex()); }); + std::ranges::transform( + params.peers, peers.begin(), [](const auto &peer_id) { + return makeValue(peer_id.toHex()); + }); return jStruct{std::pair{"broadcast", std::move(peers)}}; }, [](const primitives::events::InBlockEventParams ¶ms) { diff --git a/core/api/service/author/impl/author_api_impl.cpp b/core/api/service/author/impl/author_api_impl.cpp index b2d36988bf..89b7eba517 100644 --- a/core/api/service/author/impl/author_api_impl.cpp +++ b/core/api/service/author/impl/author_api_impl.cpp @@ -43,8 +43,8 @@ namespace kagome::api { store_{std::move(store)}, keys_{std::move(keys)}, key_store_{std::move(key_store)}, - api_service_{std::move(api_service)}, - block_tree_{std::move(block_tree)}, + api_service_{api_service}, + block_tree_{block_tree}, logger_{log::createLogger("AuthorApi", "author_api")} { BOOST_ASSERT_MSG(keys_api_ != nullptr, "session keys api is nullptr"); BOOST_ASSERT_MSG(pool_ != nullptr, "transaction pool is nullptr"); @@ -63,8 +63,7 @@ namespace kagome::api { outcome::result AuthorApiImpl::insertKey(crypto::KeyType key_type_id, crypto::SecureBuffer<> seed, const BufferView &public_key) { - if (std::find(kKeyTypes.begin(), kKeyTypes.end(), key_type_id) - == kKeyTypes.end()) { + if (std::ranges::find(kKeyTypes, key_type_id) == kKeyTypes.end()) { std::string types; for (auto &type : kKeyTypes) { types.append(type.toString()); @@ -112,8 +111,6 @@ namespace kagome::api { // it could be extended by reading config from chainspec palletSession/keys // value outcome::result AuthorApiImpl::hasSessionKeys(const BufferView &keys) { - scale::ScaleDecoderStream stream(keys); - std::array key; if (keys.size() < 32 || keys.size() > 32 * 6 || (keys.size() % 32) != 0) { SL_WARN(logger_, "not valid key sequence, author_hasSessionKeys RPC call expects " @@ -121,16 +118,19 @@ namespace kagome::api { "be 32 byte in size"); return false; } + scale::ScaleDecoderStream stream(keys); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init,hicpp-member-init) + std::array key; stream >> key; if (store_->ed25519().findKeypair( crypto::KeyTypes::GRANDPA, crypto::Ed25519PublicKey(common::Blob<32>(key)))) { - unsigned count = 1; + auto it = crypto::polkadot_key_order.begin(); while (stream.currentIndex() < keys.size()) { + ++it; stream >> key; if (not store_->sr25519().findKeypair( - crypto::polkadot_key_order[count++], - crypto::Sr25519PublicKey(common::Blob<32>(key)))) { + *it, crypto::Sr25519PublicKey(common::Blob<32>(key)))) { return false; } } diff --git a/core/api/service/beefy/rpc.cpp b/core/api/service/beefy/rpc.cpp index 0951a370cc..740578487b 100644 --- a/core/api/service/beefy/rpc.cpp +++ b/core/api/service/beefy/rpc.cpp @@ -17,8 +17,8 @@ namespace kagome::api { LazySPtr beefy, LazySPtr block_header_repository) : server_{std::move(server)}, - beefy_{std::move(beefy)}, - block_header_repository_{std::move(block_header_repository)} {} + beefy_{beefy}, + block_header_repository_{block_header_repository} {} void BeefyRpc::registerHandlers() { server_->registerHandler( diff --git a/core/api/service/chain/impl/chain_api_impl.cpp b/core/api/service/chain/impl/chain_api_impl.cpp index 8c3aa99531..4f20b83b9c 100644 --- a/core/api/service/chain/impl/chain_api_impl.cpp +++ b/core/api/service/chain/impl/chain_api_impl.cpp @@ -34,7 +34,7 @@ namespace kagome::api { LazySPtr api_service) : header_repo_{std::move(block_repo)}, block_tree_{std::move(block_tree)}, - api_service_{std::move(api_service)}, + api_service_{api_service}, block_storage_{std::move(block_storage)} { BOOST_ASSERT_MSG(header_repo_ != nullptr, "block repo parameter is nullptr"); diff --git a/core/api/service/chain/requests/get_block_hash.cpp b/core/api/service/chain/requests/get_block_hash.cpp index 92b6169160..dea3099b39 100644 --- a/core/api/service/chain/requests/get_block_hash.cpp +++ b/core/api/service/chain/requests/get_block_hash.cpp @@ -39,9 +39,9 @@ namespace kagome::api::chain::request { param.reserve(array.size()); for (const auto &v : array) { if (v.IsInteger32()) { - param.emplace_back(VectorParam(v.AsInteger32())); + param.emplace_back(v.AsInteger32()); } else if (v.IsString()) { - param.emplace_back(VectorParam(v.AsString())); + param.emplace_back(v.AsString()); } else { throw jsonrpc::InvalidParametersFault("invalid argument"); } diff --git a/core/api/service/child_state/impl/child_state_api_impl.cpp b/core/api/service/child_state/impl/child_state_api_impl.cpp index 04d3fe0a52..1777fc68c6 100644 --- a/core/api/service/child_state/impl/child_state_api_impl.cpp +++ b/core/api/service/child_state/impl/child_state_api_impl.cpp @@ -132,7 +132,7 @@ namespace kagome::api { auto res = child_storage_trie_reader->tryGet(key); return common::map_result_optional( std::move(res), - [](common::BufferOrView &&r) { return r.intoBuffer(); }); + [](common::BufferOrView &&r) { return std::move(r).intoBuffer(); }); } outcome::result> diff --git a/core/api/service/impl/api_service_impl.cpp b/core/api/service/impl/api_service_impl.cpp index 257ff1ec81..690a2efbbc 100644 --- a/core/api/service/impl/api_service_impl.cpp +++ b/core/api/service/impl/api_service_impl.cpp @@ -39,7 +39,9 @@ namespace { std::optional fetchSessionId() { return bound_session_id_; } - } threaded_info; + } + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) + threaded_info; template auto withThisSession(Func &&f) { @@ -53,7 +55,9 @@ namespace { } // namespace namespace { - using namespace kagome::api; + using kagome::api::JRpcServer; + using kagome::api::makeValue; + using kagome::api::Session; /** * Method to format json-data event into json-string representation. @@ -67,7 +71,7 @@ namespace { */ template inline void forJsonData(std::shared_ptr server, - kagome::log::Logger logger, + const kagome::log::Logger &logger, uint32_t set_id, std::string_view name, jsonrpc::Value &&value, @@ -81,7 +85,7 @@ namespace { response["subscription"] = makeValue(set_id); jsonrpc::Request::Parameters params; - params.push_back(std::move(response)); + params.emplace_back(std::move(response)); server->processJsonData(name.data(), params, [&](const auto &response) { if (response.has_value()) { @@ -93,7 +97,7 @@ namespace { } inline void sendEvent(std::shared_ptr server, std::shared_ptr session, - kagome::log::Logger logger, + const kagome::log::Logger &logger, uint32_t set_id, std::string_view name, jsonrpc::Value &&value) { @@ -114,6 +118,8 @@ namespace { } // namespace namespace kagome::api { + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) KAGOME_DEFINE_CACHE(api_service); const std::string kRpcEventRuntimeVersion = "state_runtimeVersion"; @@ -127,6 +133,7 @@ namespace kagome::api { application::AppStateManager &app_state_manager, std::vector> listeners, std::shared_ptr server, + // NOLINTNEXTLINE(performance-unnecessary-value-param) std::vector> processors, StorageSubscriptionEnginePtr storage_sub_engine, ChainSubscriptionEnginePtr chain_sub_engine, @@ -151,10 +158,8 @@ namespace kagome::api { BOOST_ASSERT(block_tree_); BOOST_ASSERT(trie_storage_); BOOST_ASSERT(core_); - BOOST_ASSERT( - std::all_of(listeners_.cbegin(), listeners_.cend(), [](auto &listener) { - return listener != nullptr; - })); + BOOST_ASSERT(std::ranges::all_of( + listeners_, [](auto &listener) { return listener != nullptr; })); BOOST_ASSERT(server_); for (auto &processor : processors) { BOOST_ASSERT(processor != nullptr); @@ -182,10 +187,10 @@ namespace kagome::api { jsonrpc::Value::Array changes; changes.reserve(key_value_pairs.size()); for (auto &[key, value] : key_value_pairs) { - changes.emplace_back(jsonrpc::Value{jsonrpc::Value::Array{ + changes.emplace_back(jsonrpc::Value::Array{ api::makeValue(key), value.has_value() ? api::makeValue(hex_lower_0x(value.value())) - : api::makeValue(std::nullopt)}}); + : api::makeValue(std::nullopt)}); } jsonrpc::Value::Struct result; diff --git a/core/api/service/mmr/rpc.cpp b/core/api/service/mmr/rpc.cpp index 88a3319f1a..b7a6d18afe 100644 --- a/core/api/service/mmr/rpc.cpp +++ b/core/api/service/mmr/rpc.cpp @@ -56,11 +56,11 @@ namespace kagome::api { LazySPtr offchain_worker_factory, LazySPtr offchain_worker_pool) : server_{std::move(server)}, - mmr_api_{std::move(mmr_api)}, - block_tree_{std::move(block_tree)}, - executor_{std::move(executor)}, - offchain_worker_factory_{std::move(offchain_worker_factory)}, - offchain_worker_pool_{std::move(offchain_worker_pool)} {} + mmr_api_{mmr_api}, + block_tree_{block_tree}, + executor_{executor}, + offchain_worker_factory_{offchain_worker_factory}, + offchain_worker_pool_{offchain_worker_pool} {} auto MmrRpc::withOffchain(const primitives::BlockHash &at) { // TODO(turuslan): simplify offchain @@ -98,14 +98,15 @@ namespace kagome::api { at = self->block_tree_.get()->bestBlock().hash; } auto offchain = self->withOffchain(*at); - OUTCOME_TRY(r, - self->mmr_api_.get()->generateProof( - *at, block_numbers, best_known_block_number)); + OUTCOME_TRY( + r, + self->mmr_api_.get()->generateProof( + *at, std::move(block_numbers), best_known_block_number)); auto [leaves, proof] = unwrap(std::move(r)); return primitives::MmrLeavesProof{ - *at, - common::Buffer{scale::encode(leaves).value()}, - common::Buffer{scale::encode(proof).value()}, + .block_hash = *at, + .leaves = common::Buffer{scale::encode(leaves).value()}, + .proof = common::Buffer{scale::encode(proof).value()}, }; })); diff --git a/core/api/service/state/impl/state_api_impl.cpp b/core/api/service/state/impl/state_api_impl.cpp index c095e7d213..1999ae4d19 100644 --- a/core/api/service/state/impl/state_api_impl.cpp +++ b/core/api/service/state/impl/state_api_impl.cpp @@ -50,7 +50,7 @@ namespace kagome::api { storage_{std::move(trie_storage)}, block_tree_{std::move(block_tree)}, runtime_core_{std::move(runtime_core)}, - api_service_{std::move(api_service)}, + api_service_{api_service}, metadata_{std::move(metadata)}, executor_{std::move(executor)} { BOOST_ASSERT(nullptr != header_repo_); @@ -126,7 +126,7 @@ namespace kagome::api { auto res = trie_reader->tryGet(key); return common::map_result_optional( std::move(res), - [](common::BufferOrView &&r) { return r.intoBuffer(); }); + [](common::BufferOrView &&r) { return std::move(r).intoBuffer(); }); } outcome::result> StateApiImpl::getStorageSize( @@ -171,15 +171,16 @@ namespace kagome::api { for (auto &block : range) { OUTCOME_TRY(header, header_repo_->getBlockHeader(block)); OUTCOME_TRY(batch, storage_->getEphemeralBatchAt(header.state_root)); - StorageChangeSet change{block, {}}; + StorageChangeSet change{.block = block}; for (auto &key : keys) { OUTCOME_TRY(opt_get, batch->tryGet(key)); auto opt_value = common::map_optional( std::move(opt_get), - [](common::BufferOrView &&r) { return r.intoBuffer(); }); + [](common::BufferOrView &&r) { return std::move(r).intoBuffer(); }); auto it = last_values.find(key); if (it == last_values.end() || it->second != opt_value) { - change.changes.push_back(StorageChangeSet::Change{key, opt_value}); + change.changes.push_back( + StorageChangeSet::Change{.key = key, .data = opt_value}); } last_values[key] = std::move(opt_value); } @@ -211,7 +212,7 @@ namespace kagome::api { for (auto &key : keys) { OUTCOME_TRY(trie->tryGet(key)); } - return ReadProof{at, db.vec()}; + return ReadProof{.at = at, .proof = db.vec()}; } outcome::result StateApiImpl::getRuntimeVersion( diff --git a/core/api/transport/impl/ws/ws_session.cpp b/core/api/transport/impl/ws/ws_session.cpp index 5ea538a840..e1d4b12a94 100644 --- a/core/api/transport/impl/ws/ws_session.cpp +++ b/core/api/transport/impl/ws/ws_session.cpp @@ -26,7 +26,8 @@ namespace boost::beast { buffered_read_stream &s, TeardownHandler &&handler) { using boost::beast::websocket::async_teardown; - async_teardown(role, s.next_layer(), std::move(handler)); + async_teardown( + role, s.next_layer(), std::forward(handler)); } } // namespace boost::beast @@ -147,14 +148,14 @@ namespace kagome::api { } auto &req = self->http_request_->get(); auto &res = self->http_response_.emplace( - boost::beast::http::status::ok, req.version(), std::move(response)); + boost::beast::http::status::ok, req.version(), response); res.set(boost::beast::http::field::server, kServerName); res.set(boost::beast::http::field::content_type, "application/json"); res.keep_alive(req.keep_alive()); self->httpWrite(); return; } - self->pending_responses_.emplace(std::move(response)); + self->pending_responses_.emplace(response); self->asyncWrite(); }); } diff --git a/core/application/app_configuration.hpp b/core/application/app_configuration.hpp index 0d3946d4d7..24d0252109 100644 --- a/core/application/app_configuration.hpp +++ b/core/application/app_configuration.hpp @@ -24,7 +24,9 @@ namespace kagome::application { - enum class Subcommand { ChainInfo }; + enum class Subcommand : uint8_t { + ChainInfo, + }; struct BlockBenchmarkConfig { primitives::BlockNumber from; @@ -219,7 +221,7 @@ namespace kagome::application { */ virtual SyncMethod syncMethod() const = 0; - enum class RuntimeExecutionMethod { + enum class RuntimeExecutionMethod : uint8_t { Compile, Interpret, }; @@ -229,7 +231,7 @@ namespace kagome::application { */ virtual RuntimeExecutionMethod runtimeExecMethod() const = 0; - enum class RuntimeInterpreter { + enum class RuntimeInterpreter : uint8_t { WasmEdge, Binaryen, }; @@ -271,7 +273,11 @@ namespace kagome::application { */ virtual bool disableSecureMode() const = 0; - enum class OffchainWorkerMode { WhenValidating, Always, Never }; + enum class OffchainWorkerMode : uint8_t { + WhenValidating, + Always, + Never, + }; /** * @return enum constant of the mode of run offchain workers */ @@ -283,7 +289,9 @@ namespace kagome::application { virtual std::optional recoverState() const = 0; - enum class StorageBackend { RocksDB }; + enum class StorageBackend : uint8_t { + RocksDB, + }; /** * @return enum constant of the chosen storage backend diff --git a/core/application/app_state_manager.hpp b/core/application/app_state_manager.hpp index 172ad2eea7..1a21efa082 100644 --- a/core/application/app_state_manager.hpp +++ b/core/application/app_state_manager.hpp @@ -6,6 +6,7 @@ #pragma once +#include #include #include #include @@ -58,7 +59,7 @@ namespace kagome::application { using OnLaunch = Action; using OnShutdown = Action; - enum class State { + enum class State : uint8_t { Init, Prepare, ReadyToStart, diff --git a/core/application/impl/app_configuration_impl.cpp b/core/application/impl/app_configuration_impl.cpp index aedd21f2d2..70dc193657 100644 --- a/core/application/impl/app_configuration_impl.cpp +++ b/core/application/impl/app_configuration_impl.cpp @@ -6,7 +6,6 @@ #include "application/impl/app_configuration_impl.hpp" -#include #include #include #include @@ -18,8 +17,10 @@ #include #include #include +#include #include #include +#include #include #include "api/transport/tuner.hpp" @@ -31,6 +32,7 @@ #include "common/uri.hpp" #include "filesystem/common.hpp" #include "log/formatters/filepath.hpp" +#include "runtime/wasm_compiler_definitions.hpp" // this header-file is generated #include "utils/mkdirs.hpp" #include "utils/read_file.hpp" #include "utils/write_file.hpp" @@ -82,6 +84,7 @@ namespace { const bool def_dev_mode = false; const kagome::network::Roles def_roles = [] { kagome::network::Roles roles; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) roles.flags.full = 1; return roles; }(); @@ -164,12 +167,14 @@ namespace { return std::nullopt; } - std::array execution_methods{"Interpreted", "Compiled"}; + static constexpr std::array execution_methods{ + "Interpreted", "Compiled"}; - std::string execution_methods_str = + static const std::string execution_methods_str = fmt::format("[{}]", fmt::join(execution_methods, ", ")); - std::array + static constexpr std::array interpreters { #if KAGOME_WASM_COMPILER_WASM_EDGE == 1 "WasmEdge", @@ -177,7 +182,7 @@ namespace { "Binaryen" }; - std::string interpreters_str = + static const std::string interpreters_str = fmt::format("[{}]", fmt::join(interpreters, ", ")); std::optional @@ -323,8 +328,7 @@ namespace kagome::application { AppConfigurationImpl::FilePtr AppConfigurationImpl::open_file( const std::string &filepath) { assert(!filepath.empty()); - return AppConfigurationImpl::FilePtr(std::fopen(filepath.c_str(), "r"), - &std::fclose); + return {std::fopen(filepath.c_str(), "r"), &std::fclose}; } bool AppConfigurationImpl::load_ms(const rapidjson::Value &val, @@ -398,7 +402,7 @@ namespace kagome::application { bool AppConfigurationImpl::load_u16(const rapidjson::Value &val, const char *name, uint16_t &target) { - uint32_t i; + uint32_t i; // NOLINT(cppcoreguidelines-init-variables) if (load_u32(val, name, i) && (i & ~std::numeric_limits::max()) == 0) { target = static_cast(i); @@ -437,7 +441,9 @@ namespace kagome::application { bool validator_mode = false; load_bool(val, "validator", validator_mode); if (validator_mode) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) roles_.flags.full = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) roles_.flags.authority = 1; } @@ -778,14 +784,18 @@ namespace kagome::application { bool AppConfigurationImpl::initializeFromArgs(int argc, const char **argv) { namespace po = boost::program_options; + libp2p::common::FinalAction flush([] { std::cout.flush(); }); + std::optional command; std::optional subcommand; using std::string_view_literals::operator""sv; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) if (argc > 0 && argv[0] == "benchmark"sv) { command = "benchmark"; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) if (argc > 1 && argv[1] == "block"sv) { subcommand = "block"; } else { @@ -796,7 +806,7 @@ namespace kagome::application { } if (subcommand) { argc--; - argv++; + argv++; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) } // clang-format off @@ -863,7 +873,7 @@ namespace kagome::application { ("node-wss-pem", po::value(), "Path to pem file with SSL certificate for libp2p wss") ("rpc-cors", po::value(), "(unused, zombienet stub)") ("unsafe-rpc-external", po::bool_switch(), "alias for \"--rpc-host 0.0.0.0\"") - ("rpc-methods", po::value(), "\"auto\" (default), \"unsafe\", \"safe\"") + ("rpc-methods", po::value(), R"("auto" (default), "unsafe", "safe")") ("no-mdns", po::bool_switch(), "(unused, zombienet stub)") ("prometheus-external", po::bool_switch(), "alias for \"--prometheus-host 0.0.0.0\"") ; @@ -886,7 +896,7 @@ namespace kagome::application { ("parachain-precompilation-thread-num", po::value()->default_value(parachain_precompilation_thread_num_), "Number of threads that precompile parachain runtime modules at node startup") - ("parachain-single-process", po::bool_switch(), + ("parachain-single-process", po::bool_switch(), "Disables spawn of child pvf check processes, thus they could not be aborted by deadline timer") ("parachain-check-deadline", po::value()->default_value(2000), "Pvf check subprocess execution deadline in milliseconds") @@ -941,11 +951,11 @@ namespace kagome::application { if (vm.count("help") > 0) { std::cout << "Available subcommands: storage-explorer db-editor benchmark\n"; - std::cout << desc << std::endl; + std::cout << desc << '\n'; return false; } if (vm.count("version") > 0) { - std::cout << "Kagome version " << buildVersion() << std::endl; + std::cout << "Kagome version " << buildVersion() << '\n'; return false; } @@ -957,8 +967,7 @@ namespace kagome::application { po::notify(vm); } catch (const std::exception &e) { std::cerr << "Error: " << e.what() << '\n' - << "Try run with option '--help' for more information" - << std::endl; + << "Try run with option '--help' for more information" << '\n'; return false; } @@ -975,7 +984,7 @@ namespace kagome::application { std::cerr << "Warning: developers mode is not available. " "Application was built without developers embeddings " "(EMBEDDINGS option is OFF)." - << std::endl; + << '\n'; return false; } else { dev_mode_ = true; @@ -1000,14 +1009,14 @@ namespace kagome::application { if (not chain_spec.has_value()) { std::cerr << "Warning: developers mode chain spec is corrupted." - << std::endl; + << '\n'; return false; } if (chain_spec.value()->bootNodes().empty()) { std::cerr << "Warning: developers mode chain spec bootnodes is empty." - << std::endl; + << '\n'; return false; } @@ -1021,7 +1030,9 @@ namespace kagome::application { } } + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) roles_.flags.full = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) roles_.flags.authority = 1; p2p_port_ = def_p2p_port; rpc_host_ = def_rpc_host; @@ -1043,7 +1054,9 @@ namespace kagome::application { node_name_ = name; dev_mnemonic_phrase_ = dev; // if dev account is passed node is considered as validator + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) roles_.flags.full = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) roles_.flags.authority = 1; } } @@ -1065,14 +1078,16 @@ namespace kagome::application { find_argument(vm, "config-file", [&](const std::string &path) { if (dev_mode_) { std::cerr << "Warning: config file has ignored because dev mode" - << std::endl; + << '\n'; } else { read_config_from_file(path); } }); if (vm.end() != vm.find("validator")) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) roles_.flags.full = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) roles_.flags.authority = 1; } @@ -1080,7 +1095,7 @@ namespace kagome::application { vm, "chain", [&](const std::string &val) { chain_spec_path_ = val; }); if (not chainspecExists(chain_spec_path_)) { std::cerr << "Specified chain spec " << chain_spec_path_ - << " does not exist." << std::endl; + << " does not exist." << '\n'; } if (vm.end() != vm.find("tmp")) { @@ -1126,14 +1141,14 @@ namespace kagome::application { auto err_msg = fmt::format( "Bootnode '{}' is invalid: {}", addr_str, ma_res.error()); SL_ERROR(logger_, "{}", err_msg); - std::cout << err_msg << std::endl; + std::cout << err_msg << '\n'; return false; } auto peer_id_base58_opt = ma_res.value().getPeerId(); if (not peer_id_base58_opt) { auto err_msg = "Bootnode '" + addr_str + "' has not peer_id"; SL_ERROR(logger_, "{}", err_msg); - std::cout << err_msg << std::endl; + std::cout << err_msg << '\n'; return false; } boot_nodes_.emplace_back(std::move(ma_res.value())); @@ -1150,7 +1165,7 @@ namespace kagome::application { auto err_msg = fmt::format( "Node key '{}' is invalid: {}", node_key.value(), key_res.error()); SL_ERROR(logger_, "{}", err_msg); - std::cout << err_msg << std::endl; + std::cout << err_msg << '\n'; return false; } node_key_.emplace(std::move(key_res.value())); @@ -1625,7 +1640,7 @@ namespace kagome::application { // if something wrong with config print help message if (not validate_config()) { - std::cout << desc << std::endl; + std::cout << desc << '\n'; return false; } return true; diff --git a/core/application/impl/app_configuration_impl.hpp b/core/application/impl/app_configuration_impl.hpp index 6b6cd9e72b..fa66748fbb 100644 --- a/core/application/impl/app_configuration_impl.hpp +++ b/core/application/impl/app_configuration_impl.hpp @@ -342,7 +342,7 @@ namespace kagome::application { std::vector telemetry_endpoints_; bool is_telemetry_enabled_; uint16_t p2p_port_; - bool p2p_port_explicitly_defined_ = false; + bool p2p_port_explicitly_defined_; boost::asio::ip::tcp::endpoint rpc_endpoint_; boost::asio::ip::tcp::endpoint openmetrics_http_endpoint_; std::vector logger_tuning_config_; diff --git a/core/application/impl/app_state_manager_impl.cpp b/core/application/impl/app_state_manager_impl.cpp index 4aba6137f2..36dfd4ffd2 100644 --- a/core/application/impl/app_state_manager_impl.cpp +++ b/core/application/impl/app_state_manager_impl.cpp @@ -13,6 +13,7 @@ namespace kagome::application { std::atomic_bool AppStateManagerImpl::signals_enabled{false}; void AppStateManagerImpl::signalsEnable() { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init,hicpp-member-init) struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = shuttingDownSignalsHandler; @@ -33,6 +34,7 @@ namespace kagome::application { if (not signals_enabled.compare_exchange_strong(expected, false)) { return; } + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init,hicpp-member-init) struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = SIG_DFL; diff --git a/core/application/impl/chain_spec_impl.cpp b/core/application/impl/chain_spec_impl.cpp index 643ebd253a..7b9fe52609 100644 --- a/core/application/impl/chain_spec_impl.cpp +++ b/core/application/impl/chain_spec_impl.cpp @@ -185,21 +185,20 @@ namespace kagome::application { outcome::result ChainSpecImpl::parseBlockId( const std::string_view block_id_str) const { - primitives::BlockId block_id; if (block_id_str.rfind("0x", 0) != std::string::npos) { // Is it hash? OUTCOME_TRY(block_hash, common::Hash256::fromHexWithPrefix(block_id_str)); - block_id = block_hash; - } else { - primitives::BlockNumber block_num; - auto res = std::from_chars(block_id_str.data(), - block_id_str.data() + block_id_str.size(), - block_num); - if (res.ec != std::errc()) { - return Error::PARSER_ERROR; - } - block_id = block_num; + return primitives::BlockId{block_hash}; + } + + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + primitives::BlockNumber block_num; + auto res = std::from_chars(block_id_str.data(), + block_id_str.data() + block_id_str.size(), + block_num); + if (res.ec != std::errc()) { + return Error::PARSER_ERROR; } - return block_id; + return primitives::BlockId{block_num}; } outcome::result ChainSpecImpl::fetchCodeSubstituteByBlockInfo( diff --git a/core/application/impl/kagome_application_impl.cpp b/core/application/impl/kagome_application_impl.cpp index f8837a4852..397e53f5e7 100644 --- a/core/application/impl/kagome_application_impl.cpp +++ b/core/application/impl/kagome_application_impl.cpp @@ -108,6 +108,7 @@ namespace kagome::application { "The roles the node is running as"); auto metric_node_roles = metrics_registry->registerGaugeMetric(nodeRolesMetricName); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) metric_node_roles->set(app_config_->roles().value); constexpr auto buildInfoMetricName = "kagome_build_info"; @@ -122,7 +123,9 @@ namespace kagome::application { } #ifdef __linux__ - if (!app_config_->disableSecureMode() && app_config_->usePvfSubprocess() + if (!app_config_->disableSecureMode() + && app_config_->usePvfSubprocess() + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) && app_config_->roles().flags.authority) { auto res = parachain::runSecureModeCheckProcess( *injector_.injectIoContext(), app_config_->runtimeCacheDirPath()); diff --git a/core/application/modes/print_chain_info_mode.cpp b/core/application/modes/print_chain_info_mode.cpp index bcd00301d4..bdc6307ed5 100644 --- a/core/application/modes/print_chain_info_mode.cpp +++ b/core/application/modes/print_chain_info_mode.cpp @@ -8,7 +8,7 @@ #define RAPIDJSON_NO_SIZETYPEDEFINE namespace rapidjson { - typedef ::std::size_t SizeType; + using SizeType = size_t; } #include #include @@ -43,7 +43,8 @@ namespace kagome::application::mode { rapidjson::OStreamWrapper stream = std::cout; rapidjson::Writer writer(stream); document.Accept(writer); - std::cout << std::endl; + std::cout << '\n'; + std::cout.flush(); return EXIT_SUCCESS; } diff --git a/core/application/sync_method.hpp b/core/application/sync_method.hpp index db2eaa87c1..2d173a8b7f 100644 --- a/core/application/sync_method.hpp +++ b/core/application/sync_method.hpp @@ -6,9 +6,11 @@ #pragma once +#include + namespace kagome::application { - enum class SyncMethod { + enum class SyncMethod : uint8_t { /// Full sync. /// Download blocks fully and execute all of them Full, diff --git a/core/authority_discovery/protobuf/CMakeLists.txt b/core/authority_discovery/protobuf/CMakeLists.txt index f71197707f..4ecc931a1e 100644 --- a/core/authority_discovery/protobuf/CMakeLists.txt +++ b/core/authority_discovery/protobuf/CMakeLists.txt @@ -5,11 +5,5 @@ # add_proto_library(authority_discovery_proto - authority_discovery.v2.proto - ) -target_include_directories(authority_discovery_proto PUBLIC - # required for common targets - $ - # required for compiling proto targets - $ - ) + authority_discovery.v2.proto + ) diff --git a/core/authority_discovery/publisher/address_publisher.cpp b/core/authority_discovery/publisher/address_publisher.cpp index f656a49909..964d588f58 100644 --- a/core/authority_discovery/publisher/address_publisher.cpp +++ b/core/authority_discovery/publisher/address_publisher.cpp @@ -82,6 +82,7 @@ namespace kagome::authority_discovery { if (not libp2p_key_) { return true; } + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) if (not roles_.flags.authority) { return true; } diff --git a/core/authority_discovery/query/query_impl.cpp b/core/authority_discovery/query/query_impl.cpp index ad49eddef5..edbf9d6aba 100644 --- a/core/authority_discovery/query/query_impl.cpp +++ b/core/authority_discovery/query/query_impl.cpp @@ -52,7 +52,7 @@ namespace kagome::authority_discovery { libp2p_crypto_provider_{std::move(libp2p_crypto_provider)}, key_marshaller_{std::move(key_marshaller)}, host_{host}, - kademlia_{std::move(kademlia)}, + kademlia_{kademlia}, scheduler_{[&] { BOOST_ASSERT(scheduler != nullptr); return std::move(scheduler); @@ -124,7 +124,7 @@ namespace kagome::authority_discovery { } auto it = auth_to_peer_cache_.find(*id); if (it != auth_to_peer_cache_.end()) { - auto it_value = std::find(values.begin(), values.end(), it->second.raw); + auto it_value = std::ranges::find(values, it->second.raw); if (it_value != values.end()) { return it_value - values.begin(); } @@ -147,7 +147,7 @@ namespace kagome::authority_discovery { crypto::KeyTypes::AUTHORITY_DISCOVERY)); auto has = [](const std::vector &keys, const primitives::AuthorityDiscoveryId &key) { - return std::find(keys.begin(), keys.end(), key) != keys.end(); + return std::ranges::find(keys, key) != keys.end(); }; retain_if(authorities, [&](const primitives::AuthorityDiscoveryId &id) { return not has(local_keys, id); @@ -194,14 +194,16 @@ namespace kagome::authority_discovery { auto authority = queue_.back(); queue_.pop_back(); - common::Buffer hash{crypto::sha256(authority)}; - scheduler_->schedule([=, this, wp{weak_from_this()}] { + scheduler_->schedule([wp{weak_from_this()}, + hash = common::Buffer{crypto::sha256(authority)}] { if (auto self = wp.lock()) { - std::ignore = kademlia_.get()->getValue( - hash, [=, this](outcome::result> res) { - std::unique_lock lock{mutex_}; - --active_; - pop(); + std::ignore = self->kademlia_.get()->getValue( + hash, [=](const outcome::result> &res) { + if (auto self = wp.lock()) { + std::unique_lock lock{self->mutex_}; + --self->active_; + self->pop(); + } }); } }); @@ -218,8 +220,10 @@ namespace kagome::authority_discovery { return outcome::success(); } ::authority_discovery_v3::SignedAuthorityRecord signed_record; - if (not signed_record.ParseFromArray(signed_record_pb.data(), - signed_record_pb.size())) { + if (not signed_record.ParseFromArray( + signed_record_pb.data(), + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) + signed_record_pb.size())) { return Error::DECODE_ERROR; } @@ -252,7 +256,7 @@ namespace kagome::authority_discovery { return outcome::success(); } } - libp2p::peer::PeerInfo peer{std::move(peer_id), {}}; + libp2p::peer::PeerInfo peer{.id = std::move(peer_id)}; auto peer_id_str = peer.id.toBase58(); for (auto &pb : record.addresses()) { OUTCOME_TRY(address, libp2p::multi::Multiaddress::create(str2byte(pb))); @@ -286,9 +290,12 @@ namespace kagome::authority_discovery { peer.id, peer.addresses, libp2p::peer::ttl::kDay); peer_to_auth_cache_.insert_or_assign(peer.id, authority); - auth_to_peer_cache_.insert_or_assign( - authority, - Authority{std::move(signed_record_pb), time, std::move(peer)}); + auth_to_peer_cache_.insert_or_assign(authority, + Authority{ + .raw = std::move(signed_record_pb), + .time = time, + .peer = std::move(peer), + }); return outcome::success(); } diff --git a/core/authorship/impl/block_builder_factory_impl.cpp b/core/authorship/impl/block_builder_factory_impl.cpp index b9148ca7d0..a39a0f748f 100644 --- a/core/authorship/impl/block_builder_factory_impl.cpp +++ b/core/authorship/impl/block_builder_factory_impl.cpp @@ -42,17 +42,15 @@ namespace kagome::authorship { }; // Try to initialize the block with the created header and changes tracker - if (auto res = - r_core_->initialize_block(header, std::move(changes_tracker)); - not res) { + auto res = r_core_->initialize_block(header, std::move(changes_tracker)); + if (res.has_error()) { logger_->error("Core_initialize_block failed: {}", res.error()); return res.error(); - } else { - auto &[ctx, mode] = res.value(); - return std::make_pair(std::make_unique( - header, std::move(ctx), r_block_builder_), - mode); } + auto &[ctx, mode] = res.value(); + return std::make_pair(std::make_unique( + header, std::move(ctx), r_block_builder_), + mode); } } // namespace kagome::authorship diff --git a/core/authorship/impl/block_builder_impl.cpp b/core/authorship/impl/block_builder_impl.cpp index 72a8fd929b..c5251811b3 100644 --- a/core/authorship/impl/block_builder_impl.cpp +++ b/core/authorship/impl/block_builder_impl.cpp @@ -100,7 +100,7 @@ namespace kagome::authorship { outcome::result BlockBuilderImpl::bake() const { OUTCOME_TRY(finalized_header, block_builder_api_->finalize_block(*ctx_)); - return primitives::Block{finalized_header, extrinsics_}; + return primitives::Block{.header = finalized_header, .body = extrinsics_}; } size_t BlockBuilderImpl::estimateBlockSize() const { diff --git a/core/benchmark/block_execution_benchmark.cpp b/core/benchmark/block_execution_benchmark.cpp index 71de414c77..30e8fd275b 100644 --- a/core/benchmark/block_execution_benchmark.cpp +++ b/core/benchmark/block_execution_benchmark.cpp @@ -107,10 +107,10 @@ namespace kagome::benchmark { std::shared_ptr module_repo, std::shared_ptr trie_storage) : logger_{log::createLogger("BlockExecutionBenchmark", "benchmark")}, - core_api_{core_api}, - block_tree_{block_tree}, - module_repo_{module_repo}, - trie_storage_{trie_storage} { + core_api_{std::move(core_api)}, + block_tree_{std::move(block_tree)}, + module_repo_{std::move(module_repo)}, + trie_storage_{std::move(trie_storage)} { BOOST_ASSERT(block_tree_ != nullptr); BOOST_ASSERT(core_api_ != nullptr); BOOST_ASSERT(module_repo_ != nullptr); @@ -223,7 +223,7 @@ namespace kagome::benchmark { using ConsumedWeight = PerDispatchClass; // Hard-coded key for System::BlockWeight. - auto BLOCK_WEIGHT_KEY = + static const auto BLOCK_WEIGHT_KEY = "26aa394eea5630e07c48ae0c9558cef734abf5cb34d6244378cddbf18e849d96"_hex2buf; constexpr uint64_t WEIGHT_REF_TIME_PER_NANOS = 1000; @@ -272,8 +272,8 @@ namespace kagome::benchmark { block_tree_->getBlockBody(current_block_info.hash), "block {}", current_block_info); - primitives::Block current_block{std::move(current_block_header), - std::move(current_block_body)}; + primitives::Block current_block{.header = std::move(current_block_header), + .body = std::move(current_block_body)}; current_block.header.digest.pop_back(); block_hashes.emplace_back(current_block_info.hash); blocks.emplace_back(std::move(current_block)); @@ -295,9 +295,10 @@ namespace kagome::benchmark { std::chrono::steady_clock clock; std::vector> duration_stats; + duration_stats.reserve(blocks.size()); for (size_t i = 0; i < blocks.size(); i++) { - duration_stats.emplace_back(Stats{ - primitives::BlockInfo{block_hashes[i], blocks[i].header.number}}); + duration_stats.emplace_back( + primitives::BlockInfo{block_hashes[i], blocks[i].header.number}); } auto duration_stat_it = duration_stats.begin(); for (size_t block_i = 0; block_i < blocks.size(); block_i++) { diff --git a/core/blockchain/block_header_repository.hpp b/core/blockchain/block_header_repository.hpp index 98bbc6abca..a18e6c73cf 100644 --- a/core/blockchain/block_header_repository.hpp +++ b/core/blockchain/block_header_repository.hpp @@ -19,7 +19,10 @@ namespace kagome::blockchain { /** * Status of a block */ - enum class BlockStatus { InChain, Unknown }; + enum class BlockStatus : uint8_t { + InChain, + Unknown, + }; /** * An interface to a storage with block headers that provides several diff --git a/core/blockchain/block_tree.hpp b/core/blockchain/block_tree.hpp index a2c3bcb954..8ff72eb36a 100644 --- a/core/blockchain/block_tree.hpp +++ b/core/blockchain/block_tree.hpp @@ -158,7 +158,10 @@ namespace kagome::blockchain { const primitives::BlockHash &block, const primitives::Justification &justification) = 0; - enum class GetChainDirection { ASCEND, DESCEND }; + enum class GetChainDirection : uint8_t { + ASCEND, + DESCEND, + }; /** * Get a chain of blocks from provided block to best block direction diff --git a/core/blockchain/block_tree_error.hpp b/core/blockchain/block_tree_error.hpp index 6033c35c6d..e018a9c53b 100644 --- a/core/blockchain/block_tree_error.hpp +++ b/core/blockchain/block_tree_error.hpp @@ -13,7 +13,7 @@ namespace kagome::blockchain { * Errors of the block tree are here, so that other modules can use them, for * example, to compare a received error with those */ - enum class BlockTreeError { + enum class BlockTreeError : uint8_t { NO_PARENT = 1, BLOCK_EXISTS, // target block number is past the given maximum number diff --git a/core/blockchain/impl/block_tree_impl.cpp b/core/blockchain/impl/block_tree_impl.cpp index 603778f2ab..aa056ba2b5 100644 --- a/core/blockchain/impl/block_tree_impl.cpp +++ b/core/blockchain/impl/block_tree_impl.cpp @@ -174,12 +174,12 @@ namespace kagome::blockchain { } // Met early observed block - if (observed.count(block.hash) != 0) { + if (observed.contains(block.hash)) { break; } // Met known dead block - if (dead.count(block) != 0) { + if (dead.contains(block)) { dead.insert(subchain.begin(), subchain.end()); break; } @@ -309,7 +309,7 @@ namespace kagome::blockchain { } outcome::result BlockTreeImpl::recover( - primitives::BlockId target_block_id, + const primitives::BlockId &target_block_id, std::shared_ptr storage, std::shared_ptr header_repo, std::shared_ptr trie_storage, @@ -331,7 +331,8 @@ namespace kagome::blockchain { "Can't get header of target block: {}", target_block_hash_opt_res.error()); return BlockTreeError::HEADER_NOT_FOUND; - } else if (not target_block_hash_opt_res.value().has_value()) { + } + if (not target_block_hash_opt_res.value().has_value()) { SL_CRITICAL(log, "Can't get header of target block: header not found"); return BlockTreeError::HEADER_NOT_FOUND; } @@ -389,10 +390,9 @@ namespace kagome::blockchain { std::vector leaves; leaves.reserve(block_tree_leaves.size()); - std::transform(block_tree_leaves.begin(), - block_tree_leaves.end(), - std::back_inserter(leaves), - [](const auto it) { return it.hash; }); + std::ranges::transform(block_tree_leaves, + std::back_inserter(leaves), + [](const auto it) { return it.hash; }); if (auto res = storage->setBlockTreeLeaves(leaves); res.has_error()) { SL_CRITICAL( log, "Can't save updated block tree leaves: {}", res.error()); @@ -437,7 +437,9 @@ namespace kagome::blockchain { .genesis_block_hash_ = {}, .blocks_pruning_ = {app_config.blocksPruning(), finalized.number}, }}, - main_pool_handler_{main_thread_pool.handlerStarted()} { + chain_events_engine_{std::move(chain_events_engine)}, + main_pool_handler_{main_thread_pool.handlerStarted()}, + extrinsic_events_engine_{std::move(extrinsic_events_engine)} { block_tree_data_.sharedAccess([&](const BlockTreeData &p) { BOOST_ASSERT(p.header_repo_ != nullptr); BOOST_ASSERT(p.storage_ != nullptr); @@ -478,10 +480,7 @@ namespace kagome::blockchain { } }); - chain_events_engine_ = std::move(chain_events_engine); BOOST_ASSERT(chain_events_engine_ != nullptr); - - extrinsic_events_engine_ = std::move(extrinsic_events_engine); BOOST_ASSERT(extrinsic_events_engine_ != nullptr); } @@ -499,7 +498,8 @@ namespace kagome::blockchain { res.has_value(), "Block tree must contain at least genesis block"); - const_cast &>( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + const_cast &>( p.genesis_block_hash_) .emplace(res.value()); return p.genesis_block_hash_.value(); @@ -587,8 +587,7 @@ namespace kagome::blockchain { main_pool_handler_->execute( [wself{weak_from_this()}, event, header]() mutable { if (auto self = wself.lock()) { - self->chain_events_engine_->notify(std::move(event), - std::move(header)); + self->chain_events_engine_->notify(event, header); } }); } @@ -603,8 +602,8 @@ namespace kagome::blockchain { OUTCOME_TRY(p.storage_->removeJustification(finalized.hash)); auto parent = *header.parentInfo(); ReorgAndPrune changes{ - Reorg{parent, {finalized}, {}}, - {finalized}, + .reorg = Reorg{.common = parent, .revert = {finalized}}, + .prune = {finalized}, }; p.tree_ = std::make_unique(parent); OUTCOME_TRY(reorgAndPrune(p, changes)); @@ -821,7 +820,7 @@ namespace kagome::blockchain { for (auto parent = node->parent(); parent; parent = parent->parent()) { retired_hashes.emplace_back( primitives::events::RemoveAfterFinalizationParams::HeaderInfo{ - parent->info.hash, parent->info.number}); + .hash = parent->info.hash, .number = parent->info.number}); } auto changes = p.tree_->finalize(node); @@ -853,7 +852,8 @@ namespace kagome::blockchain { main_pool_handler_->execute( [weak{weak_from_this()}, retired{primitives::events::RemoveAfterFinalizationParams{ - std::move(retired_hashes), header.number}}] { + .removed = std::move(retired_hashes), + .finalized = header.number}}] { if (auto self = weak.lock()) { self->chain_events_engine_->notify( primitives::events::ChainEventType:: @@ -1032,7 +1032,7 @@ namespace kagome::blockchain { if (chain.back() != block) { return std::vector{block}; } - std::reverse(chain.begin(), chain.end()); + std::ranges::reverse(chain); return chain; }); } @@ -1106,7 +1106,7 @@ namespace kagome::blockchain { if (chain.back() != ancestor) { return BlockTreeError::BLOCK_ON_DEAD_END; } - std::reverse(chain.begin(), chain.end()); + std::ranges::reverse(chain); return chain; }); } @@ -1339,7 +1339,7 @@ namespace kagome::blockchain { } retired_hashes.emplace_back( primitives::events::RemoveAfterFinalizationParams::HeaderInfo{ - block.hash, block.number}); + .hash = block.hash, .number = block.number}); OUTCOME_TRY(p.storage_->removeBlock(block.hash)); } @@ -1348,8 +1348,8 @@ namespace kagome::blockchain { [extrinsics{std::move(extrinsics)}, wself{weak_from_this()}, retired{primitives::events::RemoveAfterFinalizationParams{ - std::move(retired_hashes), - getLastFinalizedNoLock(p).number}}]() mutable { + .removed = std::move(retired_hashes), + .finalized = getLastFinalizedNoLock(p).number}}]() mutable { if (auto self = wself.lock()) { auto eo = self->block_tree_data_.sharedAccess( [&](const BlockTreeData &p) { return p.extrinsic_observer_; }); @@ -1390,7 +1390,7 @@ namespace kagome::blockchain { OUTCOME_TRY(hash_opt, getBlockHash(next_pruned_number)); BOOST_ASSERT(hash_opt.has_value()); - primitives::BlockHash hash = std::move(*hash_opt); + auto &hash = hash_opt.value(); auto pruning_depth = block_tree_data.state_pruner_->getPruningDepth().value_or(0); if (new_finalized < pruning_depth) { @@ -1404,7 +1404,7 @@ namespace kagome::blockchain { auto &next_hash = *next_hash_opt; OUTCOME_TRY(header, getBlockHeader(hash)); OUTCOME_TRY(block_tree_data.state_pruner_->pruneFinalized(header)); - hash = std::move(next_hash); + hash = next_hash; } return outcome::success(); diff --git a/core/blockchain/impl/block_tree_impl.hpp b/core/blockchain/impl/block_tree_impl.hpp index 0b160cc42b..972e46b1e5 100644 --- a/core/blockchain/impl/block_tree_impl.hpp +++ b/core/blockchain/impl/block_tree_impl.hpp @@ -75,7 +75,7 @@ namespace kagome::blockchain { /// Recover block tree state at provided block static outcome::result recover( - primitives::BlockId target_block_id, + const primitives::BlockId &target_block_id, std::shared_ptr storage, std::shared_ptr header_repo, std::shared_ptr trie_storage, diff --git a/core/blockchain/impl/cached_tree.cpp b/core/blockchain/impl/cached_tree.cpp index 4eb8bcd640..c5703b9688 100644 --- a/core/blockchain/impl/cached_tree.cpp +++ b/core/blockchain/impl/cached_tree.cpp @@ -52,7 +52,7 @@ namespace kagome::blockchain { } } reorg.common = to->info; - std::reverse(reorg.apply.begin(), reorg.apply.end()); + std::ranges::reverse(reorg.apply); return reorg; } @@ -244,7 +244,7 @@ namespace kagome::blockchain { parent->children.clear(); nodes_.erase(parent->info.hash); } - std::reverse(changes.prune.begin(), changes.prune.end()); + std::ranges::reverse(changes.prune); root_ = new_finalized; root_->weak_parent.reset(); if (changes.reorg) { @@ -255,8 +255,10 @@ namespace kagome::blockchain { changes.reorg->apply.emplace_back(node->info); }); BOOST_ASSERT(ok); - std::reverse(changes.reorg->apply.begin() + offset, - changes.reorg->apply.end()); + std::reverse( + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) + changes.reorg->apply.begin() + offset, + changes.reorg->apply.end()); } return changes; } @@ -304,7 +306,7 @@ namespace kagome::blockchain { } parent->children.clear(); } - std::reverse(changes.prune.begin(), changes.prune.end()); + std::ranges::reverse(changes.prune); *this = CachedTree{root_->info}; return changes; } diff --git a/core/common/blob.hpp b/core/common/blob.hpp index 7c53646dd6..8578c83bfe 100644 --- a/core/common/blob.hpp +++ b/core/common/blob.hpp @@ -100,7 +100,7 @@ namespace kagome::common { /** * Error codes for exceptions that may occur during blob initialization */ - enum class BlobError { INCORRECT_LENGTH = 1 }; + enum class BlobError : uint8_t { INCORRECT_LENGTH = 1 }; using byte_t = uint8_t; @@ -120,8 +120,10 @@ namespace kagome::common { // Next line is required at least for the scale-codec static constexpr bool is_static_collection = true; + // NOLINTBEGIN(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) using const_narref = const byte_t (&)[size_]; using const_narptr = const byte_t (*)[size_]; + // NOLINTEND(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) /** * Initialize blob value */ @@ -169,7 +171,7 @@ namespace kagome::common { } Blob b; - std::copy(data.begin(), data.end(), b.begin()); + std::ranges::copy(data, b.begin()); return b; } @@ -206,7 +208,7 @@ namespace kagome::common { } Blob blob; - std::copy(span.begin(), span.end(), blob.begin()); + std::ranges::copy(span, blob.begin()); return blob; } }; diff --git a/core/common/buffer.hpp b/core/common/buffer.hpp index fea96605aa..35f4937a59 100644 --- a/core/common/buffer.hpp +++ b/core/common/buffer.hpp @@ -54,7 +54,7 @@ namespace kagome::common { explicit SLBuffer(const std::array &other) : Base(other.begin(), other.end()) {} - SLBuffer(const uint8_t *begin, const uint8_t *end) : Base(begin, end){}; + SLBuffer(const uint8_t *begin, const uint8_t *end) : Base(begin, end) {}; using Base::Base; using Base::operator=; @@ -91,6 +91,7 @@ namespace kagome::common { n = htobe32(n); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) const auto *begin = reinterpret_cast(&n); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) const auto *end = begin + sizeof(n) / sizeof(uint8_t); Base::insert(this->end(), begin, end); return *this; @@ -105,6 +106,7 @@ namespace kagome::common { n = htobe64(n); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) const auto *begin = reinterpret_cast(&n); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) const auto *end = begin + sizeof(n) / sizeof(uint8_t); Base::insert(this->end(), begin, end); return *this; @@ -227,8 +229,9 @@ namespace kagome::common { /// creates a buffer filled with characters from the original string /// mind that it does not perform unhexing, there is ""_unhex for it inline Buffer operator""_buf(const char *c, size_t s) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) std::vector chars(c, c + s); - return Buffer(std::move(chars)); + return {std::move(chars)}; } inline Buffer operator""_hex2buf(const char *hex, unsigned long size) { diff --git a/core/common/buffer_or_view.hpp b/core/common/buffer_or_view.hpp index fc09220105..05085f0db7 100644 --- a/core/common/buffer_or_view.hpp +++ b/core/common/buffer_or_view.hpp @@ -24,6 +24,7 @@ namespace kagome::common { public: BufferOrView() = default; + ~BufferOrView() = default; BufferOrView(const BufferView &view) : variant{view} {} @@ -36,7 +37,7 @@ namespace kagome::common { : variant{Buffer{std::move(vector)}} {} BufferOrView(const BufferOrView &) = delete; - BufferOrView(BufferOrView &&) = default; + BufferOrView(BufferOrView &&) noexcept = default; BufferOrView &operator=(const BufferOrView &) = delete; BufferOrView &operator=(BufferOrView &&) = default; @@ -92,12 +93,17 @@ namespace kagome::common { } /// Move buffer away. Copy once if view. - Buffer intoBuffer() { + Buffer intoBuffer() & { auto buffer = std::move(mut()); variant = Moved{}; return buffer; } + /// Move buffer away. Copy once if view. + Buffer intoBuffer() && { + return std::move(mut()); + } + private: std::variant variant; diff --git a/core/common/buffer_view.hpp b/core/common/buffer_view.hpp index ac88fd08aa..04b0d0af03 100644 --- a/core/common/buffer_view.hpp +++ b/core/common/buffer_view.hpp @@ -7,15 +7,14 @@ #pragma once #include +#include #include #include "common/hexutil.hpp" #include "macro/endianness_utils.hpp" -#include -#include - inline auto operator""_bytes(const char *s, std::size_t size) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) return std::span(reinterpret_cast(s), size); } @@ -37,11 +36,13 @@ namespace kagome::common { template requires std::is_integral_v> and (sizeof(T) == 1) BufferView(std::span other) + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) : span(reinterpret_cast(other.data()), other.size()) {} template - decltype(auto) operator=(T &&t) { - return span::operator=(std::forward(t)); + BufferView &operator=(T &&value) { + span::operator=(std::forward(value)); + return *this; } template @@ -67,7 +68,7 @@ namespace kagome::common { } std::string_view toStringView() const { - // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast) + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) return {reinterpret_cast(data()), size()}; } @@ -107,7 +108,8 @@ struct fmt::formatter { // Parses format specifications of the form ['s' | 'l']. constexpr auto parse(format_parse_context &ctx) -> decltype(ctx.begin()) { // Parse the presentation format and store it in the formatter: - auto it = ctx.begin(), end = ctx.end(); + auto it = ctx.begin(); + auto end = ctx.end(); if (it != end && (*it == 's' || *it == 'l')) { presentation = *it++; } @@ -130,7 +132,7 @@ struct fmt::formatter { if (view.empty()) { static constexpr string_view message(""); - return std::copy(std::begin(message), std::end(message), ctx.out()); + return std::copy(message.begin(), message.end(), ctx.out()); } if (presentation == 's' && view.size() > 5) { diff --git a/core/common/hexutil.hpp b/core/common/hexutil.hpp index de0b95c803..02b17ced4a 100644 --- a/core/common/hexutil.hpp +++ b/core/common/hexutil.hpp @@ -19,7 +19,7 @@ namespace kagome::common { /** * @brief error codes for exceptions that may occur during unhexing */ - enum class UnhexError { + enum class UnhexError : uint8_t { NOT_ENOUGH_INPUT = 1, NON_HEX_INPUT, VALUE_OUT_OF_RANGE, @@ -100,7 +100,8 @@ namespace kagome::common { * @param value source hex string * @return unhexed value */ - template >> + template + requires std::is_unsigned_v outcome::result unhexNumber(std::string_view value) { std::vector bytes; OUTCOME_TRY(bts, common::unhexWith0x(value)); @@ -111,14 +112,14 @@ namespace kagome::common { } T result{0u}; - for (auto b : bytes) { + for (auto byte : bytes) { // check if `multiply by 10` will cause overflow if constexpr (sizeof(T) > 1) { result <<= 8u; } else { result = 0; } - result += b; + result += byte; } return result; diff --git a/core/common/int_serialization.cpp b/core/common/int_serialization.cpp index 8457a9cb8c..c71c821731 100644 --- a/core/common/int_serialization.cpp +++ b/core/common/int_serialization.cpp @@ -15,7 +15,7 @@ namespace kagome::common { inline std::array uint_to_le_bytes(uint &&i) { std::array res{}; res.fill(0); - export_bits(i, res.begin(), 8, false); + export_bits(std::forward(i), res.begin(), 8, false); return res; } @@ -23,7 +23,7 @@ namespace kagome::common { inline std::array uint_to_be_bytes(uint &&i) { std::array res{}; res.fill(0); - export_bits(i, res.rbegin(), 8, false); + export_bits(std::forward(i), res.rbegin(), 8, false); return res; } @@ -46,26 +46,28 @@ namespace kagome::common { std::array uint64_to_le_bytes(uint64_t number) { std::array result{}; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) *reinterpret_cast(result.data()) = htole64(number); return result; } uint64_t le_bytes_to_uint64(BufferView bytes) { BOOST_ASSERT(bytes.size() >= 8); - uint64_t number; + uint64_t number; // NOLINT(cppcoreguidelines-init-variables) memcpy(&number, bytes.data(), 8); return le64toh(number); } std::array uint64_to_be_bytes(uint64_t number) { std::array result{}; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) *reinterpret_cast(result.data()) = htobe64(number); return result; } uint64_t be_bytes_to_uint64(BufferView bytes) { BOOST_ASSERT(bytes.size() >= 8); - uint64_t number; + uint64_t number; // NOLINT(cppcoreguidelines-init-variables) memcpy(&number, bytes.data(), 8); return be64toh(number); } diff --git a/core/common/literals.hpp b/core/common/literals.hpp index e4c4d84094..29b968a6d9 100644 --- a/core/common/literals.hpp +++ b/core/common/literals.hpp @@ -6,30 +6,32 @@ #pragma once +#include + namespace kagome::common::literals { - constexpr size_t operator""_kB(long long unsigned int kilobytes) { - return kilobytes << 10u; + constexpr std::size_t operator""_kB(long long unsigned int kilobytes) { + return static_cast(kilobytes << 10u); } - constexpr size_t operator""_kB(long double kilobytes) { - return (1ull << 10) * kilobytes; + constexpr std::size_t operator""_kB(long double kilobytes) { + return static_cast((1ull << 10ull) * kilobytes); } - constexpr size_t operator""_MB(long long unsigned int megabytes) { - return megabytes << 20u; + constexpr std::size_t operator""_MB(long long unsigned int megabytes) { + return static_cast(megabytes << 20ull); } - constexpr size_t operator""_MB(long double megabytes) { - return (1ull << 20) * megabytes; + constexpr std::size_t operator""_MB(long double megabytes) { + return static_cast((1ull << 20ull) * megabytes); } - constexpr size_t operator""_GB(long long unsigned int gigabytes) { - return gigabytes << 30u; + constexpr std::size_t operator""_GB(long long unsigned int gigabytes) { + return static_cast(gigabytes << 30ull); } - constexpr size_t operator""_GB(long double gigabytes) { - return (1ull << 30) * gigabytes; + constexpr std::size_t operator""_GB(long double gigabytes) { + return static_cast((1ull << 30ull) * gigabytes); } } // namespace kagome::common::literals diff --git a/core/common/lru_cache.hpp b/core/common/lru_cache.hpp index 70f43bccff..00ba20f1d0 100644 --- a/core/common/lru_cache.hpp +++ b/core/common/lru_cache.hpp @@ -117,8 +117,8 @@ namespace kagome { } if constexpr (std::is_same_v) { - auto it = - std::find_if(cache_.begin(), cache_.end(), [&](const auto &item) { + auto it = std::ranges::find_if( + cache_.begin(), cache_.end(), [&](const auto &item) { return *item.value == value; }); if (it != cache_.end()) { @@ -134,8 +134,8 @@ namespace kagome { } else { auto value_sptr = std::make_shared(std::forward(value)); - auto it = - std::find_if(cache_.begin(), cache_.end(), [&](const auto &item) { + auto it = std::ranges::find_if( + cache_.begin(), cache_.end(), [&](const auto &item) { return *item.value == *value_sptr; }); if (it != cache_.end()) { @@ -153,18 +153,19 @@ namespace kagome { if (auto opt = get(key); opt.has_value()) { return opt.value(); } - if (auto res = func(); res.has_value()) { + auto res = func(); + if (res.has_value()) { return put(key, std::move(res.value())); - } else { - return res.as_failure(); } + return res.as_failure(); } void erase(const Key &key) { LockGuard lg(*this); - auto it = std::find_if(cache_.begin(), - cache_.end(), - [&](const auto &item) { return item.key == key; }); + auto it = std::ranges::find_if( + cache_.begin(), cache_.end(), [&](const auto &item) { + return item.key == key; + }); if (it != cache_.end()) { cache_.erase(it); } diff --git a/core/common/optref.hpp b/core/common/optref.hpp index e8fb2a8880..1b73d62dc9 100644 --- a/core/common/optref.hpp +++ b/core/common/optref.hpp @@ -15,14 +15,18 @@ namespace kagome { template class OptRef { public: - OptRef() : data{nullptr} {} + OptRef() = default; + OptRef(const OptRef &) = default; + OptRef(OptRef &&) noexcept = default; + OptRef(T &data) : data{&data} {} OptRef(T &&) = delete; - OptRef(std::nullopt_t) : data{nullptr} {} + OptRef(std::nullopt_t) {} - OptRef(const OptRef &) = default; + ~OptRef() = default; OptRef &operator=(const OptRef &) = default; + OptRef &operator=(OptRef &&) noexcept = default; T &operator*() { BOOST_ASSERT(data); @@ -73,6 +77,6 @@ namespace kagome { } private: - T *data; + T *data = nullptr; }; } // namespace kagome diff --git a/core/common/outcome_throw.hpp b/core/common/outcome_throw.hpp index 0c8af7c899..29ea30871f 100644 --- a/core/common/outcome_throw.hpp +++ b/core/common/outcome_throw.hpp @@ -17,7 +17,8 @@ namespace kagome::common { * @tparam T enum error type, only outcome::result enums are allowed * @param t error value */ - template >> + template + requires std::is_enum_v void raise(T t) { std::error_code ec = make_error_code(t); boost::throw_exception(std::system_error(ec)); @@ -28,7 +29,8 @@ namespace kagome::common { * @tparam T outcome error type * @param t outcome error value */ - template >> + template + requires(not std::is_enum_v) void raise(const T &t) { boost::throw_exception(std::system_error(t.value(), t.category())); } diff --git a/core/common/size_limited_containers.hpp b/core/common/size_limited_containers.hpp index ba35043415..f73d7ff29f 100644 --- a/core/common/size_limited_containers.hpp +++ b/core/common/size_limited_containers.hpp @@ -16,10 +16,18 @@ namespace kagome::common { + template + concept MutIter = std::is_same_v; + template + concept ConstIter = std::is_same_v; + template + concept Iter = MutIter or ConstIter; + class MaxSizeException : public std::length_error { public: template - MaxSizeException(const Format &format, Args &&...args) + // cppcoreguidelines-missing-std-forward + MaxSizeException(const Format &format, const Args &...args) : std::length_error( fmt::vformat(format, fmt::make_format_args(args...))) {} }; @@ -95,10 +103,10 @@ namespace kagome::common { return std::move(other); }()) {} - template ::iterator_category>>> + template + requires std::is_base_of_v< + std::input_iterator_tag, + typename std::iterator_traits::iterator_category> SizeLimitedContainer(Iter begin, Iter end) : Base([&] { if constexpr (size_check_is_enabled) { @@ -170,10 +178,10 @@ namespace kagome::common { return Base::assign(size, value); } - template ::iterator_category>>> + template + requires std::is_base_of_v< + std::input_iterator_tag, + typename std::iterator_traits::iterator_category> void assign(Iter begin, Iter end) { if constexpr (size_check_is_enabled) { const size_t size = std::distance(begin, end); @@ -212,13 +220,9 @@ namespace kagome::common { return Base::emplace_back(std::forward(args)...); } - template < - typename Iter, - typename... Args, - bool isIter = std::is_same_v, - bool isConstIter = std::is_same_v, - typename = std::enable_if_t> - typename Base::iterator emplace(Iter pos, Args &&...args) { + template + requires Iter + typename Base::iterator emplace(It pos, Args &&...args) { if constexpr (size_check_is_enabled) { [[unlikely]] if (Base::size() >= max_size()) { throw MaxSizeException( @@ -230,12 +234,9 @@ namespace kagome::common { return Base::emplace(std::move(pos), std::forward(args)...); } - template < - typename Iter, - bool isIter = std::is_same_v, - bool isConstIter = std::is_same_v, - typename = std::enable_if_t> - typename Base::iterator insert(Iter pos, + template + requires Iter + typename Base::iterator insert(It pos, const typename Base::value_type &value) { if constexpr (size_check_is_enabled) { [[unlikely]] if (Base::size() >= max_size()) { @@ -248,12 +249,9 @@ namespace kagome::common { return Base::insert(std::move(pos), value); } - template < - typename Iter, - bool isIter = std::is_same_v, - bool isConstIter = std::is_same_v, - typename = std::enable_if_t> - typename Base::iterator insert(Iter pos, + template + requires Iter + typename Base::iterator insert(It pos, typename Base::size_type size, const typename Base::value_type &value) { if constexpr (size_check_is_enabled) { @@ -268,15 +266,11 @@ namespace kagome::common { return Base::insert(std::move(pos), size, value); } - template < - typename OutIt, - typename InIt, - bool isIter = std::is_same_v, - bool isConstIter = std::is_same_v, - typename = std::enable_if_t, - typename = std::enable_if_t::iterator_category>>> + template + requires Iter + and std::is_base_of_v< + std::input_iterator_tag, + typename std::iterator_traits::iterator_category> typename Base::iterator insert(OutIt pos, InIt begin, InIt end) { if constexpr (size_check_is_enabled) { const size_t size = std::distance(begin, end); @@ -293,13 +287,10 @@ namespace kagome::common { return Base::insert(std::move(pos), std::move(begin), std::move(end)); } - template < - typename Iter, - bool isIter = std::is_same_v, - bool isConstIter = std::is_same_v, - typename = std::enable_if_t> + template + requires Iter typename Base::iterator insert( - Iter pos, std::initializer_list &&list) { + It pos, std::initializer_list &&list) { if constexpr (size_check_is_enabled) { const auto available = max_size() - Base::size(); [[unlikely]] if (available < list.size()) { diff --git a/core/common/span_adl.hpp b/core/common/span_adl.hpp index 82036e70de..5aa92f7767 100644 --- a/core/common/span_adl.hpp +++ b/core/common/span_adl.hpp @@ -7,6 +7,7 @@ #pragma once #include +#include #include #include #include @@ -32,10 +33,9 @@ auto operator<=>(const SpanAdl &l_, const auto &r_) auto n = std::min(l.size(), r.size()); auto c = std::memcmp(l.data(), r.data(), n) <=> 0; return c != 0 ? c : l.size() <=> r.size(); - } else { - return qtils::cxx20::lexicographical_compare_three_way( - l.begin(), l.end(), r.begin(), r.end()); } + return qtils::cxx20::lexicographical_compare_three_way( + l.begin(), l.end(), r.begin(), r.end()); } template diff --git a/core/common/spin_lock.hpp b/core/common/spin_lock.hpp index 5a5b6c2424..b9a14b19a8 100644 --- a/core/common/spin_lock.hpp +++ b/core/common/spin_lock.hpp @@ -34,6 +34,8 @@ namespace kagome::common { spin_lock() = default; spin_lock(const spin_lock &) = delete; spin_lock(spin_lock &&) = delete; + ~spin_lock() = default; + spin_lock &operator=(const spin_lock &) = delete; spin_lock &operator=(spin_lock &&) = delete; diff --git a/core/common/tagged.hpp b/core/common/tagged.hpp index 50bf69f88f..b0a858d860 100644 --- a/core/common/tagged.hpp +++ b/core/common/tagged.hpp @@ -34,6 +34,7 @@ namespace kagome { Tagged(T value) : Base(std::move(value)) {} + // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) Tagged &operator=(T &&value) noexcept( not std::is_lvalue_reference_v) { if constexpr (std::is_scalar_v) { @@ -46,6 +47,7 @@ namespace kagome { template explicit operator Out() const { + // NOLINTNEXTLINE(readability-else-after-return) if constexpr (std::is_scalar_v) { return this->Wrapper::value; } else { @@ -66,10 +68,11 @@ namespace kagome { friend inline ::scale::ScaleDecoderStream &operator>>( ::scale::ScaleDecoderStream &s, Tagged &tagged) { if constexpr (std::is_scalar_v) { - return s >> tagged.Wrapper::value; + s >> tagged.Wrapper::value; } else { - return s >> static_cast(tagged); + s >> static_cast(tagged); } + return s; } }; diff --git a/core/common/unused.hpp b/core/common/unused.hpp index 19b6ce1ed9..538b50409e 100644 --- a/core/common/unused.hpp +++ b/core/common/unused.hpp @@ -6,6 +6,8 @@ #pragma once +#include + #include #include "common/empty.hpp" @@ -13,7 +15,7 @@ namespace kagome { - enum UnusedError { + enum UnusedError : uint8_t { AttemptToEncodeUnused = 1, AttemptToDecodeUnused, }; diff --git a/core/common/uri.cpp b/core/common/uri.cpp index ca4476e815..26b061262f 100644 --- a/core/common/uri.cpp +++ b/core/common/uri.cpp @@ -61,7 +61,7 @@ namespace kagome::common { } result.Schema.assign(schema_begin, schema_end); - if (std::find_if_not( + if (std::ranges::find_if_not( schema_begin, schema_end, [](auto ch) { return std::isalpha(ch); }) != schema_end) { if (not result.error_.has_value()) { @@ -71,12 +71,14 @@ namespace kagome::common { // Host const auto host_begin = + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) schema_end + (std::string_view(schema_end, 3) == "://" ? 3 : 0); - const auto host_end = std::find_if(host_begin, uri_end, [](auto ch) { - return ch == ':' or ch == '/' or ch == '?' or ch == '#'; - }); + const auto host_end = + std::ranges::find_if(host_begin, uri_end, [](auto ch) { + return ch == ':' or ch == '/' or ch == '?' or ch == '#'; + }); result.Host.assign(host_begin, host_end); - if (std::find_if_not( + if (std::ranges::find_if_not( host_begin, host_end, [](auto ch) { return std::isalnum(ch) or ch == '.' or ch == '-'; }) @@ -88,14 +90,17 @@ namespace kagome::common { } // Port - const auto port_begin = host_end + (*host_end == ':' ? 1 : 0); - const auto port_end = std::find_if(port_begin, uri_end, [](auto ch) { - return ch == '/' or ch == '?' or ch == '#'; - }); + const auto port_begin = + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + host_end + (*host_end == ':' ? 1 : 0); + const auto port_end = + std::ranges::find_if(port_begin, uri_end, [](auto ch) { + return ch == '/' or ch == '?' or ch == '#'; + }); result.Port.assign(port_begin, port_end); - if (std::find_if_not( + if (std::ranges::find_if_not( port_begin, port_end, [](auto ch) { return std::isdigit(ch); }) != port_end or (result.Port.empty() and *host_end == ':') or (result.Port == "0") @@ -108,19 +113,23 @@ namespace kagome::common { // Path const auto path_begin = port_end; - const auto path_end = std::find_if( + const auto path_end = std::ranges::find_if( path_begin, uri_end, [](auto ch) { return ch == '?' or ch == '#'; }); result.Path.assign(path_begin, path_end); // Query - const auto query_begin = path_end + (*path_end == '?' ? 1 : 0); + const auto query_begin = + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + path_end + (*path_end == '?' ? 1 : 0); const auto query_end = std::find(query_begin, uri_end, '#'); result.Query.assign(query_begin, query_end); // Fragment - const auto fragment_begin = query_end + (*query_end == '#' ? 1 : 0); + const auto fragment_begin = + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + query_end + (*query_end == '#' ? 1 : 0); const auto fragment_end = uri_end; result.Fragment.assign(fragment_begin, fragment_end); diff --git a/core/common/wrapper.hpp b/core/common/wrapper.hpp index cc7a7f9c31..f5aee382d3 100644 --- a/core/common/wrapper.hpp +++ b/core/common/wrapper.hpp @@ -44,9 +44,8 @@ namespace kagome::common { T data_; }; - template ::value>> + template + requires std::is_arithmetic_v bool operator<(const Wrapper &a, const Wrapper &b) { return a.unwrap() < b.unwrap(); } diff --git a/core/consensus/babe/impl/babe.cpp b/core/consensus/babe/impl/babe.cpp index b15c4ce6f7..67aa4e5d31 100644 --- a/core/consensus/babe/impl/babe.cpp +++ b/core/consensus/babe/impl/babe.cpp @@ -58,6 +58,7 @@ namespace { constexpr const char *kIsRelayChainValidator = "kagome_node_is_active_validator"; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) kagome::metrics::HistogramTimer metric_block_proposal_time{ "kagome_proposer_block_constructed", "Time taken to construct new block", @@ -96,7 +97,7 @@ namespace kagome::consensus::babe { : log_(log::createLogger("Babe", "babe")), clock_(clock), block_tree_(std::move(block_tree)), - slots_util_(std::move(slots_util)), + slots_util_(slots_util), config_repo_(std::move(config_repo)), timings_(timings), session_keys_(std::move(session_keys)), @@ -117,6 +118,7 @@ namespace kagome::consensus::babe { offchain_worker_pool_(std::move(offchain_worker_pool)), main_pool_handler_{main_thread_pool.handler(app_state_manager)}, worker_pool_handler_{worker_thread_pool.handler(app_state_manager)}, + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) is_validator_by_config_(app_config.roles().flags.authority != 0), telemetry_{telemetry::createTelemetryService()} { BOOST_ASSERT(block_tree_); @@ -180,9 +182,7 @@ namespace kagome::consensus::babe { } const auto &disabled_validators = disabled_validators_res.value(); - if (std::binary_search(disabled_validators.begin(), - disabled_validators.end(), - authority_index)) { + if (std::ranges::binary_search(disabled_validators, authority_index)) { return ValidatorStatus::DisabledValidator; } @@ -403,22 +403,23 @@ namespace kagome::consensus::babe { common::Buffer pre_runtime_data{std::move(encode_res.value())}; return primitives::PreRuntime{ - {primitives::kBabeEngineId, std::move(pre_runtime_data)}}; + {.consensus_engine_id = primitives::kBabeEngineId, + .data = std::move(pre_runtime_data)}}; } outcome::result Babe::makeSeal( const primitives::Block &block) const { // Calculate and save hash, 'cause it's new produced block // Note: it is temporary hash significant for signing - primitives::calculateBlockHash( - const_cast(block.header), *hasher_); + primitives::calculateBlockHash(block.header, *hasher_); auto signature_res = sr25519_provider_->sign(*slot_leadership_.keypair, block.header.hash()); if (signature_res.has_value()) { Seal seal{.signature = signature_res.value()}; auto encoded_seal = common::Buffer(scale::encode(seal).value()); - return primitives::Seal{{primitives::kBabeEngineId, encoded_seal}}; + return primitives::Seal{{.consensus_engine_id = primitives::kBabeEngineId, + .data = std::move(encoded_seal)}}; } SL_ERROR(log_, "Error signing a block seal: {}", signature_res.error()); @@ -504,7 +505,7 @@ namespace kagome::consensus::babe { pre_digest_res.error()); return BlockProductionError::CAN_NOT_PREPARE_BLOCK; } - const auto &pre_digest = pre_digest_res.value(); + auto &pre_digest = pre_digest_res.value(); auto propose = [wp{weak_from_this()}, inherent_data{std::move(inherent_data)}, @@ -622,12 +623,11 @@ namespace kagome::consensus::babe { telemetry_->pushBlockStats(); // finally, broadcast the sealed block - announce_transmitter_->blockAnnounce(network::BlockAnnounce{ - block.header, - block_info == block_tree_->bestBlock() ? network::BlockState::Best - : network::BlockState::Normal, - common::Buffer{}, - }); + announce_transmitter_->blockAnnounce( + {.header = block.header, + .state = block_info == block_tree_->bestBlock() + ? network::BlockState::Best + : network::BlockState::Normal}); SL_DEBUG( log_, "Announced block number {} in slot {} (epoch {}) with timestamp {}", diff --git a/core/consensus/babe/impl/babe.hpp b/core/consensus/babe/impl/babe.hpp index abc0d3df0b..9d49cb04c2 100644 --- a/core/consensus/babe/impl/babe.hpp +++ b/core/consensus/babe/impl/babe.hpp @@ -197,15 +197,15 @@ namespace kagome::consensus::babe { std::shared_ptr worker_pool_handler_; const bool is_validator_by_config_; - bool is_active_validator_; + bool is_active_validator_{}; using KeypairWithIndexOpt = std::optional< std::pair, AuthorityIndex>>; primitives::BlockInfo parent_; TimePoint slot_timestamp_; - SlotNumber slot_; - EpochNumber epoch_; + SlotNumber slot_{}; + EpochNumber epoch_{}; SlotLeadership slot_leadership_; // Metrics diff --git a/core/consensus/babe/impl/babe_block_validator_impl.cpp b/core/consensus/babe/impl/babe_block_validator_impl.cpp index 465d86122e..1bf170a0df 100644 --- a/core/consensus/babe/impl/babe_block_validator_impl.cpp +++ b/core/consensus/babe/impl/babe_block_validator_impl.cpp @@ -58,7 +58,7 @@ namespace kagome::consensus::babe { std::shared_ptr babe_api, primitives::events::SyncStateSubscriptionEnginePtr sync_state_observable) : log_(log::createLogger("BabeBlockValidatorImpl", "babe")), - slots_util_(std::move(slots_util)), + slots_util_(slots_util), config_repo_(std::move(config_repo)), hasher_(std::move(hasher)), sr25519_provider_(std::move(sr25519_provider)), @@ -156,9 +156,8 @@ namespace kagome::consensus::babe { block_header.blockInfo()); } - if (std::binary_search(disabled_validators.begin(), - disabled_validators.end(), - babe_header.authority_index)) { + if (std::ranges::binary_search(disabled_validators, + babe_header.authority_index)) { SL_VERBOSE(log_, "Block {} is invalid because produced by disabled validator", block_header.blockInfo()); diff --git a/core/consensus/babe/impl/babe_config_repository_impl.cpp b/core/consensus/babe/impl/babe_config_repository_impl.cpp index 3764315dac..786753be9f 100644 --- a/core/consensus/babe/impl/babe_config_repository_impl.cpp +++ b/core/consensus/babe/impl/babe_config_repository_impl.cpp @@ -43,7 +43,7 @@ namespace kagome::consensus::babe { constexpr size_t kMaxUnindexedBlocksNum = 10000; inline static NextConfigDataV1 getConfig(const BabeConfiguration &state) { - return {state.leadership_rate, state.allowed_slots}; + return {.ratio = state.leadership_rate, .second_slot = state.allowed_slots}; } BabeConfigRepositoryImpl::BabeConfigRepositoryImpl( @@ -71,11 +71,11 @@ namespace kagome::consensus::babe { block_tree_, }, header_repo_(std::move(header_repo)), - consensus_selector_(std::move(consensus_selector)), + consensus_selector_(consensus_selector), babe_api_(std::move(babe_api)), trie_storage_(std::move(trie_storage)), - chain_sub_{chain_events_engine}, - slots_util_(std::move(slots_util)), + chain_sub_{std::move(chain_events_engine)}, + slots_util_(slots_util), logger_(log::createLogger("BabeConfigRepo", "babe_config_repo")) { BOOST_ASSERT(persistent_storage_ != nullptr); BOOST_ASSERT(block_tree_ != nullptr); @@ -97,12 +97,12 @@ namespace kagome::consensus::babe { if (auto res = scale::decode(*genesis_slot_raw)) { first_block_slot_number_ = res.value(); } else { - SL_ERROR(logger_, "genesis slot decode error: {}", res.error()); + SL_ERROR(logger_, "Can't decode genesis slot: {}", res.error()); std::ignore = persistent_storage_->remove(storage::kFirstBlockSlot); } } } else { - SL_ERROR(logger_, "genesis slot db read error: {}", res.error()); + SL_ERROR(logger_, "Can't retrieve genesis slot from DB: {}", res.error()); return false; } @@ -140,7 +140,7 @@ namespace kagome::consensus::babe { return config(indexer_, best, true); }; if (not res and not config_warp_sync_) { - SL_ERROR(logger_, "get config at best {} error: {}", best, res.error()); + SL_ERROR(logger_, "Can't get config at best {}: {}", best, res.error()); auto best_header = block_tree_->getBlockHeader(best.hash).value(); if (not trie_storage_->getEphemeralBatchAt(best_header.state_root)) { SL_ERROR(logger_, @@ -245,22 +245,23 @@ namespace kagome::consensus::babe { if (not prev) { OUTCOME_TRY(_state, babe_api_->configuration(info.hash)); auto state = std::make_shared(std::move(_state)); - BabeIndexedValue value{getConfig(*state), state, std::nullopt, state}; + BabeIndexedValue value{ + .config = getConfig(*state), .state = state, .next_state = state}; if (info.number != 0) { OUTCOME_TRY(next, babe_api_->next_epoch(info.hash)); BOOST_ASSERT(state->epoch_length == next.duration); value.next_state_warp = std::make_shared(BabeConfiguration{ - state->slot_duration, - next.duration, - next.leadership_rate, - std::move(next.authorities), - next.randomness, - next.allowed_slots, + .slot_duration = state->slot_duration, + .epoch_length = next.duration, + .leadership_rate = next.leadership_rate, + .authorities = std::move(next.authorities), + .randomness = next.randomness, + .allowed_slots = next.allowed_slots, }); value.next_state = value.next_state_warp; } - indexer_.put(info, {value, std::nullopt}, true); + indexer_.put(info, {.value = value}, true); if (i_first == i_last) { return outcome::success(); } @@ -277,16 +278,16 @@ namespace kagome::consensus::babe { } auto state = applyDigests(getConfig(*prev_state), digests); BabeIndexedValue value{ - getConfig(*state), - std::nullopt, - std::nullopt, - state, + .config = getConfig(*state), + .next_state = state, }; - indexer_.put(info, {value, prev}, block_tree_->isFinalized(info)); + indexer_.put(info, + {.value = value, .prev = prev}, + block_tree_->isFinalized(info)); prev = info; prev_state = state; } else { - indexer_.put(info, {std::nullopt, prev, true}, false); + indexer_.put(info, {.prev = prev, .inherit = true}, false); } if (i_first == i_last) { break; diff --git a/core/consensus/babe/impl/babe_lottery_impl.hpp b/core/consensus/babe/impl/babe_lottery_impl.hpp index 4b9f706c6a..231380f247 100644 --- a/core/consensus/babe/impl/babe_lottery_impl.hpp +++ b/core/consensus/babe/impl/babe_lottery_impl.hpp @@ -55,9 +55,9 @@ namespace kagome::consensus::babe { // Data of actual epoch EpochNumber epoch_; Randomness randomness_; - AuthorityIndex auth_number_; + AuthorityIndex auth_number_{}; KeypairWithIndexOpt keypair_; Threshold threshold_; - AllowedSlots allowed_slots_; + AllowedSlots allowed_slots_{}; }; } // namespace kagome::consensus::babe diff --git a/core/consensus/babe/impl/threshold_util.cpp b/core/consensus/babe/impl/threshold_util.cpp index f0c334793d..e28e2fea40 100644 --- a/core/consensus/babe/impl/threshold_util.cpp +++ b/core/consensus/babe/impl/threshold_util.cpp @@ -16,7 +16,8 @@ namespace kagome::consensus::babe { AuthorityIndex authority_index) { BOOST_ASSERT(authority_index < authorities.size()); - double float_point_ratio = double(ratio.first) / ratio.second; + double float_point_ratio = + static_cast(ratio.first) / static_cast(ratio.second); using boost::adaptors::transformed; double theta = double(authorities[authority_index].weight) diff --git a/core/consensus/babe/types/babe_block_header.hpp b/core/consensus/babe/types/babe_block_header.hpp index bc3f6b11a6..b6af7a024b 100644 --- a/core/consensus/babe/types/babe_block_header.hpp +++ b/core/consensus/babe/types/babe_block_header.hpp @@ -24,10 +24,10 @@ namespace kagome::consensus::babe { SlotType slot_assignment_type{}; /// authority index of the producer - AuthorityIndex authority_index; + AuthorityIndex authority_index{}; /// slot, in which the block was produced - SlotNumber slot_number; + SlotNumber slot_number{}; /// output of VRF function crypto::VRFOutput vrf_output{}; diff --git a/core/consensus/babe/types/scheduled_change.hpp b/core/consensus/babe/types/scheduled_change.hpp index 2fe08c66e2..e66b7b0580 100644 --- a/core/consensus/babe/types/scheduled_change.hpp +++ b/core/consensus/babe/types/scheduled_change.hpp @@ -16,7 +16,7 @@ namespace kagome::consensus::babe { struct NextConfigDataV1 final { SCALE_TIE(2); std::pair ratio; - AllowedSlots second_slot; + AllowedSlots second_slot{}; }; using NextConfigData = std::variant, NextConfigDataV1>; diff --git a/core/consensus/beefy/impl/beefy_impl.cpp b/core/consensus/beefy/impl/beefy_impl.cpp index 56c7d1100b..7a7aaf7fdb 100644 --- a/core/consensus/beefy/impl/beefy_impl.cpp +++ b/core/consensus/beefy/impl/beefy_impl.cpp @@ -38,14 +38,18 @@ namespace kagome::network { constexpr std::chrono::minutes kRebroadcastAfter{1}; - metrics::GaugeHelper metric_validator_set_id{ - "kagome_beefy_validator_set_id", - "Current BEEFY active validator set id.", - }; - metrics::GaugeHelper metric_finalized{ - "kagome_beefy_best_block", - "Best block finalized by BEEFY", - }; + namespace { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) + metrics::GaugeHelper metric_validator_set_id{ + "kagome_beefy_validator_set_id", + "Current BEEFY active validator set id.", + }; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) + metrics::GaugeHelper metric_finalized{ + "kagome_beefy_best_block", + "Best block finalized by BEEFY", + }; + } // namespace BeefyImpl::BeefyImpl( std::shared_ptr app_state_manager, @@ -75,10 +79,10 @@ namespace kagome::network { beefy_pool_handler_{poolHandlerReadyMake( this, app_state_manager, beefy_thread_pool, log_)}, scheduler_{std::move(scheduler)}, - timeline_{std::move(timeline)}, + timeline_{timeline}, session_keys_{std::move(session_keys)}, - beefy_protocol_{std::move(beefy_protocol)}, - beefy_justification_protocol_{std::move(beefy_justification_protocol)}, + beefy_protocol_{beefy_protocol}, + beefy_justification_protocol_{beefy_justification_protocol}, offchain_worker_factory_{std::move(offchain_worker_factory)}, offchain_worker_pool_{std::move(offchain_worker_pool)}, min_delta_{chain_spec.beefyMinDelta()}, @@ -207,7 +211,8 @@ namespace kagome::network { SL_WARN(log_, "won't report own double woting"); return; } - auto r = reportDoubleVoting({vote_it->second.first, vote}); + auto r = reportDoubleVoting( + {.first = vote_it->second.first, .second = vote}); if (not r) { SL_WARN(log_, "reportDoubleVoting: {}", r.error()); } @@ -221,14 +226,14 @@ namespace kagome::network { if (round == session.rounds.end()) { round = session.rounds.emplace(block_number, Round{}).first; } - round->second.double_voting.emplace(*index, DoubleVoting{vote}); + round->second.double_voting.emplace(*index, DoubleVoting{.first = vote}); auto justification = round->second.justifications.find(vote.commitment); if (justification == round->second.justifications.end()) { - justification = - round->second.justifications - .emplace(vote.commitment, - consensus::beefy::SignedCommitment{vote.commitment, {}}) - .first; + justification = round->second.justifications + .emplace(vote.commitment, + consensus::beefy::SignedCommitment{ + .commitment = vote.commitment}) + .first; } justification->second.signatures.resize(total); justification->second.signatures[*index] = vote.signature; @@ -361,7 +366,7 @@ namespace kagome::network { OUTCOME_TRY(db_->put(BlockNumberKey::encode(block_number), scale::encode(justification_v1).value())); if (beefy_finalized_ > *beefy_genesis_ - and sessions_.count(beefy_finalized_) == 0) { + and not sessions_.contains(beefy_finalized_)) { OUTCOME_TRY(last_hash, block_tree_->getBlockHash(beefy_finalized_)); if (last_hash) { if (auto r = block_tree_->getBlockHeader(*last_hash)) { @@ -381,7 +386,7 @@ namespace kagome::network { session->second.rounds.upper_bound(block_number)); } if (found) { - sessions_.emplace(first, Session{std::move(validators), {}}); + sessions_.emplace(first, Session{.validators = std::move(validators)}); metricValidatorSetId(); } SL_INFO(log_, "finalized {}", block_number); @@ -509,7 +514,8 @@ namespace kagome::network { findValidators(next_digest_, sessions_.empty() ? *beefy_genesis_ : next_digest_)); if (found) { - sessions_.emplace(found->first, Session{std::move(found->second), {}}); + sessions_.emplace(found->first, + Session{.validators = std::move(found->second)}); metricValidatorSetId(); } ++next_digest_; @@ -583,8 +589,9 @@ namespace kagome::network { OUTCOME_TRY(sig, ecdsa_->signPrehashed(consensus::beefy::prehash(*commitment), key->first->secret_key)); - consensus::beefy::VoteMessage vote{ - std::move(*commitment), key->first->public_key, sig}; + consensus::beefy::VoteMessage vote{.commitment = std::move(*commitment), + .id = key->first->public_key, + .signature = sig}; onVote(vote, true); last_voted_ = target; last_vote_ = std::move(vote); @@ -607,9 +614,9 @@ namespace kagome::network { return std::nullopt; } return consensus::beefy::Commitment{ - {{consensus::beefy::kMmr, common::Buffer{*mmr}}}, - block_number, - validator_set_id, + .payload = {{consensus::beefy::kMmr, common::Buffer{*mmr}}}, + .block_number = block_number, + .validator_set_id = validator_set_id, }; } diff --git a/core/consensus/beefy/types.hpp b/core/consensus/beefy/types.hpp index 5adba98288..f04ea7bc37 100644 --- a/core/consensus/beefy/types.hpp +++ b/core/consensus/beefy/types.hpp @@ -130,7 +130,8 @@ namespace kagome::consensus::beefy { struct DoubleVotingProof { SCALE_TIE(2); - VoteMessage first, second; + VoteMessage first; + VoteMessage second; }; } // namespace kagome::consensus::beefy diff --git a/core/consensus/grandpa/ancestry_verifier.hpp b/core/consensus/grandpa/ancestry_verifier.hpp index bd57accd0b..d31443fbb8 100644 --- a/core/consensus/grandpa/ancestry_verifier.hpp +++ b/core/consensus/grandpa/ancestry_verifier.hpp @@ -25,8 +25,7 @@ namespace kagome::consensus::grandpa { // Calculate and save hash, 'cause data // has likely just received from network if (not block.hash_opt.has_value()) { - primitives::calculateBlockHash( - const_cast(block), hasher); + primitives::calculateBlockHash(block, hasher); } parents.emplace(block.blockInfo(), *block.parentInfo()); } diff --git a/core/consensus/grandpa/impl/authority_manager_impl.cpp b/core/consensus/grandpa/impl/authority_manager_impl.cpp index dc37c3dd29..f637c7708e 100644 --- a/core/consensus/grandpa/impl/authority_manager_impl.cpp +++ b/core/consensus/grandpa/impl/authority_manager_impl.cpp @@ -29,7 +29,7 @@ namespace kagome::consensus::grandpa { grandpa_api_(std::move(grandpa_api)), persistent_storage_{ persistent_storage->getSpace(storage::Space::kDefault)}, - chain_sub_{chain_events_engine}, + chain_sub_{std::move(chain_events_engine)}, indexer_{ std::make_shared( storage::kAuthorityManagerImplIndexerPrefix, @@ -69,15 +69,16 @@ namespace kagome::consensus::grandpa { return std::nullopt; } std::unique_lock lock{mutex_}; - if (auto r = authoritiesOutcome(target_block, finalized.operator bool())) { + auto r = authoritiesOutcome(target_block, finalized.operator bool()); + if (r.has_value()) { return std::move(r.value()); - } else { - SL_WARN(logger_, - "authorities {} finalized={} error: {}", - target_block, - finalized.operator bool(), - r.error()); } + + SL_WARN(logger_, + "authorities {} finalized={} error: {}", + target_block, + (bool)finalized, + r.error()); return std::nullopt; } @@ -97,12 +98,16 @@ namespace kagome::consensus::grandpa { OUTCOME_TRY(list, grandpa_api_->authorities(info.hash)); auto genesis = std::make_shared(0, std::move(list)); GrandpaIndexedValue value{ - genesis->id, - std::nullopt, - genesis, - genesis, + .next_set_id = genesis->id, + .state = genesis, + .next = genesis, }; - indexer_.put(info, {value, std::nullopt}, true); + indexer_.put(info, + { + .value = value, + .prev = std::nullopt, + }, + true); if (i_first == i_last) { return outcome::success(); } @@ -154,11 +159,15 @@ namespace kagome::consensus::grandpa { } auto state = applyDigests(info, value.next_set_id, digests); value.next = state; - indexer_.put(info, {value, prev}, block_tree_->isFinalized(info)); + indexer_.put(info, + {.value = value, .prev = prev}, + block_tree_->isFinalized(info)); prev = info; prev_state = state; } else { - indexer_.put(info, {std::nullopt, prev, true}, false); + indexer_.put(info, + {.value = std::nullopt, .prev = prev, .inherit = true}, + false); } if (i_first == i_last) { break; @@ -232,17 +241,14 @@ namespace kagome::consensus::grandpa { const AuthoritySet &authorities) { std::unique_lock lock{mutex_}; GrandpaIndexedValue value{ - authorities.id + 1, - std::nullopt, - std::nullopt, - std::nullopt, + .next_set_id = authorities.id + 1, }; HasAuthoritySetChange digests{header}; if (not digests.scheduled) { auto state = std::make_shared(authorities); - value = {authorities.id, std::nullopt, state, state}; + value = {.next_set_id = authorities.id, .state = state, .next = state}; } - indexer_.put(block, {value, std::nullopt}, true); + indexer_.put(block, {.value = value}, true); } AuthorityManager::ScheduledParentResult AuthorityManagerImpl::scheduledParent( diff --git a/core/consensus/grandpa/impl/environment_impl.cpp b/core/consensus/grandpa/impl/environment_impl.cpp index c5cd2adf0c..3bb65b9bff 100644 --- a/core/consensus/grandpa/impl/environment_impl.cpp +++ b/core/consensus/grandpa/impl/environment_impl.cpp @@ -65,7 +65,7 @@ namespace kagome::consensus::grandpa { authority_manager_{std::move(authority_manager)}, transmitter_{std::move(transmitter)}, approved_ancestor_(std::move(approved_ancestor)), - justification_observer_(std::move(justification_observer)), + justification_observer_(justification_observer), verified_justification_queue_(std::move(verified_justification_queue)), grandpa_api_(std::move(grandpa_api)), dispute_coordinator_(std::move(dispute_coordinator)), @@ -109,7 +109,7 @@ namespace kagome::consensus::grandpa { } OUTCOME_TRY(chain, block_tree_->getChainByBlocks(base, block)); - std::reverse(chain.begin(), chain.end()); + std::ranges::reverse(chain); return chain; } @@ -252,6 +252,7 @@ namespace kagome::consensus::grandpa { *main_pool_handler_, onCatchUpRequested, peer_id, set_id, round_number); network::CatchUpRequest message{.round_number = round_number, .voter_set_id = set_id}; + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) transmitter_->sendCatchUpRequest(peer_id, std::move(message)); } @@ -283,72 +284,70 @@ namespace kagome::consensus::grandpa { void EnvironmentImpl::onVoted(RoundNumber round, VoterSetId set_id, const SignedMessage &vote) { - main_pool_handler_->execute([wself{weak_from_this()}, - round{std::move(round)}, - set_id{std::move(set_id)}, - vote]() mutable { - if (auto self = wself.lock()) { - SL_VERBOSE( - self->logger_, - "Round #{}: Send {} signed by {} for block {}", - round, - visit_in_place( - vote.message, - [&](const Prevote &) { return "prevote"; }, - [&](const Precommit &) { return "precommit"; }, - [&](const PrimaryPropose &) { return "primary propose"; }), - vote.id, - vote.getBlockInfo()); - - self->transmitter_->sendVoteMessage( - network::GrandpaVote{{.round_number = std::move(round), - .counter = std::move(set_id), - .vote = std::move(vote)}}); - } - }); + main_pool_handler_->execute( + [wself{weak_from_this()}, round, set_id, vote]() mutable { + if (auto self = wself.lock()) { + SL_VERBOSE( + self->logger_, + "Round #{}: Send {} signed by {} for block {}", + round, + visit_in_place( + vote.message, + [&](const Prevote &) { return "prevote"; }, + [&](const Precommit &) { return "precommit"; }, + [&](const PrimaryPropose &) { return "primary propose"; }), + vote.id, + vote.getBlockInfo()); + + self->transmitter_->sendVoteMessage(network::GrandpaVote{{ + .round_number = round, + .counter = set_id, + .vote = vote, + }}); + } + }); } void EnvironmentImpl::sendState(const libp2p::peer::PeerId &peer_id, const MovableRoundState &state, VoterSetId voter_set_id) { - main_pool_handler_->execute([wself{weak_from_this()}, - peer_id, - voter_set_id{std::move(voter_set_id)}, - state]() mutable { - if (auto self = wself.lock()) { - auto send = [&](const SignedMessage &vote) { - SL_DEBUG( - self->logger_, - "Round #{}: Send {} signed by {} for block {} (as send " - "state)", - state.round_number, + main_pool_handler_->execute( + [wself{weak_from_this()}, peer_id, voter_set_id, state]() mutable { + if (auto self = wself.lock()) { + auto send = [&](const SignedMessage &vote) { + SL_DEBUG(self->logger_, + "Round #{}: Send {} signed by {} for block {} (as send " + "state)", + state.round_number, + visit_in_place( + vote.message, + [&](const Prevote &) { return "prevote"; }, + [&](const Precommit &) { return "precommit"; }, + [&](const PrimaryPropose &) { + return "primary propose"; + }), + vote.id, + vote.getBlockInfo()); + + ; + self->transmitter_->sendVoteMessage( + peer_id, + network::GrandpaVote{{.round_number = state.round_number, + .counter = voter_set_id, + .vote = vote}}); + }; + + for (const auto &vv : state.votes) { visit_in_place( - vote.message, - [&](const Prevote &) { return "prevote"; }, - [&](const Precommit &) { return "precommit"; }, - [&](const PrimaryPropose &) { return "primary propose"; }), - vote.id, - vote.getBlockInfo()); - - ; - self->transmitter_->sendVoteMessage( - peer_id, - network::GrandpaVote{{.round_number = state.round_number, - .counter = voter_set_id, - .vote = vote}}); - }; - - for (const auto &vv : state.votes) { - visit_in_place( - vv, - [&](const SignedMessage &vote) { send(vote); }, - [&](const EquivocatorySignedMessage &pair_vote) { - send(pair_vote.first); - send(pair_vote.second); - }); - } - } - }); + vv, + [&](const SignedMessage &vote) { send(vote); }, + [&](const EquivocatorySignedMessage &pair_vote) { + send(pair_vote.first); + send(pair_vote.second); + }); + } + } + }); } void EnvironmentImpl::onCommitted(RoundNumber round, @@ -390,9 +389,12 @@ namespace kagome::consensus::grandpa { last_finalized); SL_DEBUG(logger_, "Round #{}: Send neighbor message", round); - network::GrandpaNeighborMessage message{.round_number = round, - .voter_set_id = set_id, - .last_finalized = last_finalized}; + network::GrandpaNeighborMessage message{ + .round_number = round, + .voter_set_id = set_id, + .last_finalized = last_finalized, + }; + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) transmitter_->sendNeighborMessage(std::move(message)); } @@ -486,7 +488,7 @@ namespace kagome::consensus::grandpa { // submit an equivocation report at **best** block EquivocationProof equivocation_proof{ .set_id = authority_set_id, - .equivocation = std::move(equivocation), + .equivocation = equivocation, }; offchain_worker_pool_->addWorker(offchain_worker_factory_->make()); diff --git a/core/consensus/grandpa/impl/grandpa_impl.cpp b/core/consensus/grandpa/impl/grandpa_impl.cpp index a4917564bc..725d16650d 100644 --- a/core/consensus/grandpa/impl/grandpa_impl.cpp +++ b/core/consensus/grandpa/impl/grandpa_impl.cpp @@ -43,7 +43,7 @@ namespace { "kagome_finality_grandpa_round"; template - auto toMilliseconds(D &&duration) { + auto toMilliseconds(const D &duration) { return std::chrono::duration_cast(duration); } } // namespace @@ -100,8 +100,8 @@ namespace kagome::consensus::grandpa { peer_manager_(std::move(peer_manager)), block_tree_(std::move(block_tree)), reputation_repository_(std::move(reputation_repository)), - timeline_{std::move(timeline)}, - chain_sub_{chain_sub_engine}, + timeline_{timeline}, + chain_sub_{std::move(chain_sub_engine)}, db_{db.getSpace(storage::Space::kDefault)}, main_pool_handler_{main_thread_pool.handler(*app_state_manager)}, grandpa_pool_handler_{poolHandlerReadyMake( @@ -282,7 +282,8 @@ namespace kagome::consensus::grandpa { return VotingRoundError::NO_KNOWN_AUTHORITIES_FOR_BLOCK; } OUTCOME_TRY(voters, VoterSet::make(**authorities)); - MovableRoundState state{1, finalized, {}, std::nullopt}; + MovableRoundState state{.round_number = 1, + .last_finalized_block = finalized}; if (finalized.number != 0) { OUTCOME_TRY(raw_justification, block_tree_->getBlockJustification(finalized.hash)); @@ -357,7 +358,9 @@ namespace kagome::consensus::grandpa { REINVOKE(*grandpa_pool_handler_, onNeighborMessage, peer_id, + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) std::move(info), + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) std::move(msg)); BOOST_ASSERT(grandpa_pool_handler_->isInCurrentThread()); @@ -435,7 +438,8 @@ namespace kagome::consensus::grandpa { } pending_catchup_request_.emplace( peer_id, - network::CatchUpRequest{msg.round_number - 1, msg.voter_set_id}); + network::CatchUpRequest{.round_number = msg.round_number - 1, + .voter_set_id = msg.voter_set_id}); catchup_request_timer_handle_ = scheduler_->scheduleWithHandle( [wp{weak_from_this()}] { auto self = wp.lock(); @@ -470,7 +474,9 @@ namespace kagome::consensus::grandpa { REINVOKE(*grandpa_pool_handler_, onCatchUpRequest, peer_id, + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) std::move(info_opt), + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) std::move(msg)); if (not info_opt.has_value() or not info_opt->set_id.has_value() @@ -739,7 +745,7 @@ namespace kagome::consensus::grandpa { } GrandpaContext grandpa_context; - VotingRoundUpdate update{*round, grandpa_context}; + VotingRoundUpdate update{.round = *round, .ctx = grandpa_context}; for (auto &vote : msg.prevote_justification) { update.vote(vote); } @@ -767,9 +773,10 @@ namespace kagome::consensus::grandpa { * grandpa_context.checked_signature_counter); } if (allow_missing_blocks) { - loadMissingBlocks({peer_id, - std::move(msg), - std::move(grandpa_context.missing_blocks)}); + loadMissingBlocks( + {.peer = peer_id, + .msg = std::move(msg), + .blocks = std::move(grandpa_context.missing_blocks)}); } return; } @@ -789,7 +796,12 @@ namespace kagome::consensus::grandpa { const libp2p::peer::PeerId &peer_id, std::optional &&info, VoteMessage &&msg) { - onVoteMessage(peer_id, std::move(info), std::move(msg), true); + onVoteMessage( + peer_id, + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + std::move(info), + std::move(msg), + true); } void GrandpaImpl::onVoteMessage( @@ -800,6 +812,7 @@ namespace kagome::consensus::grandpa { REINVOKE(*grandpa_pool_handler_, onVoteMessage, peer_id, + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) std::move(info), msg, allow_missing_blocks); @@ -944,7 +957,8 @@ namespace kagome::consensus::grandpa { peer_id); GrandpaContext grandpa_context; - VotingRoundUpdate update{*target_round, grandpa_context, true}; + VotingRoundUpdate update{ + .round = *target_round, .ctx = grandpa_context, .propagate = true}; update.vote(msg.vote); update.update(); @@ -971,9 +985,10 @@ namespace kagome::consensus::grandpa { if (not target_round->finalizedBlock().has_value()) { if (allow_missing_blocks) { - loadMissingBlocks({peer_id, - std::move(msg), - std::move(grandpa_context.missing_blocks)}); + loadMissingBlocks( + {.peer = peer_id, + .msg = std::move(msg), + .blocks = std::move(grandpa_context.missing_blocks)}); } return; } @@ -993,7 +1008,7 @@ namespace kagome::consensus::grandpa { msg, allow_missing_blocks); - // TODO check if height of commit less then previous one + // TODO(xDimon) check if height of commit less then previous one // if (new_commit_height < last_commit_height) { // reputation_repository_->change( // peer_id, network::reputation::cost::INVALID_VIEW_CHANGE); @@ -1105,7 +1120,9 @@ namespace kagome::consensus::grandpa { } } if (not missing_blocks.empty()) { - loadMissingBlocks({peer_id, std::move(msg), std::move(missing_blocks)}); + loadMissingBlocks({.peer = peer_id, + .msg = std::move(msg), + .blocks = std::move(missing_blocks)}); return; } } @@ -1124,11 +1141,9 @@ namespace kagome::consensus::grandpa { } void GrandpaImpl::callbackCall(ApplyJustificationCb &&callback, - outcome::result &&result) { + const outcome::result &result) { main_pool_handler_->execute( - [callback{std::move(callback)}, result{std::move(result)}]() mutable { - callback(std::move(result)); - }); + [callback{std::move(callback)}, result]() { callback(result); }); } outcome::result GrandpaImpl::verifyJustification( @@ -1139,7 +1154,8 @@ namespace kagome::consensus::grandpa { state.round_number = justification.round_number; auto round = std::make_shared( shared_from_this(), - GrandpaConfig{voters, justification.round_number, {}, {}}, + GrandpaConfig{.voters = voters, + .round_number = justification.round_number}, hasher_, environment_, std::make_shared( @@ -1184,7 +1200,7 @@ namespace kagome::consensus::grandpa { } else { r = environment_->finalize(authority_set->id, justification); } - callbackCall(std::move(callback), std::move(r)); + callbackCall(std::move(callback), r); return; } std::shared_ptr round; @@ -1386,8 +1402,7 @@ namespace kagome::consensus::grandpa { vote, set_index); auto &[votes, dirty] = historicalVotes(set, round); - if (std::find(votes.seen.begin(), votes.seen.end(), vote) - != votes.seen.end()) { + if (std::ranges::find(votes.seen, vote) != votes.seen.end()) { return; } if (set_index) { @@ -1449,7 +1464,7 @@ namespace kagome::consensus::grandpa { void GrandpaImpl::applyHistoricalVotes(VotingRound &round) { auto &votes = historicalVotes(round.voterSetId(), round.roundNumber()).first; - VotingRoundUpdate update{round}; + VotingRoundUpdate update{.round = round}; for (auto &vote : votes.seen) { update.vote(vote); } diff --git a/core/consensus/grandpa/impl/grandpa_impl.hpp b/core/consensus/grandpa/impl/grandpa_impl.hpp index 60b296790e..a9a6189d3b 100644 --- a/core/consensus/grandpa/impl/grandpa_impl.hpp +++ b/core/consensus/grandpa/impl/grandpa_impl.hpp @@ -187,7 +187,7 @@ namespace kagome::consensus::grandpa { void startCurrentRound(); void callbackCall(ApplyJustificationCb &&callback, - outcome::result &&result); + const outcome::result &result); /** * Selects round by provided number and voter set id * @param round_number number of round to be selected diff --git a/core/consensus/grandpa/impl/verified_justification_queue.cpp b/core/consensus/grandpa/impl/verified_justification_queue.cpp index 6b0297886a..483bd59d29 100644 --- a/core/consensus/grandpa/impl/verified_justification_queue.cpp +++ b/core/consensus/grandpa/impl/verified_justification_queue.cpp @@ -29,9 +29,9 @@ namespace kagome::consensus::grandpa { : main_pool_handler_{main_thread_pool.handler(app_state_manager)}, block_tree_{std::move(block_tree)}, authority_manager_{std::move(authority_manager)}, - synchronizer_{std::move(synchronizer)}, - timeline_{std::move(timeline)}, - chain_sub_{chain_sub_engine}, + synchronizer_{synchronizer}, + timeline_{timeline}, + chain_sub_{std::move(chain_sub_engine)}, log_{log::createLogger("VerifiedJustificationQueue", "grandpa")} { BOOST_ASSERT(main_pool_handler_ != nullptr); BOOST_ASSERT(block_tree_ != nullptr); diff --git a/core/consensus/grandpa/impl/verified_justification_queue.hpp b/core/consensus/grandpa/impl/verified_justification_queue.hpp index 5ecc3520fb..3475f22692 100644 --- a/core/consensus/grandpa/impl/verified_justification_queue.hpp +++ b/core/consensus/grandpa/impl/verified_justification_queue.hpp @@ -80,7 +80,7 @@ namespace kagome::consensus::grandpa { log::Logger log_; using SetAndJustification = std::pair; - AuthoritySetId expected_; + AuthoritySetId expected_ = 0; std::map verified_; std::optional last_; std::set required_; diff --git a/core/consensus/grandpa/impl/voting_round_impl.cpp b/core/consensus/grandpa/impl/voting_round_impl.cpp index f250cf1c66..f868877ebc 100644 --- a/core/consensus/grandpa/impl/voting_round_impl.cpp +++ b/core/consensus/grandpa/impl/voting_round_impl.cpp @@ -27,27 +27,27 @@ namespace kagome::consensus::grandpa { namespace { template - auto convertToPrimaryPropose(T &&vote) { + auto convertToPrimaryPropose(const T &vote) { return PrimaryPropose(vote.number, vote.hash); } template - auto convertToPrevote(T &&vote) { + auto convertToPrevote(const T &vote) { return Prevote(vote.number, vote.hash); } template - auto convertToPrecommit(T &&vote) { + auto convertToPrecommit(const T &vote) { return Precommit(vote.number, vote.hash); } template - auto convertToBlockInfo(T &&vote) { + auto convertToBlockInfo(const T &vote) { return BlockInfo(vote.number, vote.hash); } template - auto toMilliseconds(D &&duration) { + auto toMilliseconds(const D &duration) { return std::chrono::duration_cast(duration); } } // namespace @@ -62,7 +62,7 @@ namespace kagome::consensus::grandpa { std::shared_ptr precommits, std::shared_ptr vote_graph, std::shared_ptr scheduler) - : voter_set_{std::move(config.voters)}, + : voter_set_{config.voters}, round_number_{config.round_number}, duration_{config.duration}, id_{config.id}, @@ -149,7 +149,7 @@ namespace kagome::consensus::grandpa { last_finalized_block_ = round_state.last_finalized_block; if (round_number_ != 0) { - VotingRoundUpdate update{*this}; + VotingRoundUpdate update{.round = *this}; for (auto &vote : round_state.votes) { update.vote(vote); } @@ -653,7 +653,7 @@ namespace kagome::consensus::grandpa { round_number_, justification.block_info); - VotingRoundUpdate update{*this}; + VotingRoundUpdate update{.round = *this}; for (auto &vote : justification.items) { update.vote(vote); } @@ -1055,7 +1055,7 @@ namespace kagome::consensus::grandpa { } } - bool can_start_next_round; + bool can_start_next_round; // NOLINT(cppcoreguidelines-init-variables) // Start next round only when previous round estimate is finalized if (previous_round_) { @@ -1281,6 +1281,7 @@ namespace kagome::consensus::grandpa { const auto tolerated_equivocations = voter_set_->totalWeight() - threshold_; // get total weight of all equivocators + // NOLINTNEXTLINE(boost-use-ranges) const auto current_equivocations = std::accumulate( precommit_equivocators_.begin(), precommit_equivocators_.end(), @@ -1411,15 +1412,14 @@ namespace kagome::consensus::grandpa { auto precommits = precommits_->getMessages(); round_state.votes.reserve(round_state.votes.size() + precommits.size()); - std::move(precommits.begin(), - precommits.end(), - std::back_inserter(round_state.votes)); + std::ranges::move(precommits, std::back_inserter(round_state.votes)); return round_state; } std::vector VotingRoundImpl::getPrevoteJustification( const BlockInfo &estimate, const std::vector &votes) const { + // NOLINTNEXTLINE(boost-use-ranges) auto result = std::accumulate( votes.begin(), votes.end(), @@ -1433,16 +1433,21 @@ namespace kagome::consensus::grandpa { if (env_->hasAncestry(estimate.hash, voting_message.getBlockHash())) { prevotes.push_back( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) static_cast(voting_message)); } } }, [&prevotes](const EquivocatorySignedMessage &equivocatory_voting_message) { - prevotes.push_back(static_cast( - equivocatory_voting_message.first)); - prevotes.push_back(static_cast( - equivocatory_voting_message.second)); + prevotes.push_back( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) + static_cast( + equivocatory_voting_message.first)); + prevotes.push_back( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) + static_cast( + equivocatory_voting_message.second)); }); return std::move(prevotes); }); @@ -1455,6 +1460,7 @@ namespace kagome::consensus::grandpa { VoteWeight::Weight weight = 0; // Collect equivocations first (until threshold is reached) + // NOLINTNEXTLINE(boost-use-ranges) result = std::accumulate( votes.begin(), votes.end(), @@ -1465,16 +1471,21 @@ namespace kagome::consensus::grandpa { voting_variant, [this, &precommits, &weight](const EquivocatorySignedMessage &equivocatory_voting_message) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) auto &signed_precommit = static_cast( equivocatory_voting_message.first); auto voter_weight = voter_set_->voterWeight(signed_precommit.id); if (voter_weight.has_value() and voter_weight.value() > 0) { weight += voter_weight.value(); - precommits.push_back(static_cast( - equivocatory_voting_message.first)); - precommits.push_back(static_cast( - equivocatory_voting_message.second)); + precommits.push_back( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) + static_cast( + equivocatory_voting_message.first)); + precommits.push_back( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) + static_cast( + equivocatory_voting_message.second)); } }, [](const auto &) {}); @@ -1483,6 +1494,7 @@ namespace kagome::consensus::grandpa { }); // Then collect valid precommits (until threshold is reached) + // NOLINTNEXTLINE(boost-use-ranges) result = std::accumulate( votes.begin(), votes.end(), @@ -1500,6 +1512,7 @@ namespace kagome::consensus::grandpa { and env_->hasAncestry(estimate.hash, voting_message.getBlockHash())) { auto &signed_precommit = + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) static_cast(voting_message); weight += voter_set_->voterWeight(signed_precommit.id).value(); diff --git a/core/consensus/grandpa/impl/voting_round_impl.hpp b/core/consensus/grandpa/impl/voting_round_impl.hpp index 2e5c5a6db9..04eb1b55fa 100644 --- a/core/consensus/grandpa/impl/voting_round_impl.hpp +++ b/core/consensus/grandpa/impl/voting_round_impl.hpp @@ -304,9 +304,10 @@ namespace kagome::consensus::grandpa { const Duration duration_; // length of round bool isPrimary_ = false; - size_t threshold_; // supermajority threshold - const std::optional id_; // id of current peer - std::chrono::milliseconds start_time_; // time of start round to play + size_t threshold_; // supermajority threshold + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::optional id_; // id of current peer + std::chrono::milliseconds start_time_{}; // time of start round to play std::weak_ptr grandpa_; std::shared_ptr hasher_; diff --git a/core/consensus/grandpa/justification_observer.hpp b/core/consensus/grandpa/justification_observer.hpp index 21e991bf74..675c7d8459 100644 --- a/core/consensus/grandpa/justification_observer.hpp +++ b/core/consensus/grandpa/justification_observer.hpp @@ -19,7 +19,7 @@ namespace kagome::consensus::grandpa { class JustificationObserver { public: virtual ~JustificationObserver() = default; - using ApplyJustificationCb = std::function &&)>; + using ApplyJustificationCb = std::function)>; /** * Validate {@param justification} with {@param authorities}. diff --git a/core/consensus/grandpa/structs.hpp b/core/consensus/grandpa/structs.hpp index cc8bbb006a..6378439e4e 100644 --- a/core/consensus/grandpa/structs.hpp +++ b/core/consensus/grandpa/structs.hpp @@ -59,14 +59,14 @@ namespace kagome::consensus::grandpa { } }; - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &s, const SignedMessage &signed_msg) { return s << signed_msg.message << signed_msg.signature << signed_msg.id; } - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &s, SignedMessage &signed_msg) { return s >> signed_msg.message >> signed_msg.signature >> signed_msg.id; } @@ -78,16 +78,16 @@ namespace kagome::consensus::grandpa { using SignedMessage::SignedMessage; }; - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &s, const SignedPrevote &signed_msg) { assert(signed_msg.template is()); return s << boost::strict_get(signed_msg.message) << signed_msg.signature << signed_msg.id; } - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &s, SignedPrevote &signed_msg) { signed_msg.message = Prevote{}; return s >> boost::strict_get(signed_msg.message) @@ -98,16 +98,16 @@ namespace kagome::consensus::grandpa { using SignedMessage::SignedMessage; }; - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &s, const SignedPrecommit &signed_msg) { assert(signed_msg.template is()); return s << boost::strict_get(signed_msg.message) << signed_msg.signature << signed_msg.id; } - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &s, SignedPrecommit &signed_msg) { signed_msg.message = Precommit{}; return s >> boost::strict_get(signed_msg.message) diff --git a/core/consensus/grandpa/types/authority.hpp b/core/consensus/grandpa/types/authority.hpp index f8b83c387c..756043659c 100644 --- a/core/consensus/grandpa/types/authority.hpp +++ b/core/consensus/grandpa/types/authority.hpp @@ -36,7 +36,7 @@ namespace kagome::consensus::grandpa { AuthoritySet() = default; AuthoritySet(AuthoritySetId id, Authorities authorities) - : id{id}, authorities{authorities} {} + : id{id}, authorities{std::move(authorities)} {} AuthoritySetId id{}; Authorities authorities; diff --git a/core/consensus/grandpa/vote_graph/vote_graph_impl.cpp b/core/consensus/grandpa/vote_graph/vote_graph_impl.cpp index 457aafd1a6..36f0e4dfbb 100644 --- a/core/consensus/grandpa/vote_graph/vote_graph_impl.cpp +++ b/core/consensus/grandpa/vote_graph/vote_graph_impl.cpp @@ -153,12 +153,12 @@ namespace kagome::consensus::grandpa { // Find first (best) ancestor among those presented in the entries, // and take corresponding entry - auto ancestry_it = std::find_if(ancestry.begin() + 1, - ancestry.end(), - [this, &entry_it](auto &ancestor) { - return entry_it = entries_.find(ancestor), - entry_it != entries_.end(); - }); + auto ancestry_it = std::ranges::find_if( + ancestry.begin() + 1, + ancestry.end(), + [this, &entry_it](auto &ancestor) { + return entry_it = entries_.find(ancestor), entry_it != entries_.end(); + }); BOOST_ASSERT_MSG(ancestry_it != ancestry.end(), "at least one entry presents ancestor of appending block"); @@ -212,7 +212,9 @@ namespace kagome::consensus::grandpa { if (not filled) { // `[offset_size..end)` elements new_entry.ancestors = std::vector{ - entry.ancestors.begin() + offset_size, entry.ancestors.end()}; + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) + entry.ancestors.begin() + offset_size, + entry.ancestors.end()}; auto last_it = entry.ancestors.rbegin(); if (last_it != entry.ancestors.rend()) { @@ -225,7 +227,9 @@ namespace kagome::consensus::grandpa { // `[0..offset_size)` elements entry.ancestors = std::vector{ - entry.ancestors.begin(), entry.ancestors.begin() + offset_size}; + entry.ancestors.begin(), + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) + entry.ancestors.begin() + offset_size}; new_entry.descendants.push_back(descendant); @@ -286,7 +290,7 @@ namespace kagome::consensus::grandpa { /// entries to be processed std::stack> nodes; - nodes.push(active_node); + nodes.emplace(active_node); while (not nodes.empty()) { auto &node = nodes.top().get(); nodes.pop(); @@ -311,7 +315,7 @@ namespace kagome::consensus::grandpa { node_key = descendant_hash; active_node = descendant; - nodes.push(descendant); + nodes.emplace(descendant); } } @@ -402,7 +406,7 @@ namespace kagome::consensus::grandpa { hashes.push_back(*new_best); } - return Subchain{hashes, best_number}; + return Subchain{.hashes = hashes, .best_number = best_number}; } void VoteGraphImpl::adjustBase(const std::vector &ancestry_proof) { @@ -452,10 +456,10 @@ namespace kagome::consensus::grandpa { // Not enough weight, check the parent block. if (node.ancestors.empty()) { return std::nullopt; - } else { - block.hash = node.ancestors[0]; - block.number = node.number - 1; } + block.hash = node.ancestors[0]; + block.number = node.number - 1; + } else { const auto &children = nodes_opt.value(); diff --git a/core/consensus/grandpa/voter_set.hpp b/core/consensus/grandpa/voter_set.hpp index 443d389f59..0b2e3a020e 100644 --- a/core/consensus/grandpa/voter_set.hpp +++ b/core/consensus/grandpa/voter_set.hpp @@ -91,14 +91,14 @@ namespace kagome::consensus::grandpa { friend Stream &operator>>(Stream &s, VoterSet &voters); }; - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &s, const VoterSet &voters) { return s << voters.list_ << voters.id_; } - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &s, VoterSet &voters) { voters.list_.clear(); voters.map_.clear(); diff --git a/core/consensus/timeline/impl/block_appender_base.cpp b/core/consensus/timeline/impl/block_appender_base.cpp index 49d1a50b5d..525e557660 100644 --- a/core/consensus/timeline/impl/block_appender_base.cpp +++ b/core/consensus/timeline/impl/block_appender_base.cpp @@ -28,9 +28,9 @@ namespace kagome::consensus { babe_config_repo_{std::move(babe_config_repo)}, timings_(timings), grandpa_environment_{std::move(grandpa_environment)}, - slots_util_{std::move(slots_util)}, + slots_util_{slots_util}, hasher_{std::move(hasher)}, - consensus_selector_(std::move(consensus_selector)) { + consensus_selector_(consensus_selector) { BOOST_ASSERT(block_tree_ != nullptr); BOOST_ASSERT(babe_config_repo_ != nullptr); BOOST_ASSERT(grandpa_environment_ != nullptr); @@ -51,14 +51,14 @@ namespace kagome::consensus { block_info, opt_justification.value(), [logger{logger_}, block_info, callback{std::move(callback)}]( - outcome::result result) { + const outcome::result &result) { if (result.has_error()) { SL_ERROR(logger, "Error while applying justification of block {}: {}", block_info, result.error()); } - callback(std::move(result)); + callback(result); }); } else { callback(outcome::success()); @@ -80,7 +80,7 @@ namespace kagome::consensus { OUTCOME_TRY(slot_number, consensus->getSlot(header)); auto start_time = slots_util_.get()->slotStartTime(slot_number); auto slot_duration = timings_.slot_duration; - return outcome::success(SlotInfo{start_time, slot_duration}); + return SlotInfo{.start = start_time, .duration = slot_duration}; } } // namespace kagome::consensus diff --git a/core/consensus/timeline/impl/block_executor_impl.cpp b/core/consensus/timeline/impl/block_executor_impl.cpp index ff116613fb..eac6dc16af 100644 --- a/core/consensus/timeline/impl/block_executor_impl.cpp +++ b/core/consensus/timeline/impl/block_executor_impl.cpp @@ -24,11 +24,14 @@ namespace kagome::consensus { - metrics::HistogramTimer metric_block_execution_time{ - "kagome_block_verification_and_import_time", - "Time taken to verify and import blocks", - {0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}, - }; + namespace { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) + metrics::HistogramTimer metric_block_execution_time{ + "kagome_block_verification_and_import_time", + "Time taken to verify and import blocks", + {0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}, + }; + } // namespace BlockExecutorImpl::BlockExecutorImpl( application::AppStateManager &app_state_manager, @@ -121,7 +124,7 @@ namespace kagome::consensus { auto execute = [this, self{shared_from_this()}, block{std::move(block)}, - justification, + justification{justification}, callback{std::move(callback)}, block_info, start_time, @@ -230,14 +233,12 @@ namespace kagome::consensus { } } - BlockAppenderBase::SlotInfo slot_info; - if (auto res = self->appender_->getSlotInfo(block.header); - res.has_error()) { + auto res = self->appender_->getSlotInfo(block.header); + if (res.has_error()) { callback(res.as_failure()); return; - } else { - slot_info = res.value(); } + auto &slot_info = res.value(); auto &[slot_start, slot_duration] = slot_info; auto lag = std::chrono::system_clock::now() - slot_start; diff --git a/core/consensus/timeline/impl/block_header_appender_impl.cpp b/core/consensus/timeline/impl/block_header_appender_impl.cpp index 7e7418ab9b..92642975d2 100644 --- a/core/consensus/timeline/impl/block_header_appender_impl.cpp +++ b/core/consensus/timeline/impl/block_header_appender_impl.cpp @@ -23,7 +23,7 @@ namespace kagome::consensus { : block_tree_{std::move(block_tree)}, hasher_{std::move(hasher)}, appender_{std::move(appender)}, - timeline_{std::move(timeline)}, + timeline_{timeline}, logger_{log::createLogger("BlockHeaderAppender", "block_appender")} { BOOST_ASSERT(block_tree_ != nullptr); BOOST_ASSERT(hasher_ != nullptr); diff --git a/core/consensus/timeline/impl/consensus_selector_impl.cpp b/core/consensus/timeline/impl/consensus_selector_impl.cpp index 6e4d55c97c..d69375a36a 100644 --- a/core/consensus/timeline/impl/consensus_selector_impl.cpp +++ b/core/consensus/timeline/impl/consensus_selector_impl.cpp @@ -19,14 +19,12 @@ namespace kagome::consensus { finality_consensuses_(std::move(finality_consensuses)) { BOOST_ASSERT(header_repo_ != nullptr); BOOST_ASSERT(not production_consensuses_.empty()); - BOOST_ASSERT(std::all_of( - production_consensuses_.begin(), - production_consensuses_.end(), + BOOST_ASSERT(std::ranges::all_of( + production_consensuses_, [](const auto &consensus) { return consensus != nullptr; })); BOOST_ASSERT(not finality_consensuses_.empty()); - BOOST_ASSERT(std::all_of( - finality_consensuses_.begin(), - finality_consensuses_.end(), + BOOST_ASSERT(std::ranges::all_of( + finality_consensuses_, [](const auto &consensus) { return consensus != nullptr; })); } @@ -35,12 +33,11 @@ namespace kagome::consensus { const primitives::BlockInfo &parent_block) const { auto consensus_opt = pc_cache_.get(parent_block); if (consensus_opt.has_value()) { - return consensus_opt.value(); + return consensus_opt.value().get(); } [[unlikely]] if (parent_block.number == 0) { - for (size_t i = 0; i < production_consensuses_.size(); ++i) { - const auto &consensus = production_consensuses_[i]; + for (const auto &consensus : production_consensuses_) { if (consensus->isGenesisConsensus()) { return pc_cache_.put(parent_block, consensus); } @@ -49,7 +46,7 @@ namespace kagome::consensus { auto header_res = header_repo_->getBlockHeader(parent_block.hash); if (header_res.has_error()) { - // TODO Log it + BOOST_UNREACHABLE_RETURN(); return {}; } const auto &header = header_res.value(); @@ -75,12 +72,11 @@ namespace kagome::consensus { const primitives::BlockHeader &header) const { auto consensus_opt = pc_cache_.get(header.blockInfo()); if (consensus_opt.has_value()) { - return consensus_opt.value(); + return consensus_opt.value().get(); } [[unlikely]] if (header.number == 0) { - for (size_t i = 0; i < production_consensuses_.size(); ++i) { - const auto &consensus = production_consensuses_[i]; + for (const auto &consensus : production_consensuses_) { if (consensus->isGenesisConsensus()) { return consensus; } @@ -108,7 +104,7 @@ namespace kagome::consensus { const primitives::BlockInfo &parent_block) const { auto consensus_opt = fc_cache_.get(parent_block); if (consensus_opt.has_value()) { - return consensus_opt.value(); + return consensus_opt.value().get(); } for (size_t i = 0; i < finality_consensuses_.size(); ++i) { @@ -117,7 +113,7 @@ namespace kagome::consensus { return fc_cache_.put(parent_block, consensus); } - // TODO: Code for trying to select another consensus + // TODO(xDimon): Code for trying to select another consensus } BOOST_UNREACHABLE_RETURN({}); } @@ -127,7 +123,7 @@ namespace kagome::consensus { const primitives::BlockHeader &header) const { auto consensus_opt = fc_cache_.get(header.blockInfo()); if (consensus_opt.has_value()) { - return consensus_opt.value(); + return consensus_opt.value().get(); } for (size_t i = 0; i < finality_consensuses_.size(); ++i) { @@ -136,7 +132,7 @@ namespace kagome::consensus { return consensus; } - // TODO: Code for trying to select another consensus + // TODO(xDimon): Code for trying to select another consensus } BOOST_UNREACHABLE_RETURN({}); } diff --git a/core/consensus/timeline/impl/slots_util_impl.cpp b/core/consensus/timeline/impl/slots_util_impl.cpp index 116067a632..dab5904b28 100644 --- a/core/consensus/timeline/impl/slots_util_impl.cpp +++ b/core/consensus/timeline/impl/slots_util_impl.cpp @@ -115,7 +115,6 @@ namespace kagome ::consensus { // Trying to get slot from consensus (internally it happens by runtime call) if (not slot1.has_value()) { auto consensus = consensus_selector_->getProductionConsensus(parent_info); - // TODO consensus->getTheFirstSlot(); if (trie_storage_->getEphemeralBatchAt(parent.state_root)) { if (auto epoch_res = babe_api_->next_epoch(parent_info.hash); epoch_res.has_value()) { diff --git a/core/consensus/timeline/impl/timeline_impl.cpp b/core/consensus/timeline/impl/timeline_impl.cpp index a2f2f1d150..b9a2abbb82 100644 --- a/core/consensus/timeline/impl/timeline_impl.cpp +++ b/core/consensus/timeline/impl/timeline_impl.cpp @@ -69,7 +69,7 @@ namespace kagome::consensus { hasher_(std::move(hasher)), block_announce_transmitter_(std::move(block_announce_transmitter)), warp_sync_(std::move(warp_sync)), - warp_protocol_(std::move(warp_protocol)), + warp_protocol_(warp_protocol), justification_observer_(std::move(justification_observer)), scheduler_(std::move(scheduler)), chain_sub_engine_(std::move(chain_sub_engine)), diff --git a/core/consensus/timeline/impl/timeline_impl.hpp b/core/consensus/timeline/impl/timeline_impl.hpp index e7421d9d09..8e24eaf83d 100644 --- a/core/consensus/timeline/impl/timeline_impl.hpp +++ b/core/consensus/timeline/impl/timeline_impl.hpp @@ -172,7 +172,7 @@ namespace kagome::consensus { SyncState current_state_{SyncState::WAIT_REMOTE_STATUS}; bool was_synchronized_{false}; - EpochNumber current_epoch_; + EpochNumber current_epoch_{}; SlotNumber current_slot_{}; primitives::BlockInfo best_block_{}; diff --git a/core/consensus/timeline/sync_state.hpp b/core/consensus/timeline/sync_state.hpp index 294f5ecdc5..76f45751fc 100644 --- a/core/consensus/timeline/sync_state.hpp +++ b/core/consensus/timeline/sync_state.hpp @@ -6,9 +6,11 @@ #pragma once +#include + namespace kagome::consensus { - enum class SyncState { + enum class SyncState : uint8_t { /// Node is just launched and waits status of remote peer to sync missing /// blocks WAIT_REMOTE_STATUS, diff --git a/core/consensus/timeline/types.hpp b/core/consensus/timeline/types.hpp index a38758dc58..616b1fadb7 100644 --- a/core/consensus/timeline/types.hpp +++ b/core/consensus/timeline/types.hpp @@ -69,7 +69,7 @@ namespace kagome::consensus { friend ::scale::ScaleDecoderStream &operator>>( ::scale::ScaleDecoderStream &s, SlotDuration &duration) { - uint64_t v; + uint64_t v; // NOLINT(cppcoreguidelines-init-variables) s >> v; duration = {v}; return s; diff --git a/core/crypto/bandersnatch/bandersnatch_provider_impl.cpp b/core/crypto/bandersnatch/bandersnatch_provider_impl.cpp index f68db1166c..a4d491a9c2 100644 --- a/core/crypto/bandersnatch/bandersnatch_provider_impl.cpp +++ b/core/crypto/bandersnatch/bandersnatch_provider_impl.cpp @@ -55,12 +55,13 @@ namespace kagome::crypto { } BandersnatchKeypair keypair{ - BandersnatchSecretKey::from(SecureCleanGuard{ + .secret_key = BandersnatchSecretKey::from(SecureCleanGuard{ std::span(kp).subspan<0, constants::bandersnatch::SECRET_SIZE>()}), - BandersnatchPublicKey::fromSpan( - std::span(kp).subspan(constants::bandersnatch::SECRET_SIZE, - constants::bandersnatch::PUBLIC_SIZE)) - .value()}; + .public_key = + BandersnatchPublicKey::fromSpan( + std::span(kp).subspan(constants::bandersnatch::SECRET_SIZE, + constants::bandersnatch::PUBLIC_SIZE)) + .value()}; return keypair; } diff --git a/core/crypto/bandersnatch/bandersnatch_provider_impl.hpp b/core/crypto/bandersnatch/bandersnatch_provider_impl.hpp index 4fbd78cb5d..e72e18851b 100644 --- a/core/crypto/bandersnatch/bandersnatch_provider_impl.hpp +++ b/core/crypto/bandersnatch/bandersnatch_provider_impl.hpp @@ -18,7 +18,7 @@ namespace kagome::crypto { /** * sr25519 provider error codes */ - enum class BandersnatchProviderError { + enum class BandersnatchProviderError : uint8_t { SIGN_UNKNOWN_ERROR = 1, // unknown error occured during call to `sign` // method of bound function VERIFY_UNKNOWN_ERROR, // unknown error occured during call to `verify` diff --git a/core/crypto/bandersnatch/vrf.cpp b/core/crypto/bandersnatch/vrf.cpp index b1a2769c99..56882af3ee 100644 --- a/core/crypto/bandersnatch/vrf.cpp +++ b/core/crypto/bandersnatch/vrf.cpp @@ -11,7 +11,7 @@ namespace kagome::crypto::bandersnatch::vrf { VrfInput vrf_input(BytesIn domain, BytesIn data) { auto vrf_input = ::bandersnatch_vrf_input( domain.data(), domain.size(), data.data(), data.size()); - return VrfInput(vrf_input); + return vrf_input; } VrfInput vrf_input_from_data(BytesIn domain, std::span data) { @@ -86,7 +86,7 @@ namespace kagome::crypto::bandersnatch::vrf { data.size(), input_ptrs.data(), input_ptrs.size()); - return VrfSignData(res); + return res; } template <> diff --git a/core/crypto/bandersnatch/vrf.hpp b/core/crypto/bandersnatch/vrf.hpp index 8f66b734ed..12dffdc162 100644 --- a/core/crypto/bandersnatch/vrf.hpp +++ b/core/crypto/bandersnatch/vrf.hpp @@ -105,10 +105,9 @@ namespace kagome::crypto::bandersnatch::vrf { RingProver prover(std::span keys, size_t index) const { std::vector ptrs; - std::transform(keys.begin(), - keys.end(), - std::back_inserter(ptrs), - [](const auto &key) { return key.data(); }); + std::ranges::transform(keys, + std::back_inserter(ptrs), + [](const auto &key) { return key.data(); }); auto prover = ::bandersnatch_ring_prover(ptr_, ptrs.data(), ptrs.size(), index); return RingProver(prover); @@ -117,10 +116,9 @@ namespace kagome::crypto::bandersnatch::vrf { RingVerifier verifier(std::span keys, size_t index) const { std::vector ptrs; - std::transform(keys.begin(), - keys.end(), - std::back_inserter(ptrs), - [](const auto &key) { return key.data(); }); + std::ranges::transform(keys, + std::back_inserter(ptrs), + [](const auto &key) { return key.data(); }); auto verifier = ::bandersnatch_ring_verifier(ptr_, ptrs.data(), ptrs.size()); return RingVerifier(verifier); diff --git a/core/crypto/bandersnatch_types.hpp b/core/crypto/bandersnatch_types.hpp index 62db2249d7..f0764df385 100644 --- a/core/crypto/bandersnatch_types.hpp +++ b/core/crypto/bandersnatch_types.hpp @@ -17,25 +17,23 @@ #include "primitives/math.hpp" #include "scale/tie.hpp" -namespace kagome::crypto { - namespace constants::bandersnatch { - /// Important constants to deal with bandersnatch - enum { - SEED_SIZE = BANDERSNATCH_SEED_SIZE, - SECRET_SIZE = BANDERSNATCH_SECRET_KEY_SIZE, - PUBLIC_SIZE = BANDERSNATCH_PUBLIC_KEY_SIZE, - KEYPAIR_SIZE = SECRET_SIZE + PUBLIC_SIZE, - SIGNATURE_SIZE = BANDERSNATCH_SIGNATURE_SIZE, - RING_SIGNATURE_SIZE = BANDERSNATCH_RING_SIGNATURE_SIZE, - }; +namespace kagome::crypto::constants::bandersnatch { + /// Important constants to deal with bandersnatch + enum { // NOLINT(performance-enum-size) + SEED_SIZE = BANDERSNATCH_SEED_SIZE, + SECRET_SIZE = BANDERSNATCH_SECRET_KEY_SIZE, + PUBLIC_SIZE = BANDERSNATCH_PUBLIC_KEY_SIZE, + KEYPAIR_SIZE = SECRET_SIZE + PUBLIC_SIZE, + SIGNATURE_SIZE = BANDERSNATCH_SIGNATURE_SIZE, + RING_SIGNATURE_SIZE = BANDERSNATCH_RING_SIGNATURE_SIZE, + }; - namespace vrf { - enum { - OUTPUT_SIZE = BANDERSNATCH_PREOUT_SIZE, - }; - } - } // namespace constants::bandersnatch -} // namespace kagome::crypto + namespace vrf { + enum { // NOLINT(performance-enum-size) + OUTPUT_SIZE = BANDERSNATCH_PREOUT_SIZE, + }; + } +} // namespace kagome::crypto::constants::bandersnatch KAGOME_BLOB_STRICT_TYPEDEF(kagome::crypto, BandersnatchPublicKey, diff --git a/core/crypto/bip39/bip39_types.hpp b/core/crypto/bip39/bip39_types.hpp index a80004a1d7..6e56474679 100644 --- a/core/crypto/bip39/bip39_types.hpp +++ b/core/crypto/bip39/bip39_types.hpp @@ -22,7 +22,7 @@ namespace kagome::crypto::bip39 { using Bip39Seed = PrivateKey; struct RawJunction { - bool hard; + bool hard = false; common::Hash256 cc; }; diff --git a/core/crypto/bip39/dictionary.cpp b/core/crypto/bip39/dictionary.cpp index 6f2a08dc31..d4cc0da091 100644 --- a/core/crypto/bip39/dictionary.cpp +++ b/core/crypto/bip39/dictionary.cpp @@ -12,10 +12,9 @@ namespace kagome::crypto::bip39 { void Dictionary::initialize() { - for (size_t i = 0; i < english::dictionary.size(); ++i) { - auto token = EntropyToken(i); - std::string_view word = english::dictionary[i]; - entropy_map_[word] = token; + size_t i = 0; + for (const auto &word : english::dictionary) { + entropy_map_[word] = EntropyToken(i++); } } diff --git a/core/crypto/bip39/dictionary.hpp b/core/crypto/bip39/dictionary.hpp index c786209685..f7b6f16917 100644 --- a/core/crypto/bip39/dictionary.hpp +++ b/core/crypto/bip39/dictionary.hpp @@ -13,7 +13,7 @@ namespace kagome::crypto::bip39 { - enum class DictionaryError { + enum class DictionaryError : uint8_t { ENTRY_NOT_FOUND = 1, }; diff --git a/core/crypto/bip39/entropy_accumulator.hpp b/core/crypto/bip39/entropy_accumulator.hpp index 854f9f39c6..2db87f96fc 100644 --- a/core/crypto/bip39/entropy_accumulator.hpp +++ b/core/crypto/bip39/entropy_accumulator.hpp @@ -14,7 +14,7 @@ namespace kagome::crypto::bip39 { - enum class Bip39EntropyError { + enum class Bip39EntropyError : uint8_t { WRONG_WORDS_COUNT = 1, STORAGE_NOT_COMPLETE, STORAGE_IS_FULL, @@ -68,8 +68,10 @@ namespace kagome::crypto::bip39 { EntropyAccumulator(size_t bits_count, size_t checksum_bits_count); std::vector bits_; + // NOLINTBEGIN(cppcoreguidelines-avoid-const-or-ref-data-members) const size_t total_bits_count_; const size_t checksum_bits_count_; + // NOLINTEND(cppcoreguidelines-avoid-const-or-ref-data-members) }; } // namespace kagome::crypto::bip39 diff --git a/core/crypto/bip39/impl/bip39_provider_impl.cpp b/core/crypto/bip39/impl/bip39_provider_impl.cpp index b0aac58ce1..f9e6d277da 100644 --- a/core/crypto/bip39/impl/bip39_provider_impl.cpp +++ b/core/crypto/bip39/impl/bip39_provider_impl.cpp @@ -88,9 +88,8 @@ namespace kagome::crypto { } OUTCOME_TRY(entropy, calculateEntropy(*words)); return makeSeed(entropy, mnemonic.password); - } else { - return std::get(std::move(mnemonic.seed)); } + return std::get(std::move(mnemonic.seed)); }(); OUTCOME_TRY(seed, seed_res); bip39::Bip39SeedAndJunctions result{ diff --git a/core/crypto/bip39/mnemonic.cpp b/core/crypto/bip39/mnemonic.cpp index e95650c06a..8291949366 100644 --- a/core/crypto/bip39/mnemonic.cpp +++ b/core/crypto/bip39/mnemonic.cpp @@ -43,9 +43,12 @@ namespace kagome::crypto::bip39 { if (raw.size() > result.size()) { result = hasher.blake2b_256(raw); } else { - std::copy(raw.begin(), raw.end(), result.begin()); + std::ranges::copy(raw, result.begin()); } - return RawJunction{hard, result}; + return RawJunction{ + .hard = hard, + .cc = result, + }; } outcome::result Mnemonic::parse(std::string_view phrase) { @@ -82,12 +85,18 @@ namespace kagome::crypto::bip39 { } auto index = path.substr(0, slash_pos); auto end = index.data() + index.size(); - uint64_t num; + uint64_t num; // NOLINT(cppcoreguidelines-init-variables) auto parse = std::from_chars(index.data(), end, num); if (parse.ec == std::errc{} and parse.ptr == end) { - mnemonic.junctions.emplace_back(Junction{hard, num}); + mnemonic.junctions.emplace_back(Junction{ + .hard = hard, + .index = num, + }); } else { - mnemonic.junctions.emplace_back(Junction{hard, std::string{index}}); + mnemonic.junctions.emplace_back(Junction{ + .hard = hard, + .index = std::string{index}, + }); } path.remove_prefix(slash_pos); } diff --git a/core/crypto/bip39/mnemonic.hpp b/core/crypto/bip39/mnemonic.hpp index 9bd409093f..345a593125 100644 --- a/core/crypto/bip39/mnemonic.hpp +++ b/core/crypto/bip39/mnemonic.hpp @@ -15,7 +15,7 @@ namespace kagome::crypto { } // namespace kagome::crypto namespace kagome::crypto::bip39 { - enum class MnemonicError { + enum class MnemonicError : uint8_t { INVALID_MNEMONIC = 1, INVALID_SEED_LENGTH, }; diff --git a/core/crypto/common.hpp b/core/crypto/common.hpp index 2bdcebe638..c97fe4da33 100644 --- a/core/crypto/common.hpp +++ b/core/crypto/common.hpp @@ -61,6 +61,7 @@ namespace kagome::crypto { template SecureCleanGuard(common::Blob &&) -> SecureCleanGuard; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) inline std::once_flag secure_heap_init_flag{}; // TODO(turuslan): #2129 secure allocator @@ -88,7 +89,7 @@ namespace kagome::crypto { if (p == nullptr) { throw std::bad_alloc{}; } - + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) return reinterpret_cast(p); } @@ -115,6 +116,7 @@ namespace kagome::crypto { public: PrivateKey() : data(Size, 0) {} + ~PrivateKey() = default; PrivateKey(const PrivateKey &) = default; PrivateKey &operator=(const PrivateKey &) = default; @@ -147,7 +149,8 @@ namespace kagome::crypto { template requires(OtherSize >= Size) - static PrivateKey from(PrivateKey &&other_key) { + static PrivateKey from( + std::add_rvalue_reference> other_key) { return PrivateKey{std::move(other_key.data)}; } @@ -191,9 +194,12 @@ namespace kagome::crypto { } static outcome::result fromHex(const SecureBuffer<> &hex) { - OUTCOME_TRY(bytes, - common::unhex(std::string_view{ - reinterpret_cast(hex.data()), hex.size()})); + OUTCOME_TRY( + bytes, + common::unhex(std::string_view{ + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + reinterpret_cast(hex.data()), + hex.size()})); return PrivateKey::from(SecureCleanGuard{bytes}); } @@ -214,7 +220,7 @@ namespace kagome::crypto { template requires(OtherSize >= Size) - explicit PrivateKey(SecureBuffer data) + explicit PrivateKey(const SecureBuffer &data) : PrivateKey{data.view().template subspan<0, Size>()} { BOOST_ASSERT(this->data.size() == Size); } diff --git a/core/crypto/ecdsa/ecdsa_provider_impl.cpp b/core/crypto/ecdsa/ecdsa_provider_impl.cpp index 24131d139e..f51dbfa9e2 100644 --- a/core/crypto/ecdsa/ecdsa_provider_impl.cpp +++ b/core/crypto/ecdsa/ecdsa_provider_impl.cpp @@ -47,7 +47,7 @@ namespace kagome::crypto { SecureCleanGuard g{bytes}; auto _ = hasher_->blake2b_256(bytes); seed = EcdsaSeed::from( - SecureCleanGuard(static_cast>(_))); + SecureCleanGuard(static_cast &>(_))); } EcdsaKeypair keys{ .secret_key = EcdsaPrivateKey::from(seed), diff --git a/core/crypto/ecdsa/ecdsa_provider_impl.hpp b/core/crypto/ecdsa/ecdsa_provider_impl.hpp index 6f2e357c04..60a4eb2f4d 100644 --- a/core/crypto/ecdsa/ecdsa_provider_impl.hpp +++ b/core/crypto/ecdsa/ecdsa_provider_impl.hpp @@ -18,7 +18,7 @@ namespace kagome::crypto { class EcdsaProviderImpl : public EcdsaProvider { public: - enum class Error { + enum class Error : uint8_t { VERIFICATION_FAILED = 1, SIGN_FAILED, DERIVE_FAILED, diff --git a/core/crypto/ecdsa_types.hpp b/core/crypto/ecdsa_types.hpp index 3ccc66c05d..64a688e421 100644 --- a/core/crypto/ecdsa_types.hpp +++ b/core/crypto/ecdsa_types.hpp @@ -9,16 +9,14 @@ #include "crypto/common.hpp" #include "crypto/secp256k1_types.hpp" -namespace kagome::crypto { - namespace constants::ecdsa { - enum { - PRIVKEY_SIZE = 32, - PUBKEY_SIZE = secp256k1::constants::kCompressedPublicKeySize, - SIGNATURE_SIZE = secp256k1::constants::kCompactSignatureSize, - SEED_SIZE = PRIVKEY_SIZE, - }; - } -} // namespace kagome::crypto +namespace kagome::crypto::constants::ecdsa { + enum { // NOLINT(performance-enum-size) + PRIVKEY_SIZE = 32, + PUBKEY_SIZE = secp256k1::constants::kCompressedPublicKeySize, + SIGNATURE_SIZE = secp256k1::constants::kCompactSignatureSize, + SEED_SIZE = PRIVKEY_SIZE, + }; +} KAGOME_BLOB_STRICT_TYPEDEF(kagome::crypto, EcdsaPublicKey, diff --git a/core/crypto/ed25519/ed25519_provider_impl.cpp b/core/crypto/ed25519/ed25519_provider_impl.cpp index 02d66268bb..10de613092 100644 --- a/core/crypto/ed25519/ed25519_provider_impl.cpp +++ b/core/crypto/ed25519/ed25519_provider_impl.cpp @@ -47,24 +47,25 @@ namespace kagome::crypto { std::array kp_bytes{}; ed25519_keypair_from_seed(kp_bytes.data(), seed.unsafeBytes().data()); Ed25519Keypair kp{ - Ed25519PrivateKey::from(SecureCleanGuard{ + .secret_key = Ed25519PrivateKey::from(SecureCleanGuard{ std::span(kp_bytes).subspan<0, ED25519_SECRET_KEY_LENGTH>()}), - Ed25519PublicKey::fromSpan(std::span(kp_bytes) - .subspan()) - .value()}; + .public_key = Ed25519PublicKey::fromSpan( + std::span(kp_bytes) + .subspan()) + .value()}; return kp; } outcome::result Ed25519ProviderImpl::sign( const Ed25519Keypair &keypair, common::BufferView message) const { Ed25519Signature sig; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init,hicpp-member-init) std::array keypair_bytes; SecureCleanGuard g{keypair_bytes}; std::ranges::copy(keypair.secret_key.unsafeBytes(), keypair_bytes.begin()); - std::copy(keypair.public_key.begin(), - keypair.public_key.end(), - keypair_bytes.begin() + ED25519_SECRET_KEY_LENGTH); + std::ranges::copy(keypair.public_key, + keypair_bytes.begin() + ED25519_SECRET_KEY_LENGTH); auto res = ed25519_sign( sig.data(), keypair_bytes.data(), message.data(), message.size_bytes()); if (res != ED25519_RESULT_OK) { diff --git a/core/crypto/ed25519/ed25519_provider_impl.hpp b/core/crypto/ed25519/ed25519_provider_impl.hpp index 01f029a6e2..dd7cab858b 100644 --- a/core/crypto/ed25519/ed25519_provider_impl.hpp +++ b/core/crypto/ed25519/ed25519_provider_impl.hpp @@ -15,7 +15,7 @@ namespace kagome::crypto { class Ed25519ProviderImpl : public Ed25519Provider { public: - enum class Error { + enum class Error : uint8_t { VERIFICATION_FAILED = 1, SIGN_FAILED, SOFT_JUNCTION_NOT_SUPPORTED, diff --git a/core/crypto/ed25519_types.hpp b/core/crypto/ed25519_types.hpp index 8052c60ddf..bb4728f2dd 100644 --- a/core/crypto/ed25519_types.hpp +++ b/core/crypto/ed25519_types.hpp @@ -14,21 +14,17 @@ extern "C" { #include "crypto/common.hpp" #include "scale/tie.hpp" -namespace kagome::crypto { - - namespace constants::ed25519 { - /** - * Important constants to deal with ed25519 - */ - enum { - PRIVKEY_SIZE = ED25519_SECRET_KEY_LENGTH, - PUBKEY_SIZE = ED25519_PUBLIC_KEY_LENGTH, - SIGNATURE_SIZE = ED25519_SIGNATURE_LENGTH, - SEED_SIZE = PRIVKEY_SIZE, - }; - } // namespace constants::ed25519 - -} // namespace kagome::crypto +namespace kagome::crypto::constants::ed25519 { + /** + * Important constants to deal with ed25519 + */ + enum { // NOLINT(performance-enum-size) + PRIVKEY_SIZE = ED25519_SECRET_KEY_LENGTH, + PUBKEY_SIZE = ED25519_PUBLIC_KEY_LENGTH, + SIGNATURE_SIZE = ED25519_SIGNATURE_LENGTH, + SEED_SIZE = PRIVKEY_SIZE, + }; +} // namespace kagome::crypto::constants::ed25519 KAGOME_BLOB_STRICT_TYPEDEF(kagome::crypto, Ed25519PublicKey, diff --git a/core/crypto/elliptic_curves/elliptic_curves_impl.cpp b/core/crypto/elliptic_curves/elliptic_curves_impl.cpp index 34e4881ffe..4fd49dcd42 100644 --- a/core/crypto/elliptic_curves/elliptic_curves_impl.cpp +++ b/core/crypto/elliptic_curves/elliptic_curves_impl.cpp @@ -24,12 +24,15 @@ namespace kagome::crypto { namespace { ::BytesVec convert(common::BufferView view) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return {.data = const_cast(view.data()), .size = view.size()}; } outcome::result convert(::Result res) { if (res.tag == ::RESULT_OK) { - // TODO avoid coping to runtime + // TODO(xDimon): avoid coping to runtime + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access,cppcoreguidelines-pro-bounds-pointer-arithmetic) common::Buffer buf(res.ok.data, res.ok.data + res.ok.size); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) ::AWCR_deallocate_bytesvec(&res.ok); return buf; } diff --git a/core/crypto/hasher/blake2b_stream_hasher.hpp b/core/crypto/hasher/blake2b_stream_hasher.hpp index 3e7e49af04..9b5ce9100d 100644 --- a/core/crypto/hasher/blake2b_stream_hasher.hpp +++ b/core/crypto/hasher/blake2b_stream_hasher.hpp @@ -17,9 +17,8 @@ namespace kagome::crypto { static constexpr size_t kOutlen = Outlen; static_assert((Outlen & (Outlen - 1)) == 0, "Outlen is pow 2"); - Blake2b_StreamHasher() { - initialized_ = (0 == blake2b_init(&ctx_, Outlen, nullptr, 0ull)); - } + Blake2b_StreamHasher() + : initialized_(blake2b_init(&ctx_, Outlen, nullptr, 0ull) == 0) {} bool update(std::span buffer) { if (!initialized_) { @@ -38,7 +37,7 @@ namespace kagome::crypto { } private: - blake2b_ctx ctx_; + blake2b_ctx ctx_{}; bool initialized_{false}; }; } // namespace kagome::crypto diff --git a/core/crypto/key_store.hpp b/core/crypto/key_store.hpp index d24fc68b99..24ca3b1ddc 100644 --- a/core/crypto/key_store.hpp +++ b/core/crypto/key_store.hpp @@ -30,7 +30,7 @@ namespace kagome::crypto { - enum class KeyStoreError { + enum class KeyStoreError : uint8_t { UNSUPPORTED_KEY_TYPE = 1, UNSUPPORTED_CRYPTO_TYPE, WRONG_SEED_SIZE, diff --git a/core/crypto/key_store/key_file_storage.cpp b/core/crypto/key_store/key_file_storage.cpp index 996cfad008..36d33f0cb6 100644 --- a/core/crypto/key_store/key_file_storage.cpp +++ b/core/crypto/key_store/key_file_storage.cpp @@ -39,7 +39,8 @@ namespace kagome::crypto { outcome::result> KeyFileStorage::createAt( Path keystore_path) { - std::unique_ptr kfs{new KeyFileStorage(keystore_path)}; + std::unique_ptr kfs{ + new KeyFileStorage(std::move(keystore_path))}; OUTCOME_TRY(kfs->initialize()); return kfs; } diff --git a/core/crypto/key_store/key_file_storage.hpp b/core/crypto/key_store/key_file_storage.hpp index a159de1684..3c66d4018d 100644 --- a/core/crypto/key_store/key_file_storage.hpp +++ b/core/crypto/key_store/key_file_storage.hpp @@ -23,7 +23,7 @@ namespace kagome::crypto { */ class KeyFileStorage { public: - enum class Error { + enum class Error : uint8_t { WRONG_KEYFILE_NAME = 1, NOT_REGULAR_FILE, FAILED_OPEN_FILE, diff --git a/core/crypto/key_store/key_store_impl.cpp b/core/crypto/key_store/key_store_impl.cpp index cbd1bd02ee..a9427c7eff 100644 --- a/core/crypto/key_store/key_store_impl.cpp +++ b/core/crypto/key_store/key_store_impl.cpp @@ -47,12 +47,12 @@ namespace kagome::crypto { const auto &secret_key = kp.secret_key; const auto &public_key = kp.public_key; libp2p::crypto::PublicKey lp2p_public{ - {libp2p::crypto::Key::Type::Ed25519, - std::vector{public_key.cbegin(), public_key.cend()}}}; + {.type = libp2p::crypto::Key::Type::Ed25519, + .data = std::vector{public_key.cbegin(), public_key.cend()}}}; libp2p::crypto::PrivateKey lp2p_private{ - {libp2p::crypto::Key::Type::Ed25519, - std::vector{secret_key.unsafeBytes().begin(), - secret_key.unsafeBytes().end()}}}; + {.type = libp2p::crypto::Key::Type::Ed25519, + .data = std::vector{secret_key.unsafeBytes().begin(), + secret_key.unsafeBytes().end()}}}; return libp2p::crypto::KeyPair{ .publicKey = lp2p_public, .privateKey = lp2p_private, diff --git a/core/crypto/key_store/key_type.hpp b/core/crypto/key_store/key_type.hpp index a583c773b7..efb3b1350f 100644 --- a/core/crypto/key_store/key_type.hpp +++ b/core/crypto/key_store/key_type.hpp @@ -12,7 +12,7 @@ namespace kagome::crypto { - enum class KeyTypeError { + enum class KeyTypeError : uint8_t { UNSUPPORTED_KEY_TYPE = 1, }; diff --git a/core/crypto/key_store/session_keys.cpp b/core/crypto/key_store/session_keys.cpp index 971ad7c008..09daabc701 100644 --- a/core/crypto/key_store/session_keys.cpp +++ b/core/crypto/key_store/session_keys.cpp @@ -18,6 +18,7 @@ namespace kagome::crypto { const KeySuiteStore &store, const std::vector &authorities, const Eq &eq) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) if (not roles_.flags.authority) { return std::nullopt; } @@ -26,7 +27,7 @@ namespace kagome::crypto { && eq(cache->first->public_key, authorities[cache->second])) { return cache; } - auto it = std::find_if( + auto it = std::ranges::find_if( authorities.begin(), authorities.end(), [&](const A &authority) { return eq(cache->first->public_key, authority); }); @@ -41,7 +42,7 @@ namespace kagome::crypto { } auto &keys = keys_res.value(); for (auto &pubkey : keys) { - auto it = std::find_if( + auto it = std::ranges::find_if( authorities.begin(), authorities.end(), [&](const A &authority) { return eq(pubkey, authority); }); diff --git a/core/crypto/key_store/session_keys.hpp b/core/crypto/key_store/session_keys.hpp index db561c7748..0e2d6d2249 100644 --- a/core/crypto/key_store/session_keys.hpp +++ b/core/crypto/key_store/session_keys.hpp @@ -31,7 +31,7 @@ namespace kagome::crypto { // otherwise it could be read from chainspec palletSession/keys // nevertheless they are hardcoded in polkadot // https://github.com/paritytech/polkadot/blob/634520cd3cf4b2b850db807daaaa32e480099981/node/service/src/chain_spec.rs#L230 - constexpr KeyType polkadot_key_order[6] = { + constexpr std::array polkadot_key_order{ KeyTypes::GRANDPA, KeyTypes::BABE, KeyTypes::IM_ONLINE, diff --git a/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp b/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp index 3139e34296..b4e3bd5326 100644 --- a/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp +++ b/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp @@ -18,6 +18,7 @@ namespace kagome::crypto { SecureBuffer<> out(key_length, 0); const auto *digest = EVP_sha512(); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) int res = PKCS5_PBKDF2_HMAC(reinterpret_cast(data.data()), data.size(), salt.data(), diff --git a/core/crypto/pbkdf2/pbkdf2_provider.hpp b/core/crypto/pbkdf2/pbkdf2_provider.hpp index 51a6e60ad9..a1bc81e7e7 100644 --- a/core/crypto/pbkdf2/pbkdf2_provider.hpp +++ b/core/crypto/pbkdf2/pbkdf2_provider.hpp @@ -15,7 +15,7 @@ namespace kagome::crypto { - enum class Pbkdf2ProviderError { KEY_DERIVATION_FAILED = 1 }; + enum class Pbkdf2ProviderError : uint8_t { KEY_DERIVATION_FAILED = 1 }; /** * @class Pbkdf2Provider provides key derivation functionality diff --git a/core/crypto/secp256k1/secp256k1_provider_impl.hpp b/core/crypto/secp256k1/secp256k1_provider_impl.hpp index 572e563a2e..051cc30ab1 100644 --- a/core/crypto/secp256k1/secp256k1_provider_impl.hpp +++ b/core/crypto/secp256k1/secp256k1_provider_impl.hpp @@ -12,7 +12,7 @@ namespace kagome::crypto { - enum class Secp256k1ProviderError { + enum class Secp256k1ProviderError : uint8_t { INVALID_ARGUMENT = 1, INVALID_V_VALUE, INVALID_R_OR_S_VALUE, diff --git a/core/crypto/sr25519/sr25519_provider_impl.cpp b/core/crypto/sr25519/sr25519_provider_impl.cpp index 64137b9fce..073ad516a9 100644 --- a/core/crypto/sr25519/sr25519_provider_impl.cpp +++ b/core/crypto/sr25519/sr25519_provider_impl.cpp @@ -22,12 +22,13 @@ namespace kagome::crypto { } Sr25519Keypair keypair{ - Sr25519SecretKey::from(SecureCleanGuard{ + .secret_key = Sr25519SecretKey::from(SecureCleanGuard{ std::span(kp).subspan<0, constants::sr25519::SECRET_SIZE>()}), - Sr25519PublicKey::fromSpan( - std::span(kp).subspan(constants::sr25519::SECRET_SIZE, - constants::sr25519::PUBLIC_SIZE)) - .value()}; + .public_key = + Sr25519PublicKey::fromSpan( + std::span(kp).subspan(constants::sr25519::SECRET_SIZE, + constants::sr25519::PUBLIC_SIZE)) + .value()}; return keypair; } diff --git a/core/crypto/sr25519_provider.hpp b/core/crypto/sr25519_provider.hpp index 26f98b2353..ce6f7606f0 100644 --- a/core/crypto/sr25519_provider.hpp +++ b/core/crypto/sr25519_provider.hpp @@ -14,7 +14,7 @@ namespace kagome::crypto { /** * sr25519 provider error codes */ - enum class Sr25519ProviderError { + enum class Sr25519ProviderError : uint8_t { SIGN_UNKNOWN_ERROR = 1, // unknown error occured during call to `sign` // method of bound function VERIFY_UNKNOWN_ERROR // unknown error occured during call to `verify` diff --git a/core/crypto/sr25519_types.hpp b/core/crypto/sr25519_types.hpp index 62ae57a57d..c65dc04b78 100644 --- a/core/crypto/sr25519_types.hpp +++ b/core/crypto/sr25519_types.hpp @@ -23,7 +23,7 @@ namespace kagome::crypto { /** * Important constants to deal with sr25519 */ - enum { + enum { // NOLINT(performance-enum-size) KEYPAIR_SIZE = SR25519_KEYPAIR_SIZE, SECRET_SIZE = SR25519_SECRET_SIZE, PUBLIC_SIZE = SR25519_PUBLIC_SIZE, @@ -35,7 +35,7 @@ namespace kagome::crypto { /** * Important constants to deal with vrf */ - enum { + enum { // NOLINT(performance-enum-size) PROOF_SIZE = SR25519_VRF_PROOF_SIZE, OUTPUT_SIZE = SR25519_VRF_OUTPUT_SIZE }; diff --git a/core/crypto/vrf/vrf_provider_impl.cpp b/core/crypto/vrf/vrf_provider_impl.cpp index db4e1ba2d5..e538d07c57 100644 --- a/core/crypto/vrf/vrf_provider_impl.cpp +++ b/core/crypto/vrf/vrf_provider_impl.cpp @@ -23,12 +23,13 @@ namespace kagome::crypto { sr25519_keypair_from_seed(kp.data(), seed.data()); Sr25519Keypair keypair{ - Sr25519SecretKey::from(SecureCleanGuard( + .secret_key = Sr25519SecretKey::from(SecureCleanGuard( std::span(kp).subspan<0, constants::sr25519::SECRET_SIZE>())), - Sr25519PublicKey::fromSpan( - std::span(kp.begin() + constants::sr25519::SECRET_SIZE, - constants::sr25519::PUBLIC_SIZE)) - .value()}; + .public_key = + Sr25519PublicKey::fromSpan( + std::span(kp.begin() + constants::sr25519::SECRET_SIZE, + constants::sr25519::PUBLIC_SIZE)) + .value()}; return keypair; } diff --git a/core/dispute_coordinator/impl/batch.cpp b/core/dispute_coordinator/impl/batch.cpp index 46ef7cb937..e1b7cdb75a 100644 --- a/core/dispute_coordinator/impl/batch.cpp +++ b/core/dispute_coordinator/impl/batch.cpp @@ -8,18 +8,18 @@ namespace kagome::dispute { - Batch::Batch(CandidateHash candidate_hash, - CandidateReceipt candidate_receipt, + Batch::Batch(const CandidateHash &candidate_hash, + const CandidateReceipt &candidate_receipt, TimePoint now) - : candidate_hash(std::move(candidate_hash)), - candidate_receipt(std::move(candidate_receipt)), + : candidate_hash(candidate_hash), + candidate_receipt(candidate_receipt), best_before_(now + kMaxBatchLifetime), log_(log::createLogger(fmt::format("Batch:{}", candidate_hash), "dispute")) {} std::optional> Batch::add_votes( - Indexed valid_vote, - Indexed invalid_vote, + const Indexed &valid_vote, + const Indexed &invalid_vote, const libp2p::peer::PeerId &peer, CbOutcome &&cb) { BOOST_ASSERT(valid_vote.payload.candidate_hash == candidate_hash); @@ -48,7 +48,7 @@ namespace kagome::dispute { return std::move(cb); } - requesters_.push_back(std::make_tuple(peer, std::move(cb))); + requesters_.emplace_back(peer, std::move(cb)); return std::nullopt; } diff --git a/core/dispute_coordinator/impl/batch.hpp b/core/dispute_coordinator/impl/batch.hpp index b8170270bc..62c2ecd1d7 100644 --- a/core/dispute_coordinator/impl/batch.hpp +++ b/core/dispute_coordinator/impl/batch.hpp @@ -50,8 +50,8 @@ namespace kagome::dispute { /// This ensures a timely import of batches. static constexpr uint32_t kMinKeepBatchAliveVotes = 10; - Batch(CandidateHash candidate_hash, - CandidateReceipt candidate_receipt, + Batch(const CandidateHash &candidate_hash, + const CandidateReceipt &candidate_receipt, TimePoint now); /// Add votes from a validator into the batch. @@ -65,8 +65,8 @@ namespace kagome::dispute { /// case both votes are known already, we return the response sender as an /// `Err` value. std::optional> add_votes( - Indexed valid_vote, - Indexed invalid_vote, + const Indexed &valid_vote, + const Indexed &invalid_vote, const libp2p::peer::PeerId &peer, CbOutcome &&cb); diff --git a/core/dispute_coordinator/impl/candidate_vote_state.cpp b/core/dispute_coordinator/impl/candidate_vote_state.cpp index ea57741536..13ce012aa4 100644 --- a/core/dispute_coordinator/impl/candidate_vote_state.cpp +++ b/core/dispute_coordinator/impl/candidate_vote_state.cpp @@ -57,7 +57,7 @@ namespace kagome::dispute { return not std::binary_search( disabled_validators.begin(), disabled_validators.end(), vote.first); }; - return std::find_if(votes.begin(), votes.end(), is_not_disabled) + return std::ranges::find_if(votes.begin(), votes.end(), is_not_disabled) != votes.end(); }; diff --git a/core/dispute_coordinator/impl/dispute_coordinator_impl.cpp b/core/dispute_coordinator/impl/dispute_coordinator_impl.cpp index 053ff7812f..3be9cb84a7 100644 --- a/core/dispute_coordinator/impl/dispute_coordinator_impl.cpp +++ b/core/dispute_coordinator/impl/dispute_coordinator_impl.cpp @@ -95,8 +95,7 @@ namespace kagome::dispute { /// Returns Error if the candidate_hash is not included in the /// list of signed candidate from /// ApprovalCheckingMultipleCandidate. - if (std::find( - candidates.begin(), candidates.end(), candidate_hash) + if (std::ranges::find(candidates, candidate_hash) == candidates.end()) { return ApprovalCheckingMultipleCandidatesError::NotIncluded; } @@ -110,9 +109,8 @@ namespace kagome::dispute { if (candidates.size() == 1) { return scale::encode( std::tie(magic, candidates.front(), session)); - } else { - return scale::encode(std::tie(magic, candidates, session)); } + return scale::encode(std::tie(magic, candidates, session)); }); }, [&](const InvalidDisputeStatement &kind) { @@ -173,7 +171,7 @@ namespace kagome::dispute { router_(std::move(router)), peer_view_(std::move(peer_view)), chain_sub_{std::move(chain_sub_engine)}, - timeline_(std::move(timeline)), + timeline_(timeline), main_pool_handler_{main_thread_pool.handler(*app_state_manager)}, dispute_thread_handler_{poolHandlerReadyMake( this, app_state_manager, dispute_thread_pool, log_)}, @@ -462,7 +460,8 @@ namespace kagome::dispute { for (auto &vote : votes) { auto res = process_on_chain_votes(vote); if (res.has_error()) { - SL_WARN(log_, "Skipping scraping block due to error: {}", res.error()); + SL_WARN( + log_, "Skipping scraping block (due to error): {}", res.error()); } } @@ -552,7 +551,7 @@ namespace kagome::dispute { } outcome::result DisputeCoordinatorImpl::process_on_chain_votes( - ScrapedOnChainVotes votes) { + const ScrapedOnChainVotes &votes) { const auto &session = votes.session; const auto &backing_validators_per_candidate = votes.backing_validators_per_candidate; @@ -830,7 +829,7 @@ namespace kagome::dispute { if (not res.has_error()) { auto sessions_updated = res.value(); - auto waiting = std::move(waiting_for_active_disputes_); + auto waiting = waiting_for_active_disputes_; waiting_for_active_disputes_.reset(); if (not waiting.has_value()) { // https://github.com/paritytech/polkadot/blob/40974fb99c86f5c341105b7db53c7aa0df707d66/node/network/dispute-distribution/src/sender/mod.rs#L196 @@ -879,12 +878,10 @@ namespace kagome::dispute { } /// Make active sessions correspond to currently active heads. - auto sessions_updated = - std::equal(active_sessions_.begin(), - active_sessions_.end(), - new_sessions.begin(), - new_sessions.end(), - [](auto it1, auto it2) { return it1.first == it2.first; }); + auto sessions_updated = std::ranges::equal( + active_sessions_, new_sessions, [](auto it1, auto it2) { + return it1.first == it2.first; + }); // Update in any case, so we use current heads for queries: // https://github.com/paritytech/polkadot/blob/40974fb99c86f5c341105b7db53c7aa0df707d66/node/network/dispute-distribution/src/sender/mod.rs#L304 @@ -903,7 +900,7 @@ namespace kagome::dispute { void DisputeCoordinatorImpl::handle_active_dispute_response( outcome::result active_disputes_res) { // https://github.com/paritytech/polkadot/blob/40974fb99c86f5c341105b7db53c7aa0df707d66/node/network/dispute-distribution/src/sender/mod.rs#L184 - auto state = std::move(waiting_for_active_disputes_); + auto state = waiting_for_active_disputes_; waiting_for_active_disputes_.reset(); auto have_new_sessions = state.has_value() and state->have_new_sessions; @@ -918,11 +915,9 @@ namespace kagome::dispute { /// Handle new active disputes response. // https://github.com/paritytech/polkadot/blob/40974fb99c86f5c341105b7db53c7aa0df707d66/node/network/dispute-distribution/src/sender/mod.rs#L261 std::unordered_set candidates; - std::for_each(active_disputes.begin(), - active_disputes.end(), - [&](const auto &active_dispute) { - candidates.emplace(std::get<1>(active_dispute)); - }); + std::ranges::for_each(active_disputes, [&](const auto &active_dispute) { + candidates.emplace(std::get<1>(active_dispute)); + }); // Cleanup obsolete senders sending_disputes_.remove_if([&](const auto &x) { @@ -1095,9 +1090,9 @@ namespace kagome::dispute { struct ImportResult { CandidateVoteState old_state; CandidateVoteState new_state; - size_t imported_invalid_votes; - size_t imported_valid_votes; - size_t imported_approval_votes; + size_t imported_invalid_votes{}; + size_t imported_valid_votes{}; + size_t imported_approval_votes{}; std::vector new_invalid_voters; }; @@ -1157,9 +1152,8 @@ namespace kagome::dispute { if (fresh) { if (imported_valid_votes == 0) { // Return postponed statements to process - std::move_backward(postponed_statements.begin(), - postponed_statements.end(), - statements.end()); + std::ranges::move_backward(postponed_statements, + statements.end()); } ++imported_valid_votes; } @@ -1172,9 +1166,8 @@ namespace kagome::dispute { new_invalid_voters.push_back(val_index); if (imported_invalid_votes == 0) { // Return postponed statements to process - std::move_backward(postponed_statements.begin(), - postponed_statements.end(), - statements.end()); + std::ranges::move_backward(postponed_statements, + statements.end()); } ++imported_invalid_votes; } @@ -1182,13 +1175,13 @@ namespace kagome::dispute { } ImportResult intermediate_result{ - std::move(old_state), - CandidateVoteState::create( + .old_state = std::move(old_state), + .new_state = CandidateVoteState::create( votes, env, disabled_validators, now), // new_state - imported_invalid_votes, - imported_valid_votes, - 0, - new_invalid_voters, + .imported_invalid_votes = imported_invalid_votes, + .imported_valid_votes = imported_valid_votes, + .imported_approval_votes = 0, + .new_invalid_voters = new_invalid_voters, }; // Handle approval vote import: @@ -1423,7 +1416,7 @@ namespace kagome::dispute { auto res = participation_->queue_participation(priority, request); if (res.has_error()) { - SL_ERROR(log_, "participation error: {}", res.error()); + SL_ERROR(log_, "Error of participation: {}", res.error()); } } else { @@ -1456,11 +1449,13 @@ namespace kagome::dispute { auto &pub_key = env.session.validators[validator_index]; SignedDisputeStatement statement{ - DisputeStatement{ValidDisputeStatement{ApprovalChecking{}}}, - candidate_hash, - pub_key, - sig, - session}; + .dispute_statement = + DisputeStatement{ValidDisputeStatement{ApprovalChecking{}}}, + .candidate_hash = candidate_hash, + .validator_public = pub_key, + .validator_signature = sig, + .session_index = session, + }; SL_TRACE( log_, @@ -1532,11 +1527,11 @@ namespace kagome::dispute { if (blocks_including.size() > 0) { std::vector to_revert; to_revert.reserve(blocks_including.size()); - std::transform(blocks_including.begin(), - blocks_including.end(), - std::back_inserter(to_revert), - [](auto &block_info) { return block_info.hash; }); - std::ignore = block_tree_->markAsRevertedBlocks(std::move(to_revert)); + std::ranges::transform( + blocks_including, + std::back_inserter(to_revert), + [](auto &block_info) { return block_info.hash; }); + std::ignore = block_tree_->markAsRevertedBlocks(to_revert); SL_DEBUG( log_, "Would be reverted up to {} blocks", blocks_including.size()); } else { @@ -1579,7 +1574,9 @@ namespace kagome::dispute { metric_disputes_total_->inc(); } + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) metric_votes_valid_->inc(import_result.imported_valid_votes); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) metric_votes_invalid_->inc(import_result.imported_invalid_votes); if (is_freshly_concluded_for) { @@ -1599,7 +1596,7 @@ namespace kagome::dispute { ValidatorIndex our_index) { auto &validators = session_info.validators; - ValidatorIndex other_index; + ValidatorIndex other_index; // NOLINT(cppcoreguidelines-init-variables) auto get_other_vote = [&](auto &some_kind_votes) -> outcome::result { @@ -1723,10 +1720,10 @@ namespace kagome::dispute { }; return network::DisputeMessage{ - candidate_receipt, - session_index, - invalid_vote, - valid_vote, + .candidate_receipt = candidate_receipt, + .session_index = session_index, + .invalid_vote = invalid_vote, + .valid_vote = valid_vote, }; } @@ -1779,11 +1776,11 @@ namespace kagome::dispute { } SignedDisputeStatement our_vote_signed{ - dispute_statement, - candidate_hash, - validator_public, - validator_signature, - env.session_index, + .dispute_statement = dispute_statement, + .candidate_hash = candidate_hash, + .validator_public = validator_public, + .validator_signature = validator_signature, + .session_index = env.session_index, }; auto msg_res = make_dispute_message( @@ -1932,7 +1929,7 @@ namespace kagome::dispute { CbOutcome &&cb) { REINVOKE(*dispute_thread_handler_, importStatements, - std::move(candidate_receipt), + candidate_receipt, session, std::move(statements), std::move(cb)); @@ -1966,9 +1963,8 @@ namespace kagome::dispute { OutputDisputes output; output.reserve(recent_disputes.size()); - std::transform( - recent_disputes.begin(), - recent_disputes.end(), + std::ranges::transform( + recent_disputes, std::back_inserter(output), [](const auto &p) -> std::tuple { @@ -2044,8 +2040,8 @@ namespace kagome::dispute { } auto &state_opt = state_res.value(); if (state_opt.has_value()) { - output.push_back(std::make_tuple( - session, candidate_hash, std::move(state_opt.value()))); + output.emplace_back( + session, candidate_hash, std::move(state_opt.value())); } else { SL_DEBUG(log_, "No votes found for candidate"); } @@ -2063,7 +2059,7 @@ namespace kagome::dispute { issueLocalStatement, session, candidate_hash, - std::move(candidate_receipt), + candidate_receipt, valid); SL_TRACE(log_, @@ -2116,7 +2112,7 @@ namespace kagome::dispute { metric_disputes_finality_lag_->set(0); } - cb(std::move(undisputed_chain)); + cb(undisputed_chain); } // https://github.com/paritytech/polkadot/blob/40974fb99c86f5c341105b7db53c7aa0df707d66/node/core/dispute-coordinator/src/initialized.rs#L1272 @@ -2162,10 +2158,8 @@ namespace kagome::dispute { last = {base_number, base_hash}; for (const auto &description : descriptions) { - auto has_disputed_candidate = std::any_of( - description.candidates.begin(), - description.candidates.end(), - [&](const auto &candidate_hash) { + auto has_disputed_candidate = std::ranges::any_of( + description.candidates, [&](const auto &candidate_hash) { return is_possibly_invalid(description.session, candidate_hash); }); if (has_disputed_candidate) { @@ -2195,7 +2189,7 @@ namespace kagome::dispute { auto authority_id_opt = authority_discovery_->get(peer_id); if (not authority_id_opt.has_value()) { SL_DEBUG(log_, "Peer {} is not validator - dropping message", peer_id); - // TODO reputation_changes: vec![COST_NOT_A_VALIDATOR], + // TODO(xDimon): reputation_changes: vec![COST_NOT_A_VALIDATOR], return sendDisputeResponse(DisputeProcessingError::NotAValidator, std::move(cb)); } @@ -2207,7 +2201,7 @@ namespace kagome::dispute { if (queue.size() >= kPeerQueueCapacity) { SL_DEBUG(log_, "Peer {} hit the rate limit - dropping message", peer_id); - // TODO reputation_changes: vec![COST_APPARENT_FLOOD], + // TODO(xDimon): reputation_changes: vec![COST_APPARENT_FLOOD], return sendDisputeResponse(DisputeProcessingError::AuthorityFlooding, std::move(cb)); } @@ -2228,10 +2222,7 @@ namespace kagome::dispute { void DisputeCoordinatorImpl::sendDisputeResponse(outcome::result res, CbOutcome &&cb) { - REINVOKE(*main_pool_handler_, - sendDisputeResponse, - std::move(res), - std::move(cb)); + REINVOKE(*main_pool_handler_, sendDisputeResponse, res, std::move(cb)); cb(res); } @@ -2287,7 +2278,7 @@ namespace kagome::dispute { for (auto &[peer, request, cb] : std::move(heads)) { // No early return - we cannot cancel imports of one peer, because the // import of another failed: - auto res = start_import_or_batch(peer, std::move(request), std::move(cb)); + auto res = start_import_or_batch(peer, request, std::move(cb)); if (res.has_error()) { SL_ERROR(log_, "Can't start import or batch: {}", res.error()); } @@ -2318,7 +2309,7 @@ namespace kagome::dispute { { const auto &[validator_index, signature, kind] = unchecked_valid_vote; if (validator_index >= session_info.validators.size()) { - // TODO reputation_changes: vec![COST_INVALID_SIGNATURE], + // TODO(xDimon): reputation_changes: vec![COST_INVALID_SIGNATURE], return DisputeMessageCreationError::InvalidValidatorIndex; } auto validator_public = session_info.validators[validator_index]; @@ -2336,29 +2327,29 @@ namespace kagome::dispute { signature, payload, validator_public); if (validation_res.has_error()) { - // TODO reputation_changes: vec![COST_INVALID_SIGNATURE], + // TODO(xDimon): reputation_changes: vec![COST_INVALID_SIGNATURE], return SignatureValidationError::InvalidSignature; } if (not validation_res.value()) { - // TODO reputation_changes: vec![COST_INVALID_SIGNATURE], + // TODO(xDimon): reputation_changes: vec![COST_INVALID_SIGNATURE], return SignatureValidationError::InvalidSignature; } - checked_valid_vote = {{ - dispute_statement, - candidate_hash, - validator_public, - signature, - session_index, - }, - validator_index}; + checked_valid_vote.payload = { + .dispute_statement = dispute_statement, + .candidate_hash = candidate_hash, + .validator_public = validator_public, + .validator_signature = signature, + .session_index = session_index, + }; + checked_valid_vote.ix = validator_index; } Indexed checked_invalid_vote; { const auto &[validator_index, signature, kind] = unchecked_invalid_vote; if (validator_index >= session_info.validators.size()) { - // TODO reputation_changes: vec![COST_INVALID_SIGNATURE], + // TODO(xDimon): reputation_changes: vec![COST_INVALID_SIGNATURE], return DisputeMessageCreationError::InvalidValidatorIndex; } auto validator_public = session_info.validators[validator_index]; @@ -2376,22 +2367,22 @@ namespace kagome::dispute { signature, payload, validator_public); if (validation_res.has_error()) { - // TODO reputation_changes: vec![COST_INVALID_SIGNATURE], + // TODO(xDimon): reputation_changes: vec![COST_INVALID_SIGNATURE], return SignatureValidationError::InvalidSignature; } if (not validation_res.value()) { - // TODO reputation_changes: vec![COST_INVALID_SIGNATURE], + // TODO(xDimon): reputation_changes: vec![COST_INVALID_SIGNATURE], return SignatureValidationError::InvalidSignature; } - checked_invalid_vote = {{ - dispute_statement, - candidate_hash, - validator_public, - signature, - session_index, - }, - validator_index}; + checked_invalid_vote.payload = { + .dispute_statement = dispute_statement, + .candidate_hash = candidate_hash, + .validator_public = validator_public, + .validator_signature = signature, + .session_index = session_index, + }; + checked_invalid_vote.ix = validator_index; } auto &valid_vote = checked_valid_vote; @@ -2550,7 +2541,7 @@ namespace kagome::dispute { auto disputes = selection.select_disputes(relay_parent); - cb(std::move(disputes)); + std::move(cb)(std::move(disputes)); return; } @@ -2586,7 +2577,7 @@ namespace kagome::dispute { [[maybe_unused]] static const common::Hash64 parachain_host_api_hash = hasher_->blake2b_64(common::Buffer::fromString("ParachainHost")); - auto it = std::find_if(apis.begin(), apis.end(), [](auto &api_version) { + auto it = std::ranges::find_if(apis, [](auto &api_version) { return api_version.first == parachain_host_api_hash; }); if (it == apis.end()) { diff --git a/core/dispute_coordinator/impl/dispute_coordinator_impl.hpp b/core/dispute_coordinator/impl/dispute_coordinator_impl.hpp index bf8f9830c1..d918bbf0db 100644 --- a/core/dispute_coordinator/impl/dispute_coordinator_impl.hpp +++ b/core/dispute_coordinator/impl/dispute_coordinator_impl.hpp @@ -196,7 +196,8 @@ namespace kagome::dispute { SessionIndex session, primitives::BlockHash relay_parent); - outcome::result process_on_chain_votes(ScrapedOnChainVotes votes); + outcome::result process_on_chain_votes( + const ScrapedOnChainVotes &votes); outcome::result process_active_leaves_update( const ActiveLeavesUpdate &update); diff --git a/core/dispute_coordinator/impl/runtime_info.cpp b/core/dispute_coordinator/impl/runtime_info.cpp index 315e6348ea..2035941c33 100644 --- a/core/dispute_coordinator/impl/runtime_info.cpp +++ b/core/dispute_coordinator/impl/runtime_info.cpp @@ -54,7 +54,8 @@ namespace kagome::dispute { OUTCOME_TRY(validator_info, get_validator_info(session_info)); - ExtendedSessionInfo ext_session_info{session_info, validator_info}; + ExtendedSessionInfo ext_session_info{.session_info = session_info, + .validator_info = validator_info}; auto ext_session_info_ref = session_info_cache_.put(session_index, std::move(ext_session_info)); return *ext_session_info_ref; diff --git a/core/dispute_coordinator/impl/sending_dispute.cpp b/core/dispute_coordinator/impl/sending_dispute.cpp index 71616869a6..025dc72f7c 100644 --- a/core/dispute_coordinator/impl/sending_dispute.cpp +++ b/core/dispute_coordinator/impl/sending_dispute.cpp @@ -16,13 +16,13 @@ namespace kagome::dispute { log::Logger logger, std::shared_ptr main_pool_handler, std::shared_ptr authority_discovery, - std::shared_ptr dispute_protocol, - const network::DisputeMessage &request) + const std::shared_ptr &dispute_protocol, + network::DisputeMessage request) : logger_(std::move(logger)), main_pool_handler_(std::move(main_pool_handler)), authority_discovery_(std::move(authority_discovery)), - dispute_protocol_(std::move(dispute_protocol)), - request_(request) { + dispute_protocol_(dispute_protocol), + request_(std::move(request)) { BOOST_ASSERT(logger_ != nullptr); BOOST_ASSERT(main_pool_handler_ != nullptr); BOOST_ASSERT(authority_discovery_ != nullptr); @@ -38,13 +38,11 @@ namespace kagome::dispute { // Note this will also contain all authorities for which sending failed // previously: std::vector add_authorities; - std::for_each(new_authorities.begin(), - new_authorities.end(), - [&](const auto &authority) { - if (not deliveries_.contains(authority)) { - add_authorities.emplace_back(authority); - } - }); + std::ranges::for_each(new_authorities, [&](const auto &authority) { + if (not deliveries_.contains(authority)) { + add_authorities.emplace_back(authority); + } + }); // Get rid of dead/irrelevant tasks/statuses: SL_TRACE(logger_, "Cleaning up deliveries"); diff --git a/core/dispute_coordinator/impl/sending_dispute.hpp b/core/dispute_coordinator/impl/sending_dispute.hpp index 2c98adbe01..0997e35e33 100644 --- a/core/dispute_coordinator/impl/sending_dispute.hpp +++ b/core/dispute_coordinator/impl/sending_dispute.hpp @@ -40,8 +40,8 @@ namespace kagome::dispute { log::Logger logger, std::shared_ptr main_pool_handler, std::shared_ptr authority_discovery, - std::shared_ptr dispute_protocol, - const network::DisputeMessage &request); + const std::shared_ptr &dispute_protocol, + network::DisputeMessage request); /// Make sure we are sending to all relevant authorities. /// diff --git a/core/dispute_coordinator/impl/storage_impl.cpp b/core/dispute_coordinator/impl/storage_impl.cpp index cb9756e633..4a70cdda21 100644 --- a/core/dispute_coordinator/impl/storage_impl.cpp +++ b/core/dispute_coordinator/impl/storage_impl.cpp @@ -66,13 +66,13 @@ namespace kagome::dispute { const CandidateHash &candidate_hash, const CandidateVotes &votes) { candidate_votes_[std::tie(session, candidate_hash)] = votes; - // TODO save to DB + // TODO(xDimon): save to DB } void StorageImpl::write_recent_disputes(RecentDisputes recent_disputes) { recent_disputes_ = std::move(recent_disputes); - // TODO save to DB + // TODO(xDimon): save to DB // https://github.com/paritytech/polkadot/blob/40974fb99c86f5c341105b7db53c7aa0df707d66/node/core/dispute-coordinator/src/backend.rs#L136 } diff --git a/core/dispute_coordinator/participation/impl/participation_impl.cpp b/core/dispute_coordinator/participation/impl/participation_impl.cpp index 78172a22ae..0cca4ebac1 100644 --- a/core/dispute_coordinator/participation/impl/participation_impl.cpp +++ b/core/dispute_coordinator/participation/impl/participation_impl.cpp @@ -50,7 +50,7 @@ namespace kagome::dispute { outcome::result ParticipationImpl::queue_participation( ParticipationPriority priority, ParticipationRequest request) { // Participation already running - we can ignore that request: - if (running_participations_.count(request.candidate_hash)) { + if (running_participations_.contains(request.candidate_hash)) { return outcome::success(); } @@ -70,13 +70,12 @@ namespace kagome::dispute { ParticipationRequest request, primitives::BlockHash recent_head) { if (running_participations_.emplace(request.candidate_hash).second) { // https://github.com/paritytech/polkadot/blob/40974fb99c86f5c341105b7db53c7aa0df707d66/node/core/dispute-coordinator/src/participation/mod.rs#L256 - dispute_thread_handler_->execute([wp{weak_from_this()}, - request{std::move(request)}, - recent_head{std::move(recent_head)}]() { - if (auto self = wp.lock()) { - self->participate(std::move(request), std::move(recent_head)); - } - }); + dispute_thread_handler_->execute( + [wp{weak_from_this()}, request, recent_head]() { + if (auto self = wp.lock()) { + self->participate(request, recent_head); + } + }); } return outcome::success(); } @@ -249,22 +248,22 @@ namespace kagome::dispute { BOOST_ASSERT(ctx->available_data.has_value()); BOOST_ASSERT(ctx->validation_code.has_value()); - pvf_->pvfValidate( - ctx->available_data->validation_data, - ctx->available_data->pov, - ctx->request.candidate_receipt, - ctx->validation_code.value(), - [cb{std::move(cb)}](outcome::result &&res) { - // we cast votes (either positive or negative) - // depending on the outcome of the validation and if - // valid, whether the commitments hash matches - - if (res.has_value()) { - cb(ParticipationOutcome::Valid); - return; - } - cb(ParticipationOutcome::Invalid); - }); + pvf_->pvfValidate(ctx->available_data->validation_data, + ctx->available_data->pov, + ctx->request.candidate_receipt, + ctx->validation_code.value(), + [cb{std::move(cb)}]( + const outcome::result &res) { + // we cast votes (either positive or negative) + // depending on the outcome of the validation and if + // valid, whether the commitments hash matches + + if (res.has_value()) { + cb(ParticipationOutcome::Valid); + return; + } + cb(ParticipationOutcome::Invalid); + }); } } // namespace kagome::dispute diff --git a/core/dispute_coordinator/participation/impl/participation_impl.hpp b/core/dispute_coordinator/participation/impl/participation_impl.hpp index 0f77893652..5dc1bda93f 100644 --- a/core/dispute_coordinator/participation/impl/participation_impl.hpp +++ b/core/dispute_coordinator/participation/impl/participation_impl.hpp @@ -66,9 +66,9 @@ namespace kagome::dispute { struct ParticipationContext { ParticipationRequest request; primitives::BlockHash block_hash; - std::optional available_data{}; - std::optional validation_code{}; - std::optional group_index{}; + std::optional available_data; + std::optional validation_code; + std::optional group_index; }; using ParticipationContextPtr = std::shared_ptr; using ParticipationCallback = std::function; diff --git a/core/dispute_coordinator/participation/impl/queues_impl.cpp b/core/dispute_coordinator/participation/impl/queues_impl.cpp index 1db5700799..96fe23a9da 100644 --- a/core/dispute_coordinator/participation/impl/queues_impl.cpp +++ b/core/dispute_coordinator/participation/impl/queues_impl.cpp @@ -69,7 +69,7 @@ namespace kagome::dispute { priority_.emplace(comparator, request); } else { - if (priority_.count(comparator)) { + if (priority_.contains(comparator)) { // The candidate is already in priority queue - don't add in in best // effort too. return outcome::success(); @@ -88,13 +88,13 @@ namespace kagome::dispute { std::optional QueuesImpl::dequeue() { if (not priority_.empty()) { if (auto priority_node = priority_.extract(priority_.begin())) { - return std::move(priority_node.mapped()); + return priority_node.mapped(); } } if (not best_effort_.empty()) { if (auto best_effort_node = best_effort_.extract(best_effort_.begin())) { - return std::move(best_effort_node.mapped()); + return best_effort_node.mapped(); } } diff --git a/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp b/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp index 7a84aebf62..e455016fdc 100644 --- a/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp +++ b/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp @@ -75,8 +75,8 @@ namespace kagome::dispute { auto &dispute_status = std::get<2>(recent_dispute); if (is_type(dispute_status) // is_confirmed_concluded - or onchain.count(std::tie(std::get<0>(recent_dispute), - std::get<1>(recent_dispute)))) { + or onchain.contains(std::tie(std::get<0>(recent_dispute), + std::get<1>(recent_dispute)))) { recent_disputes.emplace_back(std::move(recent_dispute)); } } @@ -107,8 +107,8 @@ namespace kagome::dispute { session_index, candidate_hash); - auto &statement_set = result.emplace_back( - DisputeStatementSet{candidate_hash, session_index, {}}); + auto &statement_set = result.emplace_back(DisputeStatementSet{ + .candidate_hash = candidate_hash, .session = session_index}); for (auto &[validator_index, value] : votes.valid) { auto &[statement, validator_signature] = value; @@ -226,6 +226,7 @@ namespace kagome::dispute { return result; }; result.emplace(std::tie(session_index, candidate_hash), selected_votes); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) total_votes_len += votes_len; } } @@ -288,14 +289,15 @@ namespace kagome::dispute { auto &dispute_state = it->second; const auto size = dispute_state.validators_against.bits.size(); - ssize_t supermajority = size - (std::min(1, size) - 1) / 3; + auto supermajority = + static_cast(size - (std::min(1, size) - 1) / 3); // Check if there are enough onchain votes for or against to conclude // the dispute bool concluded_onchain = false; for (const auto &bits : {dispute_state.validators_for.bits, dispute_state.validators_against.bits}) { - if (std::count(bits.begin(), bits.end(), true) >= supermajority) { + if (std::ranges::count(bits, true) >= supermajority) { concluded_onchain = true; break; } diff --git a/core/dispute_coordinator/provisioner/impl/random_selection.cpp b/core/dispute_coordinator/provisioner/impl/random_selection.cpp index 772dd855d9..2652b51602 100644 --- a/core/dispute_coordinator/provisioner/impl/random_selection.cpp +++ b/core/dispute_coordinator/provisioner/impl/random_selection.cpp @@ -57,13 +57,13 @@ namespace kagome::dispute { // Load all votes for all disputes from the coordinator. auto dispute_candidate_votes = - request_votes(dispute_coordinator_, std::move(disputes)); + request_votes(dispute_coordinator_, disputes); // Transform all `CandidateVotes` into `MultiDisputeStatementSet`. MultiDisputeStatementSet result; for (auto &[session, candidate, votes] : dispute_candidate_votes) { - auto &statement_set = - result.emplace_back(DisputeStatementSet{candidate, session, {}}); + auto &statement_set = result.emplace_back( + DisputeStatementSet{.candidate_hash = candidate, .session = session}); for (auto &[validator_index, value] : votes.valid) { auto &[statement, validator_signature] = value; @@ -126,7 +126,7 @@ namespace kagome::dispute { std::unordered_set> unique_new; for (auto &ext : std::move(extension)) { - if (lut.count(ext) == 0) { + if (not lut.contains(ext)) { unique_new.emplace(ext); } } diff --git a/core/filesystem/common.hpp b/core/filesystem/common.hpp index 8f114dffab..68639e8d9e 100644 --- a/core/filesystem/common.hpp +++ b/core/filesystem/common.hpp @@ -9,7 +9,7 @@ #include namespace kagome::filesystem { - using namespace std::filesystem; + using namespace std::filesystem; // NOLINT(google-build-using-namespace) path unique_path(const path &model = "%%%%-%%%%-%%%%-%%%%"); } // namespace kagome::filesystem diff --git a/core/host_api/host_api.hpp b/core/host_api/host_api.hpp index 79111dc659..11e3eb0d81 100644 --- a/core/host_api/host_api.hpp +++ b/core/host_api/host_api.hpp @@ -236,7 +236,7 @@ namespace kagome::host_api { * @returns an i32 integer value equal to 1 if all the signatures are valid * or a value equal to 0 if one or more of the signatures are invalid. */ - [[nodiscard]] virtual int32_t + [[nodiscard]] virtual runtime::WasmSize ext_crypto_finish_batch_verify_version_1() = 0; /** diff --git a/core/host_api/impl/child_storage_extension.cpp b/core/host_api/impl/child_storage_extension.cpp index ec87ce70ee..10db739af8 100644 --- a/core/host_api/impl/child_storage_extension.cpp +++ b/core/host_api/impl/child_storage_extension.cpp @@ -66,13 +66,13 @@ namespace kagome::host_api { template auto loadBuffer(runtime::Memory &memory, Arg &&span) { - auto [span_ptr, span_size] = runtime::PtrSize(span); + auto [span_ptr, span_size] = runtime::PtrSize(std::forward(span)); return memory.loadN(span_ptr, span_size); } template - auto loadBuffer(runtime::Memory &memory, Args &&...spans) { - return std::make_tuple(loadBuffer(memory, std::forward(spans))...); + auto loadBuffer(runtime::Memory &memory, const Args &...spans) { + return std::make_tuple(loadBuffer(memory, spans)...); } void ChildStorageExtension::ext_default_child_storage_set_version_1( diff --git a/core/host_api/impl/crypto_extension.cpp b/core/host_api/impl/crypto_extension.cpp index 17ef6638c2..01b1d730ca 100644 --- a/core/host_api/impl/crypto_extension.cpp +++ b/core/host_api/impl/crypto_extension.cpp @@ -37,7 +37,7 @@ namespace { } void checkIfKeyIsSupported(kagome::crypto::KeyType key_type, - kagome::log::Logger log) { + const kagome::log::Logger &log) { if (not key_type.is_supported()) { log->warn("key type {} is not officially supported", key_type); } @@ -211,9 +211,8 @@ namespace kagome::host_api { if (seed_opt.has_value()) { return key_store_.value()->ed25519().generateKeypair(key_type, seed_opt.value()); - } else { - return key_store_.value()->ed25519().generateKeypairOnDisk(key_type); } + return key_store_.value()->ed25519().generateKeypairOnDisk(key_type); }(); if (!kp_res) { throw_with_error( @@ -336,13 +335,12 @@ namespace kagome::host_api { } outcome::result kp_res = [&]() { - auto bip39_seed = seed_res.value(); + auto &bip39_seed = seed_res.value(); if (bip39_seed.has_value()) { return key_store_.value()->sr25519().generateKeypair( key_type, bip39_seed.value()); - } else { - return key_store_.value()->sr25519().generateKeypairOnDisk(key_type); } + return key_store_.value()->sr25519().generateKeypairOnDisk(key_type); }(); if (!kp_res) { throw_with_error( @@ -426,7 +424,7 @@ namespace kagome::host_api { auto res = verify_res && verify_res.value() ? kVerifySuccess : kVerifyFail; SL_TRACE_FUNC_CALL(logger_, res, signature, msg, pubkey_buffer); - return res; + return res; // NOLINT(cppcoreguidelines-narrowing-conversions) } int32_t CryptoExtension::ext_crypto_sr25519_batch_verify_version_1( @@ -437,7 +435,7 @@ namespace kagome::host_api { logger_, "Deprecated API method ext_crypto_sr25519_batch_verify_version_1 being " "called. Passing call to ext_crypto_sr25519_verify_version_1"); - return batchVerify( + return batchVerify( // NOLINT(cppcoreguidelines-narrowing-conversions) ext_crypto_sr25519_verify_version_1(sig, msg_span, pubkey_data)); } @@ -596,7 +594,7 @@ namespace kagome::host_api { auto msg_buffer = getMemory().loadN(msg_data, msg_len); crypto::EcdsaPublicKey pk; - std::copy(public_buffer.begin(), public_buffer.end(), pk.begin()); + std::ranges::copy(public_buffer, pk.begin()); auto key_pair = key_store_.value()->ecdsa().findKeypair(key_type, pk); if (!key_pair) { logger_->error("failed to find required key"); @@ -629,7 +627,7 @@ namespace kagome::host_api { auto msg_buffer = getMemory().loadN(msg_data, msg_len); crypto::EcdsaPublicKey pk; - std::copy(public_buffer.begin(), public_buffer.end(), pk.begin()); + std::ranges::copy(public_buffer, pk.begin()); auto key_pair = key_store_.value()->ecdsa().findKeypair(key_type, pk); if (!key_pair) { logger_->error("failed to find required key"); @@ -638,7 +636,7 @@ namespace kagome::host_api { } crypto::EcdsaPrehashedMessage digest; - std::copy(msg_buffer.begin(), msg_buffer.end(), digest.begin()); + std::ranges::copy(msg_buffer, digest.begin()); auto sign = ecdsa_provider_->signPrehashed(digest, key_pair.value().secret_key); if (!sign) { @@ -664,13 +662,12 @@ namespace kagome::host_api { } outcome::result kp_res = [&]() { - auto bip39_seed = seed_res.value(); + auto &bip39_seed = seed_res.value(); if (bip39_seed.has_value()) { return key_store_.value()->ecdsa().generateKeypair(key_type, bip39_seed.value()); - } else { - return key_store_.value()->ecdsa().generateKeypairOnDisk(key_type); } + return key_store_.value()->ecdsa().generateKeypairOnDisk(key_type); }(); if (!kp_res) { throw_with_error( @@ -711,7 +708,7 @@ namespace kagome::host_api { auto res = verify_res && verify_res.value() ? kVerifySuccess : kVerifyFail; SL_TRACE_FUNC_CALL(logger_, res, signature, msg, pubkey); - return res; + return res; // NOLINT(cppcoreguidelines-narrowing-conversions) } int32_t CryptoExtension::ext_crypto_ecdsa_verify_version_1( @@ -755,7 +752,7 @@ namespace kagome::host_api { auto res = verify_res && verify_res.value() ? kVerifySuccess : kVerifyFail; SL_TRACE_FUNC_CALL(logger_, res, signature, msg, pubkey); - return res; + return res; // NOLINT(cppcoreguidelines-narrowing-conversions) } void CryptoExtension::reset() { @@ -783,14 +780,12 @@ namespace kagome::host_api { } outcome::result kp_res = [&]() { - auto bip39_seed = seed_res.value(); + auto &bip39_seed = seed_res.value(); if (bip39_seed.has_value()) { return key_store_.value()->bandersnatch().generateKeypair( key_type, bip39_seed.value()); - } else { - return key_store_.value()->bandersnatch().generateKeypairOnDisk( - key_type); } + return key_store_.value()->bandersnatch().generateKeypairOnDisk(key_type); }(); if (!kp_res) { throw_with_error(logger_, diff --git a/core/host_api/impl/host_api_impl.cpp b/core/host_api/impl/host_api_impl.cpp index 4fc5c6d6d5..dc0ca510d4 100644 --- a/core/host_api/impl/host_api_impl.cpp +++ b/core/host_api/impl/host_api_impl.cpp @@ -29,6 +29,7 @@ namespace kagome::host_api { * Helps reading arguments from wasm and writing result to wasm. */ struct Ffi { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) runtime::Memory &memory; /** @@ -245,7 +246,7 @@ namespace kagome::host_api { return crypto_ext_.ext_crypto_start_batch_verify_version_1(); } - int32_t HostApiImpl::ext_crypto_finish_batch_verify_version_1() { + runtime::WasmSize HostApiImpl::ext_crypto_finish_batch_verify_version_1() { return crypto_ext_.ext_crypto_finish_batch_verify_version_1(); } diff --git a/core/host_api/impl/host_api_impl.hpp b/core/host_api/impl/host_api_impl.hpp index 08e4e8ff2e..8a55217057 100644 --- a/core/host_api/impl/host_api_impl.hpp +++ b/core/host_api/impl/host_api_impl.hpp @@ -118,7 +118,8 @@ namespace kagome::host_api { void ext_crypto_start_batch_verify_version_1() override; - [[nodiscard]] int32_t ext_crypto_finish_batch_verify_version_1() override; + [[nodiscard]] runtime::WasmSize ext_crypto_finish_batch_verify_version_1() + override; runtime::WasmSpan ext_crypto_secp256k1_ecdsa_recover_version_1( runtime::WasmPointer sig, runtime::WasmPointer msg) override; diff --git a/core/host_api/impl/offchain_extension.cpp b/core/host_api/impl/offchain_extension.cpp index 78d74897bf..14470d1546 100644 --- a/core/host_api/impl/offchain_extension.cpp +++ b/core/host_api/impl/offchain_extension.cpp @@ -67,7 +67,7 @@ namespace kagome::host_api { } auto &xt = xt_res.value(); - auto result = worker->submitTransaction(std::move(xt)); + auto result = worker->submitTransaction(xt); return memory.storeBuffer(scale::encode(result).value()); } @@ -84,7 +84,7 @@ namespace kagome::host_api { runtime::WasmI64 OffchainExtension::ext_offchain_timestamp_version_1() { auto worker = getWorker(); auto result = worker->timestamp(); - return result; + return static_cast(result); } void OffchainExtension::ext_offchain_sleep_until_version_1( @@ -284,7 +284,8 @@ namespace kagome::host_api { auto value_buffer = memory.loadN(value_ptr, value_size); auto value = value_buffer.toStringView(); - auto result = worker->httpRequestAddHeader(request_id, name, value); + auto result = worker->httpRequestAddHeader( + static_cast(request_id), name, value); if (result.isSuccess()) { SL_TRACE_FUNC_CALL(log_, "Success", name, value); @@ -323,8 +324,8 @@ namespace kagome::host_api { } auto &deadline = deadline_res.value(); - auto result = - worker->httpRequestWriteBody(request_id, chunk_buffer, deadline); + auto result = worker->httpRequestWriteBody( + static_cast(request_id), chunk_buffer, deadline); return memory.storeBuffer(scale::encode(result).value()); } @@ -365,7 +366,8 @@ namespace kagome::host_api { auto &memory = memory_provider_->getCurrentMemory()->get(); - auto result = worker->httpResponseHeaders(request_id); + auto result = + worker->httpResponseHeaders(static_cast(request_id)); SL_TRACE_FUNC_CALL( log_, fmt::format("<{} headers>", result.size()), request_id); @@ -395,7 +397,8 @@ namespace kagome::host_api { common::Buffer buffer; buffer.resize(dst_buffer.size); - auto result = worker->httpResponseReadBody(request_id, buffer, deadline); + auto result = worker->httpResponseReadBody( + static_cast(request_id), buffer, deadline); if (result.isSuccess()) { memory.storeBuffer(dst_buffer.ptr, buffer); @@ -443,7 +446,7 @@ namespace kagome::host_api { auto [value_ptr, value_size] = runtime::PtrSize(value); auto value_buffer = memory.loadN(value_ptr, value_size); - auto result = offchain_storage_->set(key_buffer, std::move(value_buffer)); + auto result = offchain_storage_->set(key_buffer, value_buffer); if (result.has_error()) { SL_WARN(log_, "Can't set value in storage: {}", result.error()); } diff --git a/core/host_api/impl/storage_extension.cpp b/core/host_api/impl/storage_extension.cpp index 078f739d24..a5b4189412 100644 --- a/core/host_api/impl/storage_extension.cpp +++ b/core/host_api/impl/storage_extension.cpp @@ -125,7 +125,7 @@ namespace kagome::host_api { SL_TRACE_VOID_FUNC_CALL(logger_, key, value); auto batch = storage_provider_->getCurrentBatch(); - auto put_result = batch->put(key, std::move(value)); + auto put_result = batch->put(key, value); if (not put_result) { logger_->error( "ext_set_storage failed, due to fail in trie db with reason: {}", diff --git a/core/host_api/impl/storage_util.cpp b/core/host_api/impl/storage_util.cpp index b2ae4b75bd..67c1bf5d0a 100644 --- a/core/host_api/impl/storage_util.cpp +++ b/core/host_api/impl/storage_util.cpp @@ -11,11 +11,11 @@ namespace kagome::host_api::detail { kagome::runtime::WasmI32 state_version_int) { if (state_version_int == 0) { return kagome::storage::trie::StateVersion::V0; - } else if (state_version_int == 1) { + } + if (state_version_int == 1) { return kagome::storage::trie::StateVersion::V1; - } else { - throw std::runtime_error(fmt::format( - "Invalid state version: {}. Expected 0 or 1", state_version_int)); } + throw std::runtime_error(fmt::format( + "Invalid state version: {}. Expected 0 or 1", state_version_int)); } } // namespace kagome::host_api::detail diff --git a/core/injector/application_injector.cpp b/core/injector/application_injector.cpp index c64e75fe09..64e1179abb 100644 --- a/core/injector/application_injector.cpp +++ b/core/injector/application_injector.cpp @@ -190,6 +190,7 @@ #include "runtime/runtime_api/impl/tagged_transaction_queue.hpp" #include "runtime/runtime_api/impl/transaction_payment_api.hpp" #include "runtime/wabt/instrument.hpp" +#include "runtime/wasm_compiler_definitions.hpp" // this header-file is generated #if KAGOME_WASM_COMPILER_WASM_EDGE == 1 @@ -245,15 +246,15 @@ namespace { sptr get_trie_storage_backend( sptr spaced_storage) { - auto backend = - std::make_shared(spaced_storage); + auto backend = std::make_shared( + std::move(spaced_storage)); return backend; } sptr get_rocks_db( const application::AppConfiguration &app_config, - sptr chain_spec) { + const sptr &chain_spec) { // hack for recovery mode (otherwise - fails due to rocksdb bug) bool prevent_destruction = app_config.recoverState().has_value(); @@ -268,6 +269,7 @@ namespace { if (!soft_limit) { exit(EXIT_FAILURE); } + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) options.max_open_files = soft_limit.value() / 2; auto db_res = @@ -308,7 +310,7 @@ namespace { sptr get_key_file_storage( const application::AppConfiguration &config, - sptr chain_spec) { + const sptr &chain_spec) { auto path = config.keystorePath(chain_spec->id()); auto key_file_storage_res = crypto::KeyFileStorage::createAt(path); if (not key_file_storage_res) { @@ -479,11 +481,11 @@ namespace { #if KAGOME_WASM_COMPILER_WAVM == 1 - using ModuleFactory = runtime::wavm::ModuleFactoryImpl; + using ChosenModuleFactoryImpl = runtime::wavm::ModuleFactoryImpl; #elif KAGOME_WASM_COMPILER_WASM_EDGE == 1 - using ModuleFactory = runtime::wasm_edge::ModuleFactoryImpl; + using ChosenModuleFactoryImpl = runtime::wasm_edge::ModuleFactoryImpl; #endif @@ -513,7 +515,7 @@ namespace { return choose_runtime_implementation< runtime::ModuleFactory, runtime::binaryen::ModuleFactoryImpl, - ModuleFactory>(injector, method, interpreter); + ChosenModuleFactoryImpl>(injector, method, interpreter); }), bind_by_lambda([](const auto &injector) -> sptr { @@ -699,7 +701,7 @@ namespace { di::bind.template to(), di::bind.template to(), bind_by_lambda([](const auto &injector) { - const application::AppConfiguration &config = + auto& config = injector .template create(); auto chain_spec = @@ -721,7 +723,7 @@ namespace { .template create(), injector.template create< sptr>()); - if (!root_res) { + if (root_res.has_error()) { throw std::runtime_error{fmt::format("Failed to calculate genesis state: {}", root_res.error())}; } const auto &hasher = @@ -814,7 +816,7 @@ namespace { bind_by_lambda( [](const auto &injector) -> sptr { - const application::AppConfiguration &config = + auto &config = injector.template create< application::AppConfiguration const &>(); if (config.statePruningDepth() == std::nullopt @@ -828,7 +830,7 @@ namespace { di::bind.template to(), di::bind.template to(), bind_by_lambda([](const auto &injector) { - const application::AppConfiguration &config = + auto &config = injector .template create(); return get_chain_spec(config); @@ -898,7 +900,7 @@ namespace { auto makeKagomeNodeInjector(sptr app_config, Ts &&...args) { return di::make_injector( - makeApplicationInjector(app_config), + makeApplicationInjector(std::move(app_config)), // user-defined overrides... std::forward(args)...); @@ -921,7 +923,7 @@ namespace kagome::injector { KagomeNodeInjector::KagomeNodeInjector( sptr app_config) : pimpl_{std::make_unique( - makeKagomeNodeInjector(app_config))} {} + makeKagomeNodeInjector(std::move(app_config)))} {} sptr KagomeNodeInjector::injectAppConfig() { return pimpl_->injector_ diff --git a/core/injector/calculate_genesis_state.hpp b/core/injector/calculate_genesis_state.hpp index 91c190b262..7f7179938a 100644 --- a/core/injector/calculate_genesis_state.hpp +++ b/core/injector/calculate_genesis_state.hpp @@ -48,15 +48,14 @@ namespace kagome::injector { [&] { return std::make_shared(code); }, {config})); OUTCOME_TRY(ctx, runtime::RuntimeContextFactory::stateless(instance)); - BOOST_OUTCOME_TRY( - runtime_version, - runtime_cache->getVersion( - ctx.module_instance->getCodeHash(), - [&]() -> outcome::result { - return ctx.module_instance - ->callAndDecodeExportFunction( - ctx, "Core_version"); - })); + auto version_res = + runtime_cache->getVersion(ctx.module_instance->getCodeHash(), [&] { + return ctx.module_instance + ->callAndDecodeExportFunction( + ctx, "Core_version"); + }); + OUTCOME_TRY(version_res); + runtime_version = std::move(version_res.value()); } auto version = storage::trie::StateVersion{runtime_version->state_version}; std::vector> child_tries; diff --git a/core/log/configurator.cpp b/core/log/configurator.cpp index 5cc706fc37..73c05a29ea 100644 --- a/core/log/configurator.cpp +++ b/core/log/configurator.cpp @@ -9,6 +9,7 @@ namespace kagome::log { namespace { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) std::string embedded_config(R"( # ---------------- sinks: @@ -125,7 +126,7 @@ namespace kagome::log { - name: debug # ---------------- )"); - } + } // namespace Configurator::Configurator(std::shared_ptr previous) : ConfiguratorFromYAML(std::move(previous), embedded_config) {} @@ -136,6 +137,5 @@ namespace kagome::log { Configurator::Configurator(std::shared_ptr previous, filesystem::path path) - : ConfiguratorFromYAML(std::move(previous), - filesystem::path(path.string())) {} + : ConfiguratorFromYAML(std::move(previous), std::move(path)) {} } // namespace kagome::log diff --git a/core/log/formatters/ref_and_ptr.hpp b/core/log/formatters/ref_and_ptr.hpp index 4f690beb42..29f687a12f 100644 --- a/core/log/formatters/ref_and_ptr.hpp +++ b/core/log/formatters/ref_and_ptr.hpp @@ -37,7 +37,7 @@ struct fmt::formatter> { return fmt::format_to(ctx.out(), "{}", ref.value()); } else { static constexpr string_view message(""); - return std::copy(std::begin(message), std::end(message), ctx.out()); + return std::ranges::copy(message, ctx.out()); } } }; @@ -68,7 +68,7 @@ struct fmt::formatter> { return fmt::format_to(ctx.out(), "{}", *sptr); } else { static constexpr string_view message(""); - return std::copy(std::begin(message), std::end(message), ctx.out()); + return std::ranges::copy(message, ctx.out()); } } }; @@ -99,7 +99,7 @@ struct fmt::formatter> { return fmt::format_to(ctx.out(), "{}", *uptr); } else { static constexpr string_view message(""); - return std::copy(std::begin(message), std::end(message), ctx.out()); + return std::ranges::copy(message, ctx.out()); } } }; @@ -130,7 +130,7 @@ struct fmt::formatter> { return fmt::format_to(ctx.out(), "{}", *wptr.lock()); } else { static constexpr string_view message(""); - return std::copy(std::begin(message), std::end(message), ctx.out()); + return std::ranges::copy(message, ctx.out()); } } }; diff --git a/core/log/logger.cpp b/core/log/logger.cpp index e2db610fed..887cd5df98 100644 --- a/core/log/logger.cpp +++ b/core/log/logger.cpp @@ -45,27 +45,33 @@ namespace kagome::log { outcome::result str2lvl(std::string_view str) { if (str == "trace") { return Level::TRACE; - } else if (str == "debug") { + } + if (str == "debug") { return Level::DEBUG; - } else if (str == "verbose") { + } + if (str == "verbose") { return Level::VERBOSE; - } else if (str == "info" or str == "inf") { + } + if (str == "info" or str == "inf") { return Level::INFO; - } else if (str == "warning" or str == "warn") { + } + if (str == "warning" or str == "warn") { return Level::WARN; - } else if (str == "error" or str == "err") { + } + if (str == "error" or str == "err") { return Level::ERROR; - } else if (str == "critical" or str == "crit") { + } + if (str == "critical" or str == "crit") { return Level::CRITICAL; - } else if (str == "off" or str == "no") { + } + if (str == "off" or str == "no") { return Level::OFF; - } else { - return Error::WRONG_LEVEL; } + return Error::WRONG_LEVEL; } void setLoggingSystem(std::weak_ptr logging_system) { - logging_system_ = logging_system; + logging_system_ = std::move(logging_system); libp2p::log::setLoggingSystem(logging_system_.lock()); profiling_logger = createLogger("Profiler", "profile"); } @@ -91,18 +97,21 @@ namespace kagome::log { std::cerr << "Can't read group"; } if (not logging_system->getGroup(group_name)) { - std::cerr << "Unknown group: " << group_name << std::endl; + std::cerr << "Unknown group: " << group_name + << std::endl; // NOLINT(performance-avoid-endl) continue; } std::string level_string; if (not std::getline(iss2, level_string)) { - std::cerr << "Can't read level for group '" << group_name << "'"; + std::cerr << "Can't read level for group '" << group_name << "'" + << std::endl; // NOLINT(performance-avoid-endl) continue; } auto res = str2lvl(level_string); if (not res.has_value()) { - std::cerr << "Invalid level: " << level_string << std::endl; + std::cerr << "Invalid level: " << level_string + << std::endl; // NOLINT(performance-avoid-endl) continue; } auto level = res.value(); diff --git a/core/log/profiling_logger.cpp b/core/log/profiling_logger.cpp index 8e87a71ef9..5ebacd00d6 100644 --- a/core/log/profiling_logger.cpp +++ b/core/log/profiling_logger.cpp @@ -7,5 +7,6 @@ #include "log/profiling_logger.hpp" namespace kagome::log { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) Logger profiling_logger = nullptr; -} +} // namespace kagome::log diff --git a/core/log/profiling_logger.hpp b/core/log/profiling_logger.hpp index 935bb6019c..c16d6273f4 100644 --- a/core/log/profiling_logger.hpp +++ b/core/log/profiling_logger.hpp @@ -12,7 +12,7 @@ namespace kagome::log { - extern Logger profiling_logger; + extern Logger profiling_logger; // NOLINT struct ProfileScope { using Clock = ::kagome::clock::SteadyClockImpl; @@ -48,7 +48,7 @@ namespace kagome::log { private: bool done = false; - std::string_view scope{}; + std::string_view scope; Clock::TimePoint start; log::Logger logger; }; diff --git a/core/log/trace_macros.hpp b/core/log/trace_macros.hpp index ec34b72032..6ffc9474d6 100644 --- a/core/log/trace_macros.hpp +++ b/core/log/trace_macros.hpp @@ -15,6 +15,7 @@ namespace kagome::log { struct TraceFuncCall { const void *caller{}; std::string_view func_name; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) const Ret &ret; Args args; }; diff --git a/core/metrics/impl/exposer_impl.cpp b/core/metrics/impl/exposer_impl.cpp index 1af716ca4e..67d4b6e63b 100644 --- a/core/metrics/impl/exposer_impl.cpp +++ b/core/metrics/impl/exposer_impl.cpp @@ -82,11 +82,10 @@ namespace kagome::metrics { void ExposerImpl::acceptOnce() { new_session_ = std::make_shared(*context_, session_config_); - new_session_->connectOnRequest(std::bind(&Handler::onSessionRequest, - handler_.get(), - std::placeholders::_1, - std::placeholders::_2)); - + new_session_->connectOnRequest( + [handler = handler_.get()](auto request, auto session) { + handler->onSessionRequest(std::move(request), std::move(session)); + }); auto on_accept = [wp{weak_from_this()}](boost::system::error_code ec) { if (auto self = wp.lock()) { if (not ec) { diff --git a/core/metrics/impl/prometheus/handler_impl.cpp b/core/metrics/impl/prometheus/handler_impl.cpp index 0b0ad1ad1e..fb876590fc 100644 --- a/core/metrics/impl/prometheus/handler_impl.cpp +++ b/core/metrics/impl/prometheus/handler_impl.cpp @@ -12,10 +12,12 @@ #include "utils/retain_if.hpp" #include "utils/wptr.hpp" -using namespace prometheus; +using prometheus::Collectable; +using prometheus::MetricFamily; +using prometheus::TextSerializer; std::vector CollectMetrics( - const std::vector> &collectables) { + const std::vector> &collectables) { auto collected_metrics = std::vector{}; for (auto &&wcollectable : collectables) { @@ -54,7 +56,7 @@ namespace kagome::metrics { } std::size_t PrometheusHandler::writeResponse(std::shared_ptr session, - Session::Request request, + const Session::Request &request, const std::string &body) { Session::Response res{boost::beast::http::status::ok, request.version()}; res.set(boost::beast::http::field::content_type, diff --git a/core/metrics/impl/prometheus/handler_impl.hpp b/core/metrics/impl/prometheus/handler_impl.hpp index 75307417a3..4f8f076619 100644 --- a/core/metrics/impl/prometheus/handler_impl.hpp +++ b/core/metrics/impl/prometheus/handler_impl.hpp @@ -34,7 +34,7 @@ namespace kagome::metrics { static void cleanupStalePointers( std::vector> &collectables); std::size_t writeResponse(std::shared_ptr session, - Session::Request request, + const Session::Request &request, const std::string &body); std::mutex collectables_mutex_; diff --git a/core/metrics/impl/prometheus/registry_impl.cpp b/core/metrics/impl/prometheus/registry_impl.cpp index 6bb34412cc..b930c5d45a 100644 --- a/core/metrics/impl/prometheus/registry_impl.cpp +++ b/core/metrics/impl/prometheus/registry_impl.cpp @@ -74,7 +74,7 @@ namespace kagome::metrics { const std::map &labels) { prometheus::Summary::Quantiles q; for (const auto &p : quantiles) { - q.push_back({p.first, p.second}); + q.emplace_back(p.first, p.second); } return registerMetric(name, labels, q, max_age, age_buckets); } diff --git a/core/network/impl/grandpa_transmitter_impl.cpp b/core/network/impl/grandpa_transmitter_impl.cpp index 870c36cd89..6a8f741de2 100644 --- a/core/network/impl/grandpa_transmitter_impl.cpp +++ b/core/network/impl/grandpa_transmitter_impl.cpp @@ -19,6 +19,7 @@ namespace kagome::network { GrandpaNeighborMessage &&message) { auto protocol = router_->getGrandpaProtocol(); BOOST_ASSERT_MSG(protocol, "Router did not provide grandpa protocol"); + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) protocol->neighbor(std::move(message)); } @@ -52,6 +53,7 @@ namespace kagome::network { CatchUpRequest &&message) { auto protocol = router_->getGrandpaProtocol(); BOOST_ASSERT_MSG(protocol, "Router did not provide grandpa protocol"); + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) protocol->catchUpRequest(peer_id, std::move(message)); } diff --git a/core/network/impl/peer_manager_impl.cpp b/core/network/impl/peer_manager_impl.cpp index 347febe96f..35722ac3bd 100644 --- a/core/network/impl/peer_manager_impl.cpp +++ b/core/network/impl/peer_manager_impl.cpp @@ -110,7 +110,7 @@ namespace kagome::network { storage_{storage->getSpace(storage::Space::kDefault)}, hasher_{std::move(hasher)}, reputation_repository_{std::move(reputation_repository)}, - can_disconnect_{std::move(can_disconnect)}, + can_disconnect_{can_disconnect}, peer_view_{std::move(peer_view)} { BOOST_ASSERT(identify_ != nullptr); BOOST_ASSERT(kademlia_ != nullptr); @@ -289,7 +289,7 @@ namespace kagome::network { void PeerManagerImpl::forOnePeer( const PeerId &peer_id, std::function func) const { - if (active_peers_.count(peer_id)) { + if (active_peers_.contains(peer_id)) { func(peer_id); } } @@ -349,19 +349,19 @@ namespace kagome::network { // disconnect from peers with negative reputation const auto peer_reputation = reputation_repository_->reputation(peer_id); if (peer_reputation < kDisconnectReputation) { - peers_list.push_back( - std::make_pair(std::numeric_limits::min(), peer_id)); + peers_list.emplace_back(std::numeric_limits::min(), + peer_id); // we have to store peers somewhere first due to inability to iterate // over active_peers_ and do disconnectFromPeers (which modifies // active_peers_) at the same time } else { - peers_list.push_back(std::make_pair(peer_reputation, peer_id)); + peers_list.emplace_back(peer_reputation, peer_id); } } - std::sort(peers_list.begin(), - peers_list.end(), - [](const auto &l, const auto &r) { return r.first < l.first; }); + std::ranges::sort(peers_list, [](const auto &l, const auto &r) { + return r.first < l.first; + }); for (; !peers_list.empty() && (peers_list.size() > hard_limit @@ -453,7 +453,7 @@ namespace kagome::network { } SL_DEBUG(log_, "Try to connect to peer {}", peer_info.id); - for (auto addr : peer_info.addresses) { + for (auto &addr : peer_info.addresses) { SL_DEBUG(log_, " address: {}", addr.getStringAddress()); } @@ -653,20 +653,20 @@ namespace kagome::network { const PeerInfo &peer_info, const libp2p::network::ConnectionManager::ConnectionSPtr &connection, F &&opened_callback) { - auto block_announce_protocol = router_->getBlockAnnounceProtocol(); - BOOST_ASSERT_MSG(block_announce_protocol, + auto protocol = router_->getBlockAnnounceProtocol(); + BOOST_ASSERT_MSG(protocol, "Router did not provide block announce protocol"); if (!openOutgoing( stream_engine_, - block_announce_protocol, + protocol, peer_info, [wp{weak_from_this()}, peer_info, - protocol = block_announce_protocol, + protocol, connection, - opened_callback{std::forward(opened_callback)}]( - auto &&stream_res) mutable { + opened_callback = + std::forward(opened_callback)](auto &&stream_res) mutable { auto self = wp.lock(); if (not self) { return; @@ -690,19 +690,21 @@ namespace kagome::network { // Add to the active peer list if (auto [ap_it, added] = self->active_peers_.emplace( - peer_id, PeerDescriptor{peer_type, self->clock_->now()}); + peer_id, + PeerDescriptor{.peer_type = peer_type, + .time_point = self->clock_->now()}); added) { self->recently_active_peers_.insert(peer_id); // And remove from queue if (auto piq_it = self->peers_in_queue_.find(peer_id); piq_it != self->peers_in_queue_.end()) { - auto qtc_it = - std::find_if(self->queue_to_connect_.cbegin(), - self->queue_to_connect_.cend(), - [&peer_id = peer_id](const auto &item) { - return peer_id == item; - }); + auto qtc_it = std::ranges::find_if( + self->queue_to_connect_.cbegin(), + self->queue_to_connect_.cend(), + [&peer_id = peer_id](const auto &item) { + return peer_id == item; + }); self->queue_to_connect_.erase(qtc_it); self->peers_in_queue_.erase(piq_it); BOOST_ASSERT(self->queue_to_connect_.size() @@ -728,7 +730,7 @@ namespace kagome::network { })) { SL_DEBUG(log_, "Stream {} with {} is alive or connecting", - block_announce_protocol->protocolName(), + protocol->protocolName(), peer_info.id); } } @@ -757,6 +759,7 @@ namespace kagome::network { network::CollationVersion proto_version) { // network::CollationVersion::VStaging /// If validator start validation protocol + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) if (peer_state.roles.flags.authority) { auto validation_protocol = [&]() -> std::shared_ptr { return router_->getValidationProtocolVStaging(); @@ -839,6 +842,7 @@ namespace kagome::network { if (peer_state.has_value()) { auto &state = peer_state->get(); if (not out) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) if (state.roles.flags.full == 1) { if (self->countPeers(PeerType::PEER_TYPE_IN) >= self->app_config_.inPeers()) { @@ -846,6 +850,7 @@ namespace kagome::network { self->disconnectFromPeer(peer_info.id); return; } + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) } else if (state.roles.flags.light == 1) { if (self->countPeers(PeerType::PEER_TYPE_IN, IsLight(true)) >= self->app_config_.inPeersLight()) { @@ -863,11 +868,12 @@ namespace kagome::network { network::CollationVersion::VStaging); auto beefy_protocol = std::static_pointer_cast( self->router_->getBeefyProtocol()); - openOutgoing(self->stream_engine_, - beefy_protocol, - peer_info, - [](outcome::result< - std::shared_ptr>) {}); + openOutgoing( + self->stream_engine_, + beefy_protocol, + peer_info, + [](const outcome::result< + std::shared_ptr> &) {}); } }); @@ -882,6 +888,7 @@ namespace kagome::network { void PeerManagerImpl::reserveStatusStreams(const PeerId &peer_id) const { if (auto ps = getPeerState(peer_id); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) ps && ps->get().roles.flags.authority) { auto proto_val_vstaging = router_->getValidationProtocolVStaging(); BOOST_ASSERT_MSG(proto_val_vstaging, @@ -976,22 +983,22 @@ namespace kagome::network { } size_t PeerManagerImpl::countPeers(PeerType in_out, IsLight in_light) const { - return std::count_if(active_peers_.begin(), - active_peers_.end(), - [&](const decltype(active_peers_)::value_type &x) { - if (x.second.peer_type == PeerType::PEER_TYPE_OUT) { - return in_out == PeerType::PEER_TYPE_OUT; - } - if (in_out == PeerType::PEER_TYPE_OUT) { - return false; - } - auto it = peer_states_.find(x.first); - if (it == peer_states_.end()) { - return false; - } - auto &roles = it->second.roles.flags; - return (in_light ? roles.light : roles.full) == 1; - }); + return std::ranges::count_if( + active_peers_, [&](const decltype(active_peers_)::value_type &x) { + if (x.second.peer_type == PeerType::PEER_TYPE_OUT) { + return in_out == PeerType::PEER_TYPE_OUT; + } + if (in_out == PeerType::PEER_TYPE_OUT) { + return false; + } + auto it = peer_states_.find(x.first); + if (it == peer_states_.end()) { + return false; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) + const auto &roles = it->second.roles.flags; + return (in_light ? roles.light : roles.full) == 1; + }); } std::optional PeerManagerImpl::peerFinalized( diff --git a/core/network/impl/peer_view.cpp b/core/network/impl/peer_view.cpp index 6e67aa21b4..a3b06baaca 100644 --- a/core/network/impl/peer_view.cpp +++ b/core/network/impl/peer_view.cpp @@ -19,7 +19,7 @@ namespace kagome::network { std::make_shared()}, remote_view_update_observable_{ std::make_shared()}, - block_tree_(std::move(block_tree)) { + block_tree_(block_tree) { app_state_manager->takeControl(*this); } @@ -58,7 +58,7 @@ namespace kagome::network { void PeerView::updateMyView(network::ExView &&view) { BOOST_ASSERT(my_view_update_observable_); - std::sort(view.view.heads_.begin(), view.view.heads_.end()); + std::ranges::sort(view.view.heads_); if (!my_view_ || my_view_->view != view.view || my_view_->new_head != view.new_head) { if (my_view_) { @@ -94,7 +94,7 @@ namespace kagome::network { if (ref) { remote_view_update_observable_->notify( - EventType::kPeerRemoved, peer_id, std::move(*ref)); + EventType::kPeerRemoved, peer_id, *ref); } } diff --git a/core/network/impl/protocols/block_announce_protocol.cpp b/core/network/impl/protocols/block_announce_protocol.cpp index aec7973556..f34b4c0da1 100644 --- a/core/network/impl/protocols/block_announce_protocol.cpp +++ b/core/network/impl/protocols/block_announce_protocol.cpp @@ -15,6 +15,7 @@ namespace kagome::network { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) KAGOME_DEFINE_CACHE(BlockAnnounceProtocol); BlockAnnounceProtocol::BlockAnnounceProtocol( @@ -54,9 +55,9 @@ namespace kagome::network { BlockAnnounceHandshake BlockAnnounceProtocol::createHandshake() const { return BlockAnnounceHandshake{ - roles_, - block_tree_->bestBlock(), - block_tree_->getGenesisBlockHash(), + .roles = roles_, + .best_block = block_tree_->bestBlock(), + .genesis_hash = block_tree_->getGenesisBlockHash(), }; } @@ -86,11 +87,9 @@ namespace kagome::network { return true; }; auto on_message = [peer_id](std::shared_ptr self, - BlockAnnounce block_announce) { + const BlockAnnounce &block_announce) { // Calculate and save hash, 'cause it's just received announce - primitives::calculateBlockHash( - const_cast(block_announce.header), - *self->hasher_); + primitives::calculateBlockHash(block_announce.header, *self->hasher_); SL_VERBOSE(self->base_.logger(), "Announce of block {} is received from {}", diff --git a/core/network/impl/protocols/grandpa_protocol.cpp b/core/network/impl/protocols/grandpa_protocol.cpp index 2d25cd9e19..4a39705071 100644 --- a/core/network/impl/protocols/grandpa_protocol.cpp +++ b/core/network/impl/protocols/grandpa_protocol.cpp @@ -17,6 +17,8 @@ #include "network/types/roles.hpp" namespace kagome::network { + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) KAGOME_DEFINE_CACHE(GrandpaProtocol); GrandpaProtocol::GrandpaProtocol( @@ -125,9 +127,11 @@ namespace kagome::network { "NeighborMessage has received from {}", peer_id); auto info = peer_manager_->getPeerState(peer_id); - grandpa_observer_->onNeighborMessage(peer_id, - compactFromRefToOwn(info), - std::move(neighbor_message)); + grandpa_observer_->onNeighborMessage( + peer_id, + compactFromRefToOwn(info), + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + std::move(neighbor_message)); } }, [&](network::CatchUpRequest &&catch_up_request) { @@ -135,7 +139,10 @@ namespace kagome::network { base_.logger(), "CatchUpRequest has received from {}", peer_id); auto info = peer_manager_->getPeerState(peer_id); grandpa_observer_->onCatchUpRequest( - peer_id, compactFromRefToOwn(info), std::move(catch_up_request)); + peer_id, + compactFromRefToOwn(info), + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + std::move(catch_up_request)); }, [&](network::CatchUpResponse &&catch_up_response) { SL_VERBOSE( @@ -154,6 +161,7 @@ namespace kagome::network { auto filter = [&, &msg = vote_message](const PeerId &peer_id, const PeerState &info) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) if (info.roles.flags.light != 0) { return false; } @@ -255,6 +263,7 @@ namespace kagome::network { } const auto &info = info_opt.value().get(); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) if (not set_changed and info.roles.flags.light) { return false; } @@ -443,7 +452,7 @@ namespace kagome::network { auto shared_msg = KAGOME_EXTRACT_SHARED_CACHE(GrandpaProtocol, GrandpaMessage); - (*shared_msg) = GrandpaMessage(std::move(catch_up_request)); + (*shared_msg) = GrandpaMessage(catch_up_request); stream_engine_->send(peer_id, shared_from_this(), std::move(shared_msg)); } @@ -529,6 +538,7 @@ namespace kagome::network { if (not predicate(peer, info)) { return; } + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) (info.roles.flags.authority != 0 ? authorities : any) .emplace_back(peer); } diff --git a/core/network/impl/protocols/light.cpp b/core/network/impl/protocols/light.cpp index 2c8fea8681..edd6740029 100644 --- a/core/network/impl/protocols/light.cpp +++ b/core/network/impl/protocols/light.cpp @@ -66,6 +66,9 @@ namespace kagome::network { OUTCOME_TRY(trie.get().tryGet(key)); } } - return LightProtocolResponse{proof.vec(), call != nullptr}; + return LightProtocolResponse{ + .proof = proof.vec(), + .call = call != nullptr, + }; } } // namespace kagome::network diff --git a/core/network/impl/protocols/propagate_transactions_protocol.cpp b/core/network/impl/protocols/propagate_transactions_protocol.cpp index e164be5975..60a684affa 100644 --- a/core/network/impl/protocols/propagate_transactions_protocol.cpp +++ b/core/network/impl/protocols/propagate_transactions_protocol.cpp @@ -23,6 +23,7 @@ namespace { namespace kagome::network { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) KAGOME_DEFINE_CACHE(PropagateTransactionsProtocol); PropagateTransactionsProtocol::PropagateTransactionsProtocol( @@ -85,7 +86,7 @@ namespace kagome::network { }; auto on_message = [peer_id = stream->remotePeerId().value()]( std::shared_ptr self, - PropagatedExtrinsics message) { + const PropagatedExtrinsics &message) { SL_VERBOSE(self->base_.logger(), "Received {} propagated transactions from {}", message.extrinsics.size(), @@ -152,7 +153,9 @@ namespace kagome::network { peers.push_back(peer_id); }); if (peers.size() > 1) { // One of peers is current node itself - metric_propagated_tx_counter_->inc(peers.size() - 1); + auto delta = peers.size() - 1; + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) + metric_propagated_tx_counter_->inc(delta); for (const auto &tx : txs) { if (auto key = ext_event_key_repo_->get(tx.hash); key.has_value()) { extrinsic_events_engine_->notify( diff --git a/core/network/impl/protocols/protocol_req_collation.cpp b/core/network/impl/protocols/protocol_req_collation.cpp index b8f5458a53..c74bd60b00 100644 --- a/core/network/impl/protocols/protocol_req_collation.cpp +++ b/core/network/impl/protocols/protocol_req_collation.cpp @@ -92,8 +92,8 @@ namespace kagome::network { void ReqCollationProtocol::onIncomingStream(std::shared_ptr stream) {} void ReqCollationProtocol::newOutgoingStream( - const PeerId &peer_id, - std::function>)> &&cb) { + const PeerId &, + std::function>)> &&) { BOOST_ASSERT_MSG(false, "Must not be called!"); } @@ -104,8 +104,7 @@ namespace kagome::network { &&response_handler) { BOOST_ASSERT_MSG(v1_impl_, "v1 ReqCollationProtocolImpl must be initialized!"); - return v1_impl_->doRequest( - peer_id, std::move(request), std::move(response_handler)); + return v1_impl_->doRequest(peer_id, request, std::move(response_handler)); } void ReqCollationProtocol::request( @@ -116,7 +115,7 @@ namespace kagome::network { BOOST_ASSERT_MSG(vstaging_impl_, "vstaging ReqCollationProtocolImpl must be initialized!"); return vstaging_impl_->doRequest( - peer_id, std::move(request), std::move(response_handler)); + peer_id, request, std::move(response_handler)); } } // namespace kagome::network diff --git a/core/network/impl/protocols/protocol_req_pov.cpp b/core/network/impl/protocols/protocol_req_pov.cpp index 7702ee9520..a551eef5f8 100644 --- a/core/network/impl/protocols/protocol_req_pov.cpp +++ b/core/network/impl/protocols/protocol_req_pov.cpp @@ -24,15 +24,15 @@ namespace kagome::network { const blockchain::GenesisBlockHash &genesis_hash, std::shared_ptr observer) : RequestResponseProtocolImpl< - RequestPov, - ResponsePov, - ScaleMessageReadWriter>{kReqPovProtocolName, - host, - make_protocols(kReqPovProtocol, - genesis_hash, - kProtocolPrefixPolkadot), - log::createLogger(kReqPovProtocolName, - "req_pov_protocol")}, + RequestPov, + ResponsePov, + ScaleMessageReadWriter>{kReqPovProtocolName, + host, + make_protocols(kReqPovProtocol, + genesis_hash, + kProtocolPrefixPolkadot), + log::createLogger(kReqPovProtocolName, + "req_pov_protocol")}, observer_{std::move(observer)} {} protected: @@ -40,7 +40,7 @@ namespace kagome::network { RequestPov request, std::shared_ptr /*stream*/) override { BOOST_ASSERT(observer_); base().logger()->info("Received PoV request(candidate hash={})", request); - auto response = observer_->OnPovRequest(std::move(request)); + auto response = observer_->OnPovRequest(request); if (response.has_error()) { base().logger()->warn( "Our PoV response has error.(candidate hash={}, error={})", @@ -72,7 +72,7 @@ namespace kagome::network { const blockchain::GenesisBlockHash &genesis_hash, std::shared_ptr observer) : impl_{std::make_shared( - host, chain_spec, genesis_hash, std::move(observer))} {} + host, chain_spec, genesis_hash, std::move(observer))} {} const Protocol &ReqPovProtocol::protocolName() const { BOOST_ASSERT(impl_ && !!"ReqPovProtocolImpl must be initialized!"); diff --git a/core/network/impl/protocols/state_protocol_impl.cpp b/core/network/impl/protocols/state_protocol_impl.cpp index 4d6704ffcb..697e39830e 100644 --- a/core/network/impl/protocols/state_protocol_impl.cpp +++ b/core/network/impl/protocols/state_protocol_impl.cpp @@ -175,7 +175,7 @@ namespace kagome::network { self->writeRequest( stream, - std::move(state_request), + state_request, [stream, wp = std::move(wp), response_handler = @@ -203,7 +203,7 @@ namespace kagome::network { } void StateProtocolImpl::writeResponse(std::shared_ptr stream, - StateResponse state_response) { + const StateResponse &state_response) { auto read_writer = std::make_shared(stream); read_writer->write( @@ -233,7 +233,7 @@ namespace kagome::network { void StateProtocolImpl::writeRequest( std::shared_ptr stream, - StateRequest state_request, + const StateRequest &state_request, std::function)> &&cb) { auto read_writer = std::make_shared(stream); diff --git a/core/network/impl/protocols/state_protocol_impl.hpp b/core/network/impl/protocols/state_protocol_impl.hpp index 2c1c4fc595..faa38ee86b 100644 --- a/core/network/impl/protocols/state_protocol_impl.hpp +++ b/core/network/impl/protocols/state_protocol_impl.hpp @@ -61,10 +61,10 @@ namespace kagome::network { void readRequest(std::shared_ptr stream); void writeResponse(std::shared_ptr stream, - StateResponse state_response); + const StateResponse &state_response); void writeRequest(std::shared_ptr stream, - StateRequest state_request, + const StateRequest &state_request, std::function)> &&cb); void readResponse( diff --git a/core/network/impl/protocols/sync_protocol_impl.cpp b/core/network/impl/protocols/sync_protocol_impl.cpp index 5d1b76a29d..143354a6b6 100644 --- a/core/network/impl/protocols/sync_protocol_impl.cpp +++ b/core/network/impl/protocols/sync_protocol_impl.cpp @@ -57,8 +57,7 @@ namespace kagome::network { // peer record in cache is valid and not expired entry->valid_till = now + expiration_time_; // prolong expiry time auto &requests = entry->fingerprints; - if (std::count(requests.begin(), requests.end(), request_fingerprint) - >= 2) { + if (std::ranges::count(requests, request_fingerprint) >= 2) { return true; } requests.push_back(request_fingerprint); @@ -69,7 +68,7 @@ namespace kagome::network { const PeerId &peer_id, BlocksRequest::Fingerprint request_fingerprint, std::optional target_slot) { - CacheRecordIndex slot; + CacheRecordIndex slot; // NOLINT(cppcoreguidelines-init-variables) if (target_slot) { slot = *target_slot; } else { @@ -264,7 +263,7 @@ namespace kagome::network { logmsg += fmt::format(", max {}", block_request.max.value()); } - self->base_.logger()->verbose(std::move(logmsg)); + self->base_.logger()->verbose(logmsg); } auto block_response_res = self->sync_observer_->onBlocksRequest( @@ -344,7 +343,7 @@ namespace kagome::network { void SyncProtocolImpl::writeRequest( std::shared_ptr stream, - BlocksRequest block_request, + const BlocksRequest &block_request, std::function)> &&cb) { auto read_writer = std::make_shared(stream); @@ -465,7 +464,7 @@ namespace kagome::network { logmsg += fmt::format(", max {}", block_request.max.value()); } - base_.logger()->debug(std::move(logmsg)); + base_.logger()->debug(logmsg); } newOutgoingStream( @@ -492,7 +491,7 @@ namespace kagome::network { stream->remotePeerId().value()); self->writeRequest(stream, - std::move(block_request), + block_request, [stream, wp = std::move(wp), response_handler = std::move(response_handler)]( diff --git a/core/network/impl/protocols/sync_protocol_impl.hpp b/core/network/impl/protocols/sync_protocol_impl.hpp index ebb6ae8ac7..82bb67ec83 100644 --- a/core/network/impl/protocols/sync_protocol_impl.hpp +++ b/core/network/impl/protocols/sync_protocol_impl.hpp @@ -139,7 +139,7 @@ namespace kagome::network { const BlocksResponse &block_response); void writeRequest(std::shared_ptr stream, - BlocksRequest block_request, + const BlocksRequest &block_request, std::function)> &&cb); void readResponse(std::shared_ptr stream, diff --git a/core/network/impl/router_libp2p.cpp b/core/network/impl/router_libp2p.cpp index 08f6c30a3b..2283179743 100644 --- a/core/network/impl/router_libp2p.cpp +++ b/core/network/impl/router_libp2p.cpp @@ -58,37 +58,33 @@ namespace kagome::network { LazySPtr send_dispute_protocol, LazySPtr ping_protocol, LazySPtr fetch_attested_candidate) - : app_state_manager_{app_state_manager}, + : app_state_manager_{std::move(app_state_manager)}, host_{host}, app_config_(app_config), own_info_{own_info}, main_pool_handler_{main_thread_pool.handler(*app_state_manager_)}, - block_announce_protocol_(std::move(block_announce_protocol)), - grandpa_protocol_(std::move(grandpa_protocol)), - sync_protocol_(std::move(sync_protocol)), - state_protocol_(std::move(state_protocol)), - warp_protocol_{std::move(warp_protocol)}, - beefy_protocol_{std::move(beefy_protocol)}, - beefy_justifications_protocol_{ - std::move(beefy_justifications_protocol)}, - light_protocol_{std::move(light_protocol)}, - propagate_transactions_protocol_( - std::move(propagate_transactions_protocol)), - validation_protocol_(std::move(validation_protocol)), - collation_protocol_(std::move(collation_protocol)), - collation_protocol_vstaging_(std::move(collation_protocol_vstaging)), - validation_protocol_vstaging_(std::move(validation_protocol_vstaging)), - req_collation_protocol_(std::move(req_collation_protocol)), - req_pov_protocol_(std::move(req_pov_protocol)), - fetch_chunk_protocol_(std::move(fetch_chunk_protocol)), - fetch_chunk_protocol_obsolete_( - std::move(fetch_chunk_protocol_obsolete)), - fetch_available_data_protocol_( - std::move(fetch_available_data_protocol)), - statement_fetching_protocol_(std::move(statement_fetching_protocol)), - send_dispute_protocol_(std::move(send_dispute_protocol)), - ping_protocol_{std::move(ping_protocol)}, - fetch_attested_candidate_{std::move(fetch_attested_candidate)}, + block_announce_protocol_(block_announce_protocol), + grandpa_protocol_(grandpa_protocol), + sync_protocol_(sync_protocol), + state_protocol_(state_protocol), + warp_protocol_(warp_protocol), + beefy_protocol_(beefy_protocol), + beefy_justifications_protocol_(beefy_justifications_protocol), + light_protocol_(light_protocol), + propagate_transactions_protocol_(propagate_transactions_protocol), + validation_protocol_(validation_protocol), + collation_protocol_(collation_protocol), + collation_protocol_vstaging_(collation_protocol_vstaging), + validation_protocol_vstaging_(validation_protocol_vstaging), + req_collation_protocol_(req_collation_protocol), + req_pov_protocol_(req_pov_protocol), + fetch_chunk_protocol_(fetch_chunk_protocol), + fetch_chunk_protocol_obsolete_(fetch_chunk_protocol_obsolete), + fetch_available_data_protocol_(fetch_available_data_protocol), + statement_fetching_protocol_(statement_fetching_protocol), + send_dispute_protocol_(send_dispute_protocol), + ping_protocol_(ping_protocol), + fetch_attested_candidate_(fetch_attested_candidate), log_{log::createLogger("RouterLibp2p", "network")} { BOOST_ASSERT(app_state_manager_ != nullptr); BOOST_ASSERT(main_pool_handler_ != nullptr); diff --git a/core/network/impl/state_protocol_observer_impl.cpp b/core/network/impl/state_protocol_observer_impl.cpp index 67243f9c33..98b42fb720 100644 --- a/core/network/impl/state_protocol_observer_impl.cpp +++ b/core/network/impl/state_protocol_observer_impl.cpp @@ -86,8 +86,8 @@ namespace kagome::network { value_res.has_value()) { const auto &value_opt = value_res.value(); if (value_opt.has_value()) { - entry.entries.emplace_back( - StateEntry{cursor->key().value(), {*value_opt}}); + entry.entries.emplace_back(StateEntry{.key = cursor->key().value(), + .value = {*value_opt}}); size += entry.entries.back().key.size() + entry.entries.back().value.size(); } @@ -114,7 +114,7 @@ namespace kagome::network { OUTCOME_TRY(header, blocks_headers_->getBlockHeader(request.hash)); if (not request.no_proof) { OUTCOME_TRY(proof, prove(header.state_root, request.start)); - return StateResponse{{}, proof}; + return StateResponse{.entries = {}, .proof = proof}; } OUTCOME_TRY(batch, storage_->getEphemeralBatchAt(header.state_root)); @@ -157,7 +157,8 @@ namespace kagome::network { value_res.has_value()) { const auto &value = value_res.value(); auto &entry = response.entries.front(); - entry.entries.emplace_back(StateEntry{cursor->key().value(), {*value}}); + entry.entries.emplace_back( + StateEntry{.key = cursor->key().value(), .value = {*value}}); size += entry.entries.back().key.size() + entry.entries.back().value.size(); // if key is child state storage hash iterate child storage keys diff --git a/core/network/impl/state_protocol_observer_impl.hpp b/core/network/impl/state_protocol_observer_impl.hpp index 4c3ec783dc..7acdd9db98 100644 --- a/core/network/impl/state_protocol_observer_impl.hpp +++ b/core/network/impl/state_protocol_observer_impl.hpp @@ -28,7 +28,7 @@ namespace kagome::network { : public StateProtocolObserver, public std::enable_shared_from_this { public: - enum class Error { + enum class Error : uint8_t { INVALID_CHILD_ROOTHASH = 1, NOTFOUND_CHILD_ROOTHASH, VALUE_NOT_FOUND, diff --git a/core/network/impl/state_sync_request_flow.cpp b/core/network/impl/state_sync_request_flow.cpp index ea55115fe6..1a62d750c2 100644 --- a/core/network/impl/state_sync_request_flow.cpp +++ b/core/network/impl/state_sync_request_flow.cpp @@ -21,22 +21,20 @@ namespace kagome::network { : node_db_{std::move(node_db)}, block_info_{block_info}, block_{block}, + done_(isKnown(block.state_root)), log_{log::createLogger("StateSync")} { - done_ = isKnown(block.state_root); if (not done_) { - auto &level = levels_.emplace_back(); - level.child = {}; - level.branch_hash = block.state_root; + levels_.emplace_back(Level{.branch_hash = block.state_root}); } } - bool StateSyncRequestFlow::complete() const { - return done_; - } - StateRequest StateSyncRequestFlow::nextRequest() const { BOOST_ASSERT(not complete()); - StateRequest req{block_info_.hash, {}, false}; + StateRequest req{ + .hash = block_info_.hash, + .start = {}, + .no_proof = false, + }; for (auto &level : levels_) { storage::trie::KeyNibbles nibbles; for (auto &item : level.stack) { @@ -78,8 +76,16 @@ namespace kagome::network { // when trie node is contained in other node value BOOST_OUTCOME_TRY(node, codec.decodeNode(raw)); } - level.push( - {node, std::nullopt, level.child, {it->first, std::move(raw)}}); + level.push({ + .node = node, + .branch = std::nullopt, + .child = level.child, + .t = + { + .hash = it->first, + .encoded = std::move(raw), + }, + }); nodes.erase(it); return outcome::success(); }; diff --git a/core/network/impl/state_sync_request_flow.hpp b/core/network/impl/state_sync_request_flow.hpp index d01179c37d..2c7cc0a2fc 100644 --- a/core/network/impl/state_sync_request_flow.hpp +++ b/core/network/impl/state_sync_request_flow.hpp @@ -46,7 +46,9 @@ namespace kagome::network { return block_.state_root; } - bool complete() const; + bool complete() const { + return done_; + } StateRequest nextRequest() const; @@ -60,11 +62,13 @@ namespace kagome::network { primitives::BlockInfo block_info_; primitives::BlockHeader block_; - bool done_ = false; std::vector levels_; std::unordered_set known_; size_t stat_count_ = 0, stat_size_ = 0; + + bool done_ = false; + log::Logger log_; }; } // namespace kagome::network diff --git a/core/network/impl/stream_engine.cpp b/core/network/impl/stream_engine.cpp index 96723b0a4a..bbf00c3772 100644 --- a/core/network/impl/stream_engine.cpp +++ b/core/network/impl/stream_engine.cpp @@ -28,17 +28,18 @@ namespace kagome::network { streams_.exclusiveAccess([&](PeerMap &streams) { bool existing = false; - forPeerProtocol(peer_id, streams, protocol, [&](auto type, auto &descr) { - existing = true; - if (is_incoming) { - uploadStream( - descr.incoming.stream, stream, protocol, Direction::INCOMING); - } - if (is_outgoing) { - uploadStream( - descr.outgoing.stream, stream, protocol, Direction::OUTGOING); - } - }); + forPeerProtocol( + peer_id, streams, protocol, [&](const auto &type, auto &descr) { + existing = true; + if (is_incoming) { + uploadStream( + descr.incoming.stream, stream, protocol, Direction::INCOMING); + } + if (is_outgoing) { + uploadStream( + descr.outgoing.stream, stream, protocol, Direction::OUTGOING); + } + }); if (not existing) { auto &proto_map = streams[peer_id]; @@ -132,7 +133,7 @@ namespace kagome::network { BOOST_ASSERT(protocol); return streams_.exclusiveAccess([&](auto &streams) { forPeerProtocol( - peer_id, streams, protocol, [&](auto, ProtocolDescr &descr) { + peer_id, streams, protocol, [&](const auto &, ProtocolDescr &descr) { return descr.dropReserved(); }); }); @@ -192,7 +193,7 @@ namespace kagome::network { self->streams_.exclusiveAccess([&](auto &streams) { self->forPeerProtocol( - peer_id, streams, protocol, [&](auto, auto &descr) { + peer_id, streams, protocol, [&](const auto &, auto &descr) { descr.deferred_messages.clear(); descr.dropReserved(); }); @@ -214,7 +215,7 @@ namespace kagome::network { self->streams_.exclusiveAccess([&](auto &streams) { [[maybe_unused]] bool existing = false; self->forPeerProtocol( - peer_id, streams, protocol, [&](auto, auto &descr) { + peer_id, streams, protocol, [&](const auto &, auto &descr) { existing = true; self->uploadStream(descr.outgoing.stream, stream, diff --git a/core/network/impl/sync_protocol_observer_impl.cpp b/core/network/impl/sync_protocol_observer_impl.cpp index d13fb33488..7f91b43004 100644 --- a/core/network/impl/sync_protocol_observer_impl.cpp +++ b/core/network/impl/sync_protocol_observer_impl.cpp @@ -164,7 +164,7 @@ namespace kagome::network { for (const auto &hash : hash_chain) { auto &new_block = - response.blocks.emplace_back(primitives::BlockData{hash}); + response.blocks.emplace_back(primitives::BlockData{.hash = hash}); if (header_needed) { auto header_res = blocks_headers_->getBlockHeader(hash); diff --git a/core/network/impl/synchronizer_impl.cpp b/core/network/impl/synchronizer_impl.cpp index 85e66bef5e..eca774951e 100644 --- a/core/network/impl/synchronizer_impl.cpp +++ b/core/network/impl/synchronizer_impl.cpp @@ -115,7 +115,7 @@ namespace kagome::network { peer_manager_(std::move(peer_manager)), scheduler_(std::move(scheduler)), hasher_(std::move(hasher)), - timeline_{std::move(timeline)}, + timeline_{timeline}, beefy_{std::move(beefy)}, grandpa_environment_{std::move(grandpa_environment)}, chain_sub_engine_(std::move(chain_sub_engine)), @@ -291,7 +291,7 @@ namespace kagome::network { auto &block_in_queue = it->second; block_in_queue.peers.emplace(peer_id); if (handler) { - handler(std::move(block_info)); + handler(block_info); } return; } @@ -379,10 +379,10 @@ namespace kagome::network { primitives::BlockNumber hint, SyncResultHandler &&handler, std::map &&observed) { - network::BlocksRequest request{network::BlockAttribute::HEADER, - hint, - network::Direction::ASCENDING, - 1}; + network::BlocksRequest request{.fields = network::BlockAttribute::HEADER, + .from = hint, + .direction = network::Direction::ASCENDING, + .max = 1}; auto response_handler = [wp{weak_from_this()}, lower, upper, @@ -455,6 +455,7 @@ namespace kagome::network { return; } + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) primitives::BlockNumber hint; // Narrowing interval for next iteration @@ -527,10 +528,11 @@ namespace kagome::network { void SynchronizerImpl::loadBlocks(const libp2p::peer::PeerId &peer_id, primitives::BlockInfo from, SyncResultHandler &&handler) { - network::BlocksRequest request{attributesForSync(sync_method_), - from.hash, - network::Direction::ASCENDING, - std::nullopt}; + network::BlocksRequest request{ + .fields = attributesForSync(sync_method_), + .from = from.hash, + .direction = network::Direction::ASCENDING, + }; if (recent_requests_.contains({peer_id, request.fingerprint()})) { if (handler) { @@ -557,227 +559,234 @@ namespace kagome::network { } load_blocks_max_ = {from.number, now}; - auto response_handler = [wp{weak_from_this()}, - from, - peer_id, - handler = std::move(handler), - need_body = - has(request.fields, BlockAttribute::BODY), - parent_hash = primitives::BlockHash{}]( - outcome::result - response_res) mutable { - auto self = wp.lock(); - if (not self) { - return; - } - self->load_blocks_.erase(from); + auto response_handler = + [wp{weak_from_this()}, + from, + peer_id, + handler = std::move(handler), + need_body = has(request.fields, BlockAttribute::BODY), + parent_hash = primitives::BlockHash{}]( + outcome::result response_res) mutable { + auto self = wp.lock(); + if (not self) { + return; + } + self->load_blocks_.erase(from); - // Any error interrupts loading of blocks - if (response_res.has_error()) { - SL_VERBOSE(self->log_, - "Can't load blocks from {} beginning block {}: {}", - peer_id, - from, - response_res.error()); - if (handler) { - handler(response_res.as_failure()); - } - return; - } - auto &blocks = response_res.value().blocks; + // Any error interrupts loading of blocks + if (response_res.has_error()) { + SL_VERBOSE(self->log_, + "Can't load blocks from {} beginning block {}: {}", + peer_id, + from, + response_res.error()); + if (handler) { + handler(response_res.as_failure()); + } + return; + } + auto &blocks = response_res.value().blocks; + + // No block in response is abnormal situation. + // At least one starting block should be returned as existing + if (blocks.empty()) { + SL_VERBOSE(self->log_, + "Can't load blocks from {} beginning block {}: " + "Response does not have any blocks", + peer_id, + from); + if (handler) { + handler(Error::EMPTY_RESPONSE); + } + return; + } - // No block in response is abnormal situation. - // At least one starting block should be returned as existing - if (blocks.empty()) { - SL_VERBOSE(self->log_, - "Can't load blocks from {} beginning block {}: " - "Response does not have any blocks", + SL_TRACE(self->log_, + "{} blocks are loaded from {} beginning block {}", + blocks.size(), peer_id, from); - if (handler) { - handler(Error::EMPTY_RESPONSE); - } - return; - } - - SL_TRACE(self->log_, - "{} blocks are loaded from {} beginning block {}", - blocks.size(), - peer_id, - from); - - if (blocks[0].header - and blocks[0].header->number - > self->block_tree_->getLastFinalized().number - and not self->known_blocks_.contains(blocks[0].header->parent_hash) - and not self->block_tree_->has(blocks[0].header->parent_hash)) { - if (handler) { - handler(Error::DISCARDED_BLOCK); - } - return; - } - bool some_blocks_added = false; - primitives::BlockInfo last_loaded_block; - - for (auto &block : blocks) { - // Check if header is provided - if (not block.header.has_value()) { - SL_VERBOSE(self->log_, - "Can't load blocks from {} starting from block {}: " - "Received block without header", - peer_id, - from); - if (handler) { - handler(Error::RESPONSE_WITHOUT_BLOCK_HEADER); - } - return; - } - // Check if body is provided - if (need_body and block.header->number != 0 - and not block.body.has_value()) { - SL_VERBOSE(self->log_, - "Can't load blocks from {} starting from block {}: " - "Received block without body", - peer_id, - from); - if (handler) { - handler(Error::RESPONSE_WITHOUT_BLOCK_BODY); + if (blocks[0].header + and blocks[0].header->number + > self->block_tree_->getLastFinalized().number + and not self->known_blocks_.contains( + blocks[0].header->parent_hash) + and not self->block_tree_->has(blocks[0].header->parent_hash)) { + if (handler) { + handler(Error::DISCARDED_BLOCK); + } + return; } - return; - } - auto &header = block.header.value(); - const auto &last_finalized_block = - self->block_tree_->getLastFinalized(); + bool some_blocks_added = false; + primitives::BlockInfo last_loaded_block; - // Check by number if block is not finalized yet - if (last_finalized_block.number >= header.number) { - if (last_finalized_block.number == header.number) { - if (last_finalized_block.hash != block.hash) { + for (auto &block : blocks) { + // Check if header is provided + if (not block.header.has_value()) { SL_VERBOSE(self->log_, "Can't load blocks from {} starting from block {}: " - "Received discarded block {}", + "Received block without header", peer_id, - from, - BlockInfo(header.number, block.hash)); + from); if (handler) { - handler(Error::DISCARDED_BLOCK); + handler(Error::RESPONSE_WITHOUT_BLOCK_HEADER); } return; } + // Check if body is provided + if (need_body and block.header->number != 0 + and not block.body.has_value()) { + SL_VERBOSE(self->log_, + "Can't load blocks from {} starting from block {}: " + "Received block without body", + peer_id, + from); + if (handler) { + handler(Error::RESPONSE_WITHOUT_BLOCK_BODY); + } + return; + } + auto &header = block.header.value(); + + const auto &last_finalized_block = + self->block_tree_->getLastFinalized(); + + // Check by number if block is not finalized yet + if (last_finalized_block.number >= header.number) { + if (last_finalized_block.number == header.number) { + if (last_finalized_block.hash != block.hash) { + SL_VERBOSE( + self->log_, + "Can't load blocks from {} starting from block {}: " + "Received discarded block {}", + peer_id, + from, + BlockInfo(header.number, block.hash)); + if (handler) { + handler(Error::DISCARDED_BLOCK); + } + return; + } - SL_TRACE(self->log_, - "Skip block {} received from {}: " - "it is finalized with block #{}", - BlockInfo(header.number, block.hash), - peer_id, - last_finalized_block.number); - continue; - } - - SL_TRACE(self->log_, - "Skip block {} received from {}: " - "it is below the last finalized block #{}", - BlockInfo(header.number, block.hash), - peer_id, - last_finalized_block.number); - continue; - } + SL_TRACE(self->log_, + "Skip block {} received from {}: " + "it is finalized with block #{}", + BlockInfo(header.number, block.hash), + peer_id, + last_finalized_block.number); + continue; + } - // Check if block is not discarded - if (last_finalized_block.number + 1 == header.number) { - if (last_finalized_block.hash != header.parent_hash) { - SL_ERROR(self->log_, - "Can't complete blocks loading from {} starting from " - "block {}: Received discarded block {}", - peer_id, - from, - BlockInfo(header.number, header.parent_hash)); - if (handler) { - handler(Error::DISCARDED_BLOCK); + SL_TRACE(self->log_, + "Skip block {} received from {}: " + "it is below the last finalized block #{}", + BlockInfo(header.number, block.hash), + peer_id, + last_finalized_block.number); + continue; } - return; - } - - // Start to check parents - parent_hash = header.parent_hash; - } - // Check if block is in chain - static const primitives::BlockHash zero_hash; - if (parent_hash != header.parent_hash && parent_hash != zero_hash) { - SL_ERROR(self->log_, - "Can't complete blocks loading from {} starting from " - "block {}: Received block is not descendant of previous", - peer_id, - from); - if (handler) { - handler(Error::WRONG_ORDER); - } - return; - } + // Check if block is not discarded + if (last_finalized_block.number + 1 == header.number) { + if (last_finalized_block.hash != header.parent_hash) { + SL_ERROR(self->log_, + "Can't complete blocks loading from {} starting from " + "block {}: Received discarded block {}", + peer_id, + from, + BlockInfo(header.number, header.parent_hash)); + if (handler) { + handler(Error::DISCARDED_BLOCK); + } + return; + } - // Calculate and save hash, 'cause it's new received block - primitives::calculateBlockHash(header, *self->hasher_); + // Start to check parents + parent_hash = header.parent_hash; + } - // Check if hash is valid - if (block.hash != header.hash()) { - SL_ERROR(self->log_, - "Can't complete blocks loading from {} starting from " - "block {}: " - "Received block whose hash does not match the header", - peer_id, - from); - if (handler) { - handler(Error::INVALID_HASH); - } - return; - } + // Check if block is in chain + static const primitives::BlockHash zero_hash; + if (parent_hash != header.parent_hash && parent_hash != zero_hash) { + SL_ERROR(self->log_, + "Can't complete blocks loading from {} starting from " + "block {}: Received block is not descendant of previous", + peer_id, + from); + if (handler) { + handler(Error::WRONG_ORDER); + } + return; + } - last_loaded_block = header.blockInfo(); + // Calculate and save hash, 'cause it's new received block + primitives::calculateBlockHash(header, *self->hasher_); - parent_hash = block.hash; + // Check if hash is valid + if (block.hash != header.hash()) { + SL_ERROR(self->log_, + "Can't complete blocks loading from {} starting from " + "block {}: " + "Received block whose hash does not match the header", + peer_id, + from); + if (handler) { + handler(Error::INVALID_HASH); + } + return; + } - // Add block in queue and save peer or just add peer for existing record - auto it = self->known_blocks_.find(block.hash); - if (it == self->known_blocks_.end()) { - self->known_blocks_.emplace(block.hash, KnownBlock{block, {peer_id}}); - self->metric_import_queue_length_->set(self->known_blocks_.size()); - } else { - it->second.peers.emplace(peer_id); - SL_TRACE(self->log_, - "Skip block {} received from {}: already enqueued", - BlockInfo(header.number, block.hash), - peer_id); - continue; - } + last_loaded_block = header.blockInfo(); + + parent_hash = block.hash; + + // Add block in queue and save peer or just add peer for existing + // record + auto it = self->known_blocks_.find(block.hash); + if (it == self->known_blocks_.end()) { + self->known_blocks_.emplace(block.hash, + KnownBlock{ + .data = block, + .peers = {peer_id}, + }); + self->metric_import_queue_length_->set( + self->known_blocks_.size()); + } else { + it->second.peers.emplace(peer_id); + SL_TRACE(self->log_, + "Skip block {} received from {}: already enqueued", + BlockInfo(header.number, block.hash), + peer_id); + continue; + } - SL_TRACE(self->log_, - "Enqueue block {} received from {}", - BlockInfo(header.number, block.hash), - peer_id); + SL_TRACE(self->log_, + "Enqueue block {} received from {}", + BlockInfo(header.number, block.hash), + peer_id); - self->generations_.emplace(header.number, block.hash); - self->ancestry_.emplace(header.parent_hash, block.hash); + self->generations_.emplace(header.number, block.hash); + self->ancestry_.emplace(header.parent_hash, block.hash); - some_blocks_added = true; - } + some_blocks_added = true; + } - SL_TRACE(self->log_, "Block loading is finished"); - if (handler) { - handler(last_loaded_block); - } + SL_TRACE(self->log_, "Block loading is finished"); + if (handler) { + handler(last_loaded_block); + } - if (some_blocks_added) { - SL_TRACE(self->log_, "Enqueued some new blocks: schedule applying"); - self->scheduler_->schedule([wp] { - if (auto self = wp.lock()) { - self->applyNextBlock(); + if (some_blocks_added) { + SL_TRACE(self->log_, "Enqueued some new blocks: schedule applying"); + self->scheduler_->schedule([wp] { + if (auto self = wp.lock()) { + self->applyNextBlock(); + } + }); } - }); - } - }; + }; fetch(peer_id, std::move(request), @@ -814,8 +823,8 @@ namespace kagome::network { state_sync_flow_.emplace(trie_node_db_, block, header); } state_sync_.emplace(StateSync{ - peer_id, - std::move(handler), + .peer = peer_id, + .cb = std::move(handler), }); SL_INFO(log_, "Sync of state for block {} has started", block); syncState(); @@ -855,7 +864,7 @@ namespace kagome::network { outcome::result SynchronizerImpl::syncState( std::unique_lock &lock, outcome::result &&_res) { - OUTCOME_TRY(res, _res); + OUTCOME_TRY(res, std::move(_res)); OUTCOME_TRY(state_sync_flow_->onResponse(res)); if (not state_sync_flow_->complete()) { syncState(); @@ -880,17 +889,16 @@ namespace kagome::network { } void SynchronizerImpl::post_block_addition( - outcome::result &&block_addition_result, + outcome::result block_addition_result, Synchronizer::SyncResultHandler &&handler, const primitives::BlockHash &hash) { REINVOKE(*main_pool_handler_, post_block_addition, - std::move(block_addition_result), + block_addition_result, std::move(handler), hash); - processBlockAdditionResult( - std::move(block_addition_result), hash, std::move(handler)); + processBlockAdditionResult(block_addition_result, hash, std::move(handler)); postApplyBlock(hash); } @@ -1010,7 +1018,7 @@ namespace kagome::network { } void SynchronizerImpl::processBlockAdditionResult( - outcome::result &&block_addition_result, + outcome::result block_addition_result, const primitives::BlockHash &hash, SyncResultHandler &&handler) { auto node = known_blocks_.extract(hash); @@ -1031,19 +1039,19 @@ namespace kagome::network { n ? fmt::format("and {} others have", n) : fmt::format("has"), block_addition_result.error()); if (handler) { - handler(Error::DISCARDED_BLOCK); + std::move(handler)(Error::DISCARDED_BLOCK); } } else { SL_DEBUG(log_, "Block {} is skipped as existing", block_info); if (handler) { - handler(block_info); + std::move(handler)(block_info); } } } else { telemetry_->notifyBlockImported( block_info, telemetry::BlockOrigin::kNetworkInitialSync); if (handler) { - handler(block_info); + std::move(handler)(block_info); } if (block_data.beefy_justification) { @@ -1183,7 +1191,7 @@ namespace kagome::network { for (auto p_it = peers.begin(); p_it != peers.end();) { auto cp_it = p_it++; - auto peer_id = *cp_it; + auto &peer_id = *cp_it; if (busy_peers_.find(peer_id) != busy_peers_.end()) { SL_TRACE(log_, @@ -1313,11 +1321,11 @@ namespace kagome::network { bool SynchronizerImpl::fetchJustification(const primitives::BlockInfo &block, CbResultVoid cb) { BlocksRequest request{ - BlockAttribute::JUSTIFICATION, - block.hash, - Direction::DESCENDING, - 1, - false, + .fields = BlockAttribute::JUSTIFICATION, + .from = block.hash, + .direction = Direction::DESCENDING, + .max = 1, + .multiple_justifications = false, }; auto chosen = chooseJustificationPeer(block.number, request.fingerprint()); if (not chosen) { @@ -1354,11 +1362,11 @@ namespace kagome::network { bool SynchronizerImpl::fetchJustificationRange(primitives::BlockNumber min, FetchJustificationRangeCb cb) { BlocksRequest request{ - BlockAttribute::JUSTIFICATION, - min, - Direction::ASCENDING, - std::nullopt, - false, + .fields = BlockAttribute::JUSTIFICATION, + .from = min, + .direction = Direction::ASCENDING, + .max = std::nullopt, + .multiple_justifications = false, }; auto chosen = chooseJustificationPeer(min, request.fingerprint()); if (not chosen) { diff --git a/core/network/impl/synchronizer_impl.hpp b/core/network/impl/synchronizer_impl.hpp index 7b9b6ee3d5..c139387ecc 100644 --- a/core/network/impl/synchronizer_impl.hpp +++ b/core/network/impl/synchronizer_impl.hpp @@ -192,10 +192,9 @@ namespace kagome::network { private: void postApplyBlock(const primitives::BlockHash &hash); - void processBlockAdditionResult( - outcome::result &&block_addition_result, - const primitives::BlockHash &hash, - SyncResultHandler &&handler); + void processBlockAdditionResult(outcome::result block_addition_result, + const primitives::BlockHash &hash, + SyncResultHandler &&handler); /// Subscribes handler for block with provided {@param block_info} /// {@param handler} will be called When block is received or discarded /// @returns true if subscription is successful @@ -209,7 +208,7 @@ namespace kagome::network { /// Tries to request another portion of block void askNextPortionOfBlocks(); - void post_block_addition(outcome::result &&block_addition_result, + void post_block_addition(outcome::result block_addition_result, Synchronizer::SyncResultHandler &&handler, const primitives::BlockHash &hash); diff --git a/core/network/impl/transactions_transmitter_impl.cpp b/core/network/impl/transactions_transmitter_impl.cpp index 18419c5de8..ef36fe68c7 100644 --- a/core/network/impl/transactions_transmitter_impl.cpp +++ b/core/network/impl/transactions_transmitter_impl.cpp @@ -20,6 +20,6 @@ namespace kagome::network { auto protocol = router_->getPropagateTransactionsProtocol(); BOOST_ASSERT_MSG(protocol, "Router did not provide propagate transactions protocol"); - protocol->propagateTransactions(std::move(txs)); + protocol->propagateTransactions(txs); } } // namespace kagome::network diff --git a/core/network/protobuf/CMakeLists.txt b/core/network/protobuf/CMakeLists.txt index b173323e98..4c08c2fbb7 100644 --- a/core/network/protobuf/CMakeLists.txt +++ b/core/network/protobuf/CMakeLists.txt @@ -7,21 +7,7 @@ add_proto_library(node_api_proto api.v1.proto ) -target_include_directories(node_api_proto PUBLIC - # required for common targets - $ - # required for compiling proto targets - $ - ) -kagome_install(node_api_proto) add_proto_library(light_api_proto light.v1.proto ) -target_include_directories(light_api_proto PUBLIC - # required for common targets - $ - # required for compiling proto targets - $ - ) -kagome_install(light_api_proto) diff --git a/core/network/types/block_attributes.hpp b/core/network/types/block_attributes.hpp index fe3a5ed129..dc985bd8d7 100644 --- a/core/network/types/block_attributes.hpp +++ b/core/network/types/block_attributes.hpp @@ -47,13 +47,13 @@ namespace kagome::network { return (l & r) == r; } - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &s, const BlockAttribute &v) { return s << static_cast(v); } - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &s, BlockAttribute &attributes) { uint8_t value = 0u; s >> value; diff --git a/core/network/types/roles.hpp b/core/network/types/roles.hpp index 1e11a4a38c..32b8c226f1 100644 --- a/core/network/types/roles.hpp +++ b/core/network/types/roles.hpp @@ -37,7 +37,7 @@ namespace kagome::network { }; inline std::string to_string(Roles r) { - switch (r.value) { + switch (r.value) { // NOLINT(cppcoreguidelines-pro-type-union-access) case 0: return "none"; case 1: @@ -47,6 +47,7 @@ namespace kagome::network { case 4: return "authority"; } - return to_string(r.value); + return to_string( + r.value); // NOLINT(cppcoreguidelines-pro-type-union-access) } } // namespace kagome::network diff --git a/core/network/types/state_response.hpp b/core/network/types/state_response.hpp index 7a7f0fb171..8fa2eb9af3 100644 --- a/core/network/types/state_response.hpp +++ b/core/network/types/state_response.hpp @@ -25,7 +25,7 @@ namespace kagome::network { /// A collection of keys-values. std::vector entries; /// Set to true when there are no more keys to return. - bool complete; + bool complete{}; }; /** diff --git a/core/network/warp/cache.cpp b/core/network/warp/cache.cpp index 49b3daf7fb..562a14a054 100644 --- a/core/network/warp/cache.cpp +++ b/core/network/warp/cache.cpp @@ -56,7 +56,7 @@ namespace kagome::network { storage::kWarpSyncCacheBlocksPrefix, db->getSpace(storage::Space::kDefault), }, - chain_sub_{chain_sub_engine}, + chain_sub_{std::move(chain_sub_engine)}, log_{log::createLogger("WarpSyncCache", "warp_sync_protocol")} { app_state_manager.takeControl(*this); } @@ -91,7 +91,8 @@ namespace kagome::network { OUTCOME_TRY(justification, scale::decode( raw_justification.data)); - WarpSyncFragment fragment{std::move(header), std::move(justification)}; + WarpSyncFragment fragment{.header = std::move(header), + .justification = std::move(justification)}; auto fragment_size = scale::encode(fragment).value().size(); if (fragment_size > size_limit) { res.is_finished = false; @@ -110,7 +111,8 @@ namespace kagome::network { scale::decode( raw_justification.data)); res.proofs.emplace_back( - WarpSyncFragment{std::move(header), std::move(justification)}); + WarpSyncFragment{.header = std::move(header), + .justification = std::move(justification)}); } return res; } diff --git a/core/network/warp/sync.cpp b/core/network/warp/sync.cpp index b7814b24b1..b33af39922 100644 --- a/core/network/warp/sync.cpp +++ b/core/network/warp/sync.cpp @@ -78,8 +78,7 @@ namespace kagome::network { auto &fragment = res.proofs[i]; // Calculate and save hash, 'cause it's just received response - primitives::calculateBlockHash( - const_cast(fragment.header), *hasher_); + primitives::calculateBlockHash(fragment.header, *hasher_); primitives::BlockInfo block_info = fragment.header.blockInfo(); if (fragment.justification.block_info != block_info) { @@ -99,10 +98,10 @@ namespace kagome::network { return; } Op op{ - block_info, - fragment.header, - fragment.justification, - *authorities, + .block_info = block_info, + .header = fragment.header, + .justification = fragment.justification, + .authorities = *authorities, }; db_->put(storage::kWarpSyncOp, scale::encode(op).value()).value(); applyInner(op); diff --git a/core/offchain/impl/http_request.cpp b/core/offchain/impl/http_request.cpp index 3fb01a19f2..0af2be4186 100644 --- a/core/offchain/impl/http_request.cpp +++ b/core/offchain/impl/http_request.cpp @@ -29,6 +29,7 @@ namespace kagome::offchain { bool HttpRequest::init(HttpMethod method, std::string_view uri_arg, + // NOLINTNEXTLINE(performance-unnecessary-value-param) common::Buffer meta) { uri_ = common::Uri::parse(uri_arg); if (uri_.error().has_value()) { @@ -116,7 +117,8 @@ namespace kagome::offchain { } } - auto resolve_handler = [wp{weak_from_this()}](const auto &ec, auto it) { + auto resolve_handler = [wp{weak_from_this()}](const auto &ec, + const auto &it) { if (auto self = wp.lock()) { if (self->status_ != 0) { SL_TRACE( @@ -157,7 +159,8 @@ namespace kagome::offchain { : boost::beast::get_lowest_layer( *boost::relaxed_get(stream_)); - auto connect_handler = [wp{weak_from_this()}](const auto &ec, auto it) { + auto connect_handler = [wp{weak_from_this()}](const auto &ec, + const auto &it) { if (auto self = wp.lock()) { if (self->status_ != 0) { SL_TRACE( @@ -395,11 +398,13 @@ namespace kagome::offchain { } } else { - request_.body().append(reinterpret_cast(chunk.data()), - chunk.size()); + request_.body().append( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + reinterpret_cast(chunk.data()), + chunk.size()); } - return Result(); + return Success(); } std::vector> diff --git a/core/offchain/impl/offchain_local_storage.cpp b/core/offchain/impl/offchain_local_storage.cpp index 6879b2415f..b05388cc2b 100644 --- a/core/offchain/impl/offchain_local_storage.cpp +++ b/core/offchain/impl/offchain_local_storage.cpp @@ -29,7 +29,7 @@ namespace kagome::offchain { } outcome::result OffchainLocalStorageImpl::set( - const common::BufferView &key, common::Buffer value) { + const common::BufferView &key, common::BufferOrView value) { // TODO(xDimon): // Need to implemented as soon as it will implemented in Substrate. // Specification in not enough to implement it now. diff --git a/core/offchain/impl/offchain_local_storage.hpp b/core/offchain/impl/offchain_local_storage.hpp index cd7777874d..b5a36ccb63 100644 --- a/core/offchain/impl/offchain_local_storage.hpp +++ b/core/offchain/impl/offchain_local_storage.hpp @@ -19,7 +19,7 @@ namespace kagome::offchain { std::shared_ptr storage); outcome::result set(const common::BufferView &key, - common::Buffer value) override; + common::BufferOrView value) override; outcome::result clear(const common::BufferView &key) override; diff --git a/core/offchain/impl/offchain_persistent_storage.cpp b/core/offchain/impl/offchain_persistent_storage.cpp index 4961f73fb6..4bb9ff7344 100644 --- a/core/offchain/impl/offchain_persistent_storage.cpp +++ b/core/offchain/impl/offchain_persistent_storage.cpp @@ -29,7 +29,7 @@ namespace kagome::offchain { } outcome::result OffchainPersistentStorageImpl::set( - const common::BufferView &key, common::Buffer value) { + const common::BufferView &key, common::BufferOrView value) { auto iKey = internalKey(key); std::lock_guard lg(mutex_); return storage_->put(iKey, std::move(value)); diff --git a/core/offchain/impl/offchain_persistent_storage.hpp b/core/offchain/impl/offchain_persistent_storage.hpp index 2c77ebddd1..fa9cbb6999 100644 --- a/core/offchain/impl/offchain_persistent_storage.hpp +++ b/core/offchain/impl/offchain_persistent_storage.hpp @@ -19,7 +19,7 @@ namespace kagome::offchain { std::shared_ptr storage); outcome::result set(const common::BufferView &key, - common::Buffer value) override; + common::BufferOrView value) override; outcome::result clear(const common::BufferView &key) override; diff --git a/core/offchain/impl/offchain_worker_impl.cpp b/core/offchain/impl/offchain_worker_impl.cpp index 45786a9e71..0ee71df57e 100644 --- a/core/offchain/impl/offchain_worker_impl.cpp +++ b/core/offchain/impl/offchain_worker_impl.cpp @@ -68,12 +68,13 @@ namespace kagome::offchain { SL_TRACE(log_, "Offchain worker with label {} is started", label); - func(); + std::move(func)(); SL_TRACE(log_, "Offchain worker with label {} is finished", label); } bool OffchainWorkerImpl::isValidator() const { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) bool isValidator = app_config_.roles().flags.authority == 1; return isValidator; } @@ -254,7 +255,7 @@ namespace kagome::offchain { } auto &request = it->second; - HttpStatus status; + HttpStatus status; // NOLINT(cppcoreguidelines-init-variables) while ((status = request->status()) == 0) { if (deadline.has_value() and (clock_->zero() + std::chrono::milliseconds(deadline.value())) diff --git a/core/offchain/offchain_storage.hpp b/core/offchain/offchain_storage.hpp index 91f74456cd..bc385cc6e7 100644 --- a/core/offchain/offchain_storage.hpp +++ b/core/offchain/offchain_storage.hpp @@ -8,7 +8,7 @@ #include -#include "common/buffer.hpp" +#include "common/buffer_or_view.hpp" #include "outcome/outcome.hpp" namespace kagome::offchain { @@ -28,7 +28,7 @@ namespace kagome::offchain { * @return success or error */ virtual outcome::result set(const common::BufferView &key, - common::Buffer value) = 0; + common::BufferOrView value) = 0; /** * @brief Remove a value from the local storage diff --git a/core/offchain/types.hpp b/core/offchain/types.hpp index 13b34a0fc4..e67a6dc4a5 100644 --- a/core/offchain/types.hpp +++ b/core/offchain/types.hpp @@ -94,13 +94,13 @@ namespace kagome::offchain { : peer_id(std::move(peer_id)), address(std::move(address)) {} OpaqueNetworkState() - : peer_id(libp2p::peer::PeerId::fromPublicKey( - libp2p::crypto::ProtobufKey{{}}) - .value()) {} + : peer_id( + libp2p::peer::PeerId::fromPublicKey(libp2p::crypto::ProtobufKey{{}}) + .value()) {} }; - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &s, const OpaqueNetworkState &v) { s << v.peer_id.toVector(); @@ -113,8 +113,8 @@ namespace kagome::offchain { return s; } - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &s, OpaqueNetworkState &v) { common::Buffer buff; diff --git a/core/parachain/approval/approval.cpp b/core/parachain/approval/approval.cpp index aca581e84c..0164f6f86f 100644 --- a/core/parachain/approval/approval.cpp +++ b/core/parachain/approval/approval.cpp @@ -43,14 +43,17 @@ namespace kagome::parachain::approval { consensus::babe::prepareTranscript( transcript, randomness, slot, epoch_index); + // NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-type-const-cast) if (Sr25519SignatureResult::SR25519_SIGNATURE_RESULT_OK != sr25519_vrf_compute_randomness( pubkey.data(), - (Strobe128 *)(transcript.data().data()), // NOLINT - (VRFCOutput *)&vrf_output.get().output, + const_cast( + reinterpret_cast(transcript.data().data())), + reinterpret_cast(&vrf_output.get().output), &vrf_story)) { return Error::ComputeRandomnessFailed; } + // NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-type-const-cast) return outcome::success(); } diff --git a/core/parachain/approval/approval_distribution.cpp b/core/parachain/approval/approval_distribution.cpp index 70215e98f3..4f98e6af87 100644 --- a/core/parachain/approval/approval_distribution.cpp +++ b/core/parachain/approval/approval_distribution.cpp @@ -93,13 +93,13 @@ namespace { std::unordered_map &assignments) { - using namespace kagome::parachain; - using namespace kagome; + using namespace kagome::parachain; // NOLINT(google-build-using-namespace) + using namespace kagome; // NOLINT(google-build-using-namespace) VRFCOutput cert_output; VRFCProof cert_proof; - uint32_t *cores; - uint64_t cores_out_sz; + uint32_t *cores; // NOLINT(cppcoreguidelines-init-variables) + uint64_t cores_out_sz; // NOLINT(cppcoreguidelines-init-variables) if (sr25519_relay_vrf_modulo_assignments_cert_v2( assignments_key.data(), @@ -114,6 +114,7 @@ namespace { &cores_out_sz)) { ::scale::BitVec assignment_bitfield; for (size_t ix = 0; ix < cores_out_sz; ++ix) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) const auto ci = cores[ix]; if (ci >= assignment_bitfield.bits.size()) { assignment_bitfield.bits.resize(ci + 1); @@ -145,6 +146,7 @@ namespace { .triggered = false}; for (size_t ix = 0; ix < cores_out_sz; ++ix) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) const auto core_index = cores[ix]; assignments.emplace(core_index, assignment); } @@ -163,8 +165,8 @@ namespace { std::unordered_map &assignments) { - using namespace kagome::parachain; - using namespace kagome; + using namespace kagome::parachain; // NOLINT(google-build-using-namespace) + using namespace kagome; // NOLINT(google-build-using-namespace) VRFCOutput cert_output; VRFCProof cert_proof; @@ -180,7 +182,7 @@ namespace { &cert_output, &cert_proof, &core)) { - if (assignments.count(core) > 0) { + if (assignments.contains(core)) { continue; } @@ -218,8 +220,8 @@ namespace { std::unordered_map &assignments) { - using namespace kagome::parachain; - using namespace kagome; + using namespace kagome::parachain; // NOLINT(google-build-using-namespace) + using namespace kagome; // NOLINT(google-build-using-namespace) VRFCOutput cert_output; VRFCProof cert_proof; @@ -253,8 +255,7 @@ namespace { .cert = approval::AssignmentCertV2{ .kind = approval::RelayVRFDelay{.core_index = core}, - .vrf = crypto::VRFOutput{.output = std::move(o), - .proof = std::move(p)}}, + .vrf = crypto::VRFOutput{.output = o, .proof = p}}, .tranche = tranche, .validator_index = validator_ix, .triggered = false}); @@ -296,11 +297,11 @@ namespace { size_t no_shows = 0ull; std::optional next_no_show{}; - if (auto i = std::lower_bound( - tranches.begin(), - tranches.end(), + if (auto i = std::ranges::lower_bound( + tranches, tranche, - [](const auto &te, const auto t) { return te.tranche < t; }); + std::less<>(), + &kagome::parachain::ApprovalDistribution::TrancheEntry::tranche); i != tranches.end() && i->tranche == tranche) { for (const auto &[v_index, t] : i->assignments) { if (v_index < n_validators) { @@ -330,7 +331,7 @@ namespace { s = s.advance( n_assignments, no_shows, next_no_show, last_assignment_tick); - const auto output = + auto output = s.output(tranche, needed_approvals, n_validators, no_show_duration); state = kagome::visit_in_place( @@ -395,9 +396,8 @@ namespace { if (n_approved + exact->tolerated_missing >= n_assigned) { return std::make_pair(exact->tolerated_missing, exact->last_assignment_tick); - } else { - return kagome::parachain::approval::Unapproved{}; } + return kagome::parachain::approval::Unapproved{}; } UNREACHABLE; } @@ -450,7 +450,7 @@ namespace { const RelayVRFStory &relay_vrf_story, const kagome::parachain::approval::AssignmentCertV2 &assignment, const std::vector &backing_groups) { - using namespace kagome; + using namespace kagome; // NOLINT(google-build-using-namespace) using parachain::ApprovalDistributionError; if (validator_index >= config.assignment_keys.size()) { @@ -533,6 +533,7 @@ namespace { return ApprovalDistributionError::VRF_DELAY_CORE_INDEX_MISMATCH; } + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) network::DelayTranche tranche; if (SR25519_SIGNATURE_RESULT_OK != sr25519_vrf_verify_and_get_tranche( @@ -580,7 +581,7 @@ namespace kagome::parachain { this, app_state_manager, approval_thread_pool, logger_)}, worker_pool_handler_{worker_thread_pool.handler(*app_state_manager)}, parachain_host_(std::move(parachain_host)), - slots_util_(std::move(slots_util)), + slots_util_(slots_util), keystore_(std::move(keystore)), hasher_(std::move(hasher)), config_(ApprovalVotingSubsystem{.slot_duration_millis = 6'000}), @@ -595,7 +596,7 @@ namespace kagome::parachain { pvf_(std::move(pvf)), recovery_(std::move(recovery)), main_pool_handler_{main_thread_pool.handler(*app_state_manager)}, - dispute_coordinator_{std::move(dispute_coordinator)}, + dispute_coordinator_{dispute_coordinator}, scheduler_{std::make_shared( std::make_shared( approval_thread_pool.io_context()), @@ -693,7 +694,7 @@ namespace kagome::parachain { } unify_with_peer(storedDistribBlockEntries(), peer_id, view, false); - peer_views_[peer_id] = std::move(view); + peer_views_[peer_id] = view; } void ApprovalDistribution::clearCaches( @@ -740,7 +741,7 @@ namespace kagome::parachain { crypto::KeyTypes::ASSIGNMENT, crypto::Sr25519PublicKey::fromSpan(pk).value()); res.has_value()) { - return std::make_pair((ValidatorIndex)ix, std::move(res.value())); + return std::make_pair((ValidatorIndex)ix, res.value()); } } return std::nullopt; @@ -900,10 +901,9 @@ namespace kagome::parachain { std::vector out; out.reserve(result.size()); - std::transform(result.begin(), - result.end(), - std::back_inserter(out), - [](const auto it) { return it.second; }); + std::ranges::transform(result, std::back_inserter(out), [](const auto &it) { + return it.second; + }); return out; } @@ -1256,10 +1256,8 @@ namespace kagome::parachain { OUTCOME_TRY(babe_config, babe_config_repo_->config(*block_header.parentInfo(), epoch)); - return std::make_tuple(epoch, - std::move(babe_header), - std::move(babe_config->authorities), - std::move(babe_config->randomness)); + return std::make_tuple( + epoch, babe_header, babe_config->authorities, babe_config->randomness); } outcome::result @@ -1270,10 +1268,10 @@ namespace kagome::parachain { for (auto &candidate : candidates) { if (auto obj{boost::get(&candidate)}) { - included.emplace_back(std::make_tuple( - HashedCandidateReceipt{std::move(obj->candidate_receipt)}, - obj->core_index, - obj->group_index)); + included.emplace_back( + std::make_tuple(HashedCandidateReceipt{obj->candidate_receipt}, + obj->core_index, + obj->group_index)); } } return included; @@ -1289,12 +1287,11 @@ namespace kagome::parachain { const ImportedBlockInfo &block_info) { std::vector> entries; std::vector> candidates; - if (auto blocks = storedBlocks().get_or_create(block_number); - blocks.get().find(block_hash) != blocks.get().end()) { + auto blocks = storedBlocks().get_or_create(block_number); + if (blocks.get().contains(block_hash)) { return entries; - } else { - blocks.get().insert(block_hash); } + blocks.get().insert(block_hash); entries.reserve(block_info.included_candidates.size()); candidates.reserve(block_info.included_candidates.size()); @@ -1332,7 +1329,7 @@ namespace kagome::parachain { .block_number = block_number, .session = block_info.session_index, .slot = block_info.slot, - .relay_vrf_story = std::move(block_info.relay_vrf_story), + .relay_vrf_story = block_info.relay_vrf_story, .candidates = std::move(candidates), .approved_bitfield = std::move(approved_bitfield), .distributed_assignments = {}, @@ -1501,18 +1498,18 @@ namespace kagome::parachain { SL_TRACE(self->logger_, "Processing pending assignment/approvals.(count={})", it->second.size()); - for (auto i = it->second.begin(); i != it->second.end(); ++i) { + for (auto &item : it->second) { visit_in_place( - i->second, + item.second, [&](const network::vstaging::Assignment &assignment) { self->import_and_circulate_assignment( - i->first, + item.first, assignment.indirect_assignment_cert, assignment.candidate_bitfield); }, [&](const network::vstaging::IndirectSignedApprovalVoteV2 &approval) { - self->import_and_circulate_approval(i->first, approval); + self->import_and_circulate_approval(item.first, approval); }); } it = self->pending_known_.erase(it); @@ -1530,7 +1527,7 @@ namespace kagome::parachain { const auto block_number = updated.new_head.number; auto parent_hash{updated.new_head.parent_hash}; - if (approving_context_map_.count(head) != 0ull) { + if (approving_context_map_.contains(head)) { logger_->warn("Approving {} already in progress.", head); return; // Error::ALREADY_APPROVING; } @@ -1549,8 +1546,8 @@ namespace kagome::parachain { block_hash{head}, block_number, finalized_block_number{updated.view.finalized_number_}, - parent_hash{std::move(parent_hash)}, - func(std::forward(func))]( + parent_hash, + func = std::forward(func)]( outcome::result &&block_info) mutable { auto self = wself.lock(); if (!self) { @@ -1831,7 +1828,7 @@ namespace kagome::parachain { v.bits[ci] = true; } - DelayTranche tranche; + DelayTranche tranche; // NOLINT(cppcoreguidelines-init-variables) if (auto res = checkAssignmentCert(v, assignment.validator, session_info, @@ -1888,17 +1885,17 @@ namespace kagome::parachain { if (is_duplicate) { return AssignmentCheckResult::AcceptedDuplicate; - } else if (approval::count_ones(candidate_indices) > 1) { + } + if (approval::count_ones(candidate_indices) > 1) { SL_TRACE(logger_, "Imported assignment for multiple cores. (validator={})", assignment.validator); return AssignmentCheckResult::Accepted; - } else { - SL_TRACE(logger_, - "Imported assignment for a single core. (validator={})", - assignment.validator); - return AssignmentCheckResult::Accepted; } + SL_TRACE(logger_, + "Imported assignment for a single core. (validator={})", + assignment.validator); + return AssignmentCheckResult::Accepted; } ApprovalDistribution::ApprovalCheckResult @@ -2287,9 +2284,8 @@ namespace kagome::parachain { std::get<2>(message_subject)); } - std::pair> - nar; - if (auto res = entry.note_approval(vote); res.has_error()) { + auto res = entry.note_approval(vote); + if (res.has_error()) { SL_WARN(logger_, "Possible bug: Vote import failed. (hash={}, validator_index={}, " "error={})", @@ -2297,9 +2293,8 @@ namespace kagome::parachain { validator_index, res.error()); return; - } else { - nar = std::move(res.value()); } + auto nar = std::move(res.value()); auto peer_filter = [&](const auto &peer, const auto &peer_kn) { const auto &[_, pr] = nar; @@ -2501,8 +2496,7 @@ namespace kagome::parachain { assignment.indirect_assignment_cert.block_hash, assignment.indirect_assignment_cert.validator, peer_id); - it->second.emplace_back( - std::make_pair(peer_id, PendingMessage{assignment})); + it->second.emplace_back(peer_id, PendingMessage{assignment}); continue; } @@ -2526,8 +2520,7 @@ namespace kagome::parachain { approval_vote.payload.payload.block_hash, approval_vote.payload.ix, peer_id); - it->second.emplace_back( - std::make_pair(peer_id, PendingMessage{approval_vote})); + it->second.emplace_back(peer_id, PendingMessage{approval_vote}); continue; } @@ -2564,7 +2557,7 @@ namespace kagome::parachain { .indirect_assignment_cert = indirect_cert, .candidate_bitfield = candidate_indices, }}}}), - [&](const libp2p::peer::PeerId &p) { return peers.count(p) != 0ull; }); + [&](const libp2p::peer::PeerId &p) { return peers.contains(p); }); } void ApprovalDistribution::send_assignments_batched( @@ -2683,7 +2676,7 @@ namespace kagome::parachain { network::vstaging::Approvals{ .approvals = {vote}, }}), - [&](const libp2p::peer::PeerId &p) { return peers.count(p) != 0ull; }); + [&](const libp2p::peer::PeerId &p) { return peers.contains(p); }); } void ApprovalDistribution::issue_approval(const CandidateHash &candidate_hash, @@ -2795,7 +2788,7 @@ namespace kagome::parachain { }, .ix = validator_index, }, - .signature = std::move(*sig), + .signature = *sig, }); /// TODO(iceseer): store state for the dispute @@ -2813,15 +2806,14 @@ namespace kagome::parachain { } static std::array kMagic{'A', 'P', 'P', 'R'}; auto d = std::make_tuple(kMagic, candidate_hash, session_index); - auto payload = scale::encode(std::move(d)).value(); + auto payload = scale::encode(d).value(); if (auto res = crypto_provider_->sign(key_pair.value(), payload); res.has_value()) { return res.value(); - } else { - logger_->warn("Unable to sign with {}", pubkey); - return std::nullopt; } + logger_->warn("Unable to sign with {}", pubkey); + return std::nullopt; } void ApprovalDistribution::runLaunchApproval( @@ -3010,6 +3002,7 @@ namespace kagome::parachain { auto no_shows = known_no_shows(check); if (no_shows != 0) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) metric_no_shows_total_->inc(no_shows); } @@ -3225,6 +3218,7 @@ namespace kagome::parachain { indirect_cert.cert.kind, candidate_hash, block_entry)) { if (auto claimed_candidate_indices = cores_to_candidate_indices( *claimed_core_indices, block_entry)) { + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) bool distribute_assignment; if (approval::count_ones(*claimed_candidate_indices) > 1) { distribute_assignment = !block_entry.mark_assignment_distributed( @@ -3283,7 +3277,7 @@ namespace kagome::parachain { } auto &entry = opt_entry->get(); - if (entry.known_by.count(peer_id) != 0ull && !retry_known_blocks) { + if (entry.known_by.contains(peer_id) and !retry_known_blocks) { break; } @@ -3374,7 +3368,7 @@ namespace kagome::parachain { auto &chain = chain_res.value(); BOOST_ASSERT(not chain.empty() and chain[0] == max.hash); BOOST_ASSERT(chain.size() == count); - std::reverse(chain.begin(), chain.end()); + std::ranges::reverse(chain); BOOST_ASSERT(chain[0] != min.hash); primitives::BlockInfo result = min; for (auto &hash : chain) { diff --git a/core/parachain/approval/approval_distribution.hpp b/core/parachain/approval/approval_distribution.hpp index 56d14f5404..0532933597 100644 --- a/core/parachain/approval/approval_distribution.hpp +++ b/core/parachain/approval/approval_distribution.hpp @@ -444,10 +444,9 @@ namespace kagome::parachain { const { std::vector out; out.reserve(approvals.size()); - std::transform(approvals.begin(), - approvals.end(), - std::back_inserter(out), - [](const auto it) { return it.second; }); + std::ranges::transform(approvals, + std::back_inserter(out), + [](const auto &it) { return it.second; }); return out; } diff --git a/core/parachain/availability/availability_chunk_index.hpp b/core/parachain/availability/availability_chunk_index.hpp index fef88a384c..8ed51a021f 100644 --- a/core/parachain/availability/availability_chunk_index.hpp +++ b/core/parachain/availability/availability_chunk_index.hpp @@ -46,7 +46,9 @@ namespace kagome::parachain { inline bool availability_chunk_mapping_is_enabled( std::optional node_features) { // none if node_features is not defined - [[unlikely]] if (not node_features.has_value()) { return false; } + [[unlikely]] if (not node_features.has_value()) { // + return false; + } const auto &features = node_features.value(); @@ -54,7 +56,9 @@ namespace kagome::parachain { runtime::ParachainHost::NodeFeatureIndex::AvailabilityChunkMapping; // none if needed feature is out of bound - [[unlikely]] if (feature >= features.bits.size()) { return false; } + [[unlikely]] if (feature >= features.bits.size()) { // + return false; + } return features.bits[feature]; } diff --git a/core/parachain/availability/fetch/fetch_impl.cpp b/core/parachain/availability/fetch/fetch_impl.cpp index 9dfc9ee18a..36dbdd0735 100644 --- a/core/parachain/availability/fetch/fetch_impl.cpp +++ b/core/parachain/availability/fetch/fetch_impl.cpp @@ -168,9 +168,11 @@ namespace kagome::parachain { auto &active = it->second; if (_chunk) { if (auto chunk2 = boost::get(&_chunk.value())) { - network::ErasureChunk chunk{std::move(chunk2->data), - active.chunk_index, - std::move(chunk2->proof)}; + network::ErasureChunk chunk{ + .chunk = std::move(chunk2->data), + .index = active.chunk_index, + .proof = std::move(chunk2->proof), + }; if (checkTrieProof(chunk, active.erasure_encoding_root)) { av_store_->putChunk( active.relay_parent, candidate_hash, std::move(chunk)); diff --git a/core/parachain/backing/cluster.cpp b/core/parachain/backing/cluster.cpp index 5e6e6b552b..512e3eb2f4 100644 --- a/core/parachain/backing/cluster.cpp +++ b/core/parachain/backing/cluster.cpp @@ -23,7 +23,9 @@ namespace kagome::parachain { return RejectIncoming::NotInGroup; } - if (they_sent(sender, SpecificKnowledge{statement, originator})) { + if (they_sent( + sender, + SpecificKnowledge{.statement = statement, .index = originator})) { return RejectIncoming::Duplicate; } @@ -111,8 +113,8 @@ namespace kagome::parachain { pending[cluster_member].insert({originator, statement}); } } - knowledge[sender].insert( - IncomingP2P{SpecificKnowledge{statement, originator}}); + knowledge[sender].insert(IncomingP2P{ + SpecificKnowledge{.statement = statement, .index = originator}}); if (auto *seconded = std::get_if(&statement)) { knowledge[sender].insert(IncomingP2P{GeneralKnowledge{*seconded}}); @@ -153,8 +155,8 @@ namespace kagome::parachain { void ClusterTracker::note_sent(ValidatorIndex target, ValidatorIndex originator, network::CompactStatement statement) { - knowledge[target].insert( - OutgoingP2P{SpecificKnowledge{statement, originator}}); + knowledge[target].insert(OutgoingP2P{ + SpecificKnowledge{.statement = statement, .index = originator}}); if (auto *seconded = std::get_if(&statement)) { knowledge[target].insert(OutgoingP2P{GeneralKnowledge{*seconded}}); @@ -233,7 +235,7 @@ namespace kagome::parachain { ValidatorIndex validator, ValidatorIndex originator, network::CompactStatement statement) const { - SpecificKnowledge knowledge{statement, originator}; + SpecificKnowledge knowledge{.statement = statement, .index = originator}; return we_sent(validator, knowledge) || they_sent(validator, knowledge); } diff --git a/core/parachain/backing/grid.hpp b/core/parachain/backing/grid.hpp index ade6476a10..71dfce074e 100644 --- a/core/parachain/backing/grid.hpp +++ b/core/parachain/backing/grid.hpp @@ -125,7 +125,7 @@ namespace kagome::parachain::grid { /// Routing mode struct RequiredRouting { - enum { + enum { // NOLINT(performance-enum-size) /// We don't know yet, because we're waiting for topology info /// (race condition between learning about the first blocks in a new /// session diff --git a/core/parachain/backing/grid_tracker.cpp b/core/parachain/backing/grid_tracker.cpp index 6545a888b4..5477072613 100644 --- a/core/parachain/backing/grid_tracker.cpp +++ b/core/parachain/backing/grid_tracker.cpp @@ -290,7 +290,7 @@ namespace kagome::parachain::grid { result.push_back(statement); } } - std::sort(result.begin(), result.end(), [](auto &a, auto &b) { + std::ranges::sort(result, [](auto &a, auto &b) { return visit_in_place( a.second.inner_value, [](const network::vstaging::SecondedCandidateHash &) { return true; }, @@ -551,19 +551,12 @@ namespace kagome::parachain::grid { auto &prev = it->second; if (prev.claimed_group_index != manifest_summary.claimed_group_index || prev.claimed_parent_hash != manifest_summary.claimed_parent_hash - || !std::includes( - manifest_summary.statement_knowledge.seconded_in_group.bits - .begin(), - manifest_summary.statement_knowledge.seconded_in_group.bits.end(), - prev.statement_knowledge.seconded_in_group.bits.begin(), - prev.statement_knowledge.seconded_in_group.bits.end()) - || !std::includes( - manifest_summary.statement_knowledge.validated_in_group.bits - .begin(), - manifest_summary.statement_knowledge.validated_in_group.bits - .end(), - prev.statement_knowledge.validated_in_group.bits.begin(), - prev.statement_knowledge.validated_in_group.bits.end())) { + || !std::ranges::includes( + manifest_summary.statement_knowledge.seconded_in_group.bits, + prev.statement_knowledge.seconded_in_group.bits) + || !std::ranges::includes( + manifest_summary.statement_knowledge.validated_in_group.bits, + prev.statement_knowledge.validated_in_group.bits)) { return GridTracker::Error::CONFLICTING; } auto fresh_seconded = diff --git a/core/parachain/backing/store_impl.cpp b/core/parachain/backing/store_impl.cpp index c3d477c296..4852e6e1bc 100644 --- a/core/parachain/backing/store_impl.cpp +++ b/core/parachain/backing/store_impl.cpp @@ -96,7 +96,7 @@ namespace kagome::parachain { } const CandidateHash digest = candidateHash(*hasher_, candidate); - bool new_proposal; + bool new_proposal; // NOLINT(cppcoreguidelines-init-variables) if (auto it = state.authority_data_.find(authority); it != state.authority_data_.end()) { auto &existing = it->second; @@ -107,12 +107,12 @@ namespace kagome::parachain { } new_proposal = false; } else if (allow_multiple_seconded - && std::find_if(existing.proposals.begin(), - existing.proposals.end(), - [&digest](const auto &hash_and_sig) { - const auto &[h, _] = hash_and_sig; - return h == digest; - }) + && std::ranges::find_if(existing.proposals.begin(), + existing.proposals.end(), + [&digest](const auto &hash_and_sig) { + const auto &[h, _] = hash_and_sig; + return h == digest; + }) != existing.proposals.end()) { new_proposal = false; } else { diff --git a/core/parachain/pvf/kagome_pvf_worker.cpp b/core/parachain/pvf/kagome_pvf_worker.cpp index e4a931331f..04bff5349f 100644 --- a/core/parachain/pvf/kagome_pvf_worker.cpp +++ b/core/parachain/pvf/kagome_pvf_worker.cpp @@ -34,18 +34,20 @@ #include "common/bytestr.hpp" #include "log/configurator.hpp" #include "log/logger.hpp" +#include "parachain/pvf/kagome_pvf_worker.hpp" #include "parachain/pvf/kagome_pvf_worker_injector.hpp" #include "parachain/pvf/pvf_worker_types.hpp" -#include "scale/scale.hpp" -#include "utils/spdlog_stderr.hpp" - -#include "parachain/pvf/kagome_pvf_worker.hpp" #include "parachain/pvf/secure_mode.hpp" #include "runtime/binaryen/module/module_factory_impl.hpp" #include "runtime/module_instance.hpp" #include "runtime/runtime_context.hpp" #include "runtime/wabt/instrument.hpp" +#include "runtime/wasm_compiler_definitions.hpp" // this header-file is generated +#include "scale/scale.hpp" #include "utils/mkdirs.hpp" +#include "utils/spdlog_stderr.hpp" + +// NOLINTBEGIN(cppcoreguidelines-pro-type-vararg,hicpp-vararg) // rust reference: polkadot-sdk/polkadot/node/core/pvf/execute-worker/src/lib.rs @@ -60,7 +62,10 @@ } namespace kagome::parachain { - static kagome::log::Logger logger; + namespace { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) + static kagome::log::Logger logger; + } // namespace bool checkEnvVarsEmpty(const char **env) { return env != nullptr; @@ -144,9 +149,7 @@ namespace kagome::parachain { LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_WRITE_FILE | LANDLOCK_ACCESS_FS_MAKE_REG}; - int abi{}; - - abi = ::syscall( + auto abi = ::syscall( SYS_landlock_create_ruleset, NULL, 0, LANDLOCK_CREATE_RULESET_VERSION); if (abi < 0) { return getLastErr("landlock_create_ruleset"); @@ -174,14 +177,14 @@ namespace kagome::parachain { #endif }; - int ruleset_fd{}; - - ruleset_fd = ::syscall( + auto ruleset_fd = ::syscall( SYS_landlock_create_ruleset, &ruleset_attr, sizeof(ruleset_attr), 0); if (ruleset_fd < 0) { return getLastErr("landlock_create_ruleset"); } - libp2p::common::FinalAction cleanup = [ruleset_fd]() { close(ruleset_fd); }; + libp2p::common::FinalAction cleanup = [ruleset_fd]() { + close(ruleset_fd); // NOLINT(cppcoreguidelines-narrowing-conversions) + }; for (auto &[path, access_flags] : allowed_exceptions) { struct landlock_path_beneath_attr path_beneath = { @@ -203,13 +206,13 @@ namespace kagome::parachain { } } - if (::prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) - == -1) { // NOLINT(cppcoreguidelines-pro-type-vararg) + if (::prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == -1) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) ::close(ruleset_fd); return getLastErr("prctl PR_SET_NO_NEW_PRIVS"); } - if (::syscall(SYS_landlock_restrict_self, ruleset_fd, 0)) { + if (::syscall(SYS_landlock_restrict_self, ruleset_fd, 0) != 0) { return getLastErr("landlock_restrict_self"); } @@ -218,7 +221,11 @@ namespace kagome::parachain { #endif outcome::result readStdin(std::span out) { - std::cin.read(reinterpret_cast(out.data()), out.size()); + std::cin.read( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + reinterpret_cast(out.data()), + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) + out.size()); if (not std::cin.good()) { return std::errc::io_error; } @@ -227,6 +234,7 @@ namespace kagome::parachain { template outcome::result decodeInput() { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init,hicpp-member-init) std::array length_bytes; OUTCOME_TRY(readStdin(length_bytes)); OUTCOME_TRY(message_length, scale::decode(length_bytes)); @@ -350,8 +358,17 @@ namespace kagome::parachain { instance->callExportFunction(ctx, "validate_block", input_args)); OUTCOME_TRY(instance->resetEnvironment()); OUTCOME_TRY(len, scale::encode(result.size())); - std::cout.write((const char *)len.data(), len.size()); - std::cout.write((const char *)result.data(), result.size()); + + std::cout.write( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + reinterpret_cast(len.data()), + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) + len.size()); + std::cout.write( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + reinterpret_cast(result.data()), + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) + result.size()); std::cout.flush(); } } @@ -385,3 +402,5 @@ namespace kagome::parachain { return EXIT_SUCCESS; } } // namespace kagome::parachain + +// NOLINTEND(cppcoreguidelines-pro-type-vararg,hicpp-vararg) diff --git a/core/parachain/pvf/kagome_pvf_worker_injector.hpp b/core/parachain/pvf/kagome_pvf_worker_injector.hpp index e3339e3fd3..9893aa1336 100644 --- a/core/parachain/pvf/kagome_pvf_worker_injector.hpp +++ b/core/parachain/pvf/kagome_pvf_worker_injector.hpp @@ -27,6 +27,7 @@ #include "runtime/common/runtime_properties_cache_impl.hpp" #include "runtime/memory_provider.hpp" #include "runtime/module.hpp" +#include "runtime/wasm_compiler_definitions.hpp" // this header-file is generated #include "storage/trie/serialization/trie_serializer_impl.hpp" #include "storage/trie/trie_storage.hpp" diff --git a/core/parachain/pvf/module_precompiler.cpp b/core/parachain/pvf/module_precompiler.cpp index 83b2ebfd7e..cf30da2112 100644 --- a/core/parachain/pvf/module_precompiler.cpp +++ b/core/parachain/pvf/module_precompiler.cpp @@ -26,9 +26,9 @@ namespace kagome::parachain { std::shared_ptr pvf_pool, std::shared_ptr hasher) : config_{config}, - parachain_api_{parachain_api}, + parachain_api_{std::move(parachain_api)}, pvf_pool_{std::move(pvf_pool)}, - hasher_{hasher} { + hasher_{std::move(hasher)} { if (getThreadsNum() > std::thread::hardware_concurrency() - 1) { SL_WARN( log_, @@ -40,9 +40,9 @@ namespace kagome::parachain { struct ModulePrecompiler::PrecompilationStats { const size_t total_count{}; - std::atomic_int occupied_precompiled_count{}; - std::atomic_int scheduled_precompiled_count{}; - std::atomic_int total_code_size{}; + std::atomic_size_t occupied_precompiled_count{}; + std::atomic_size_t scheduled_precompiled_count{}; + std::atomic_size_t total_code_size{}; }; std::optional get_para_id(runtime::CoreState core) { @@ -149,8 +149,8 @@ namespace kagome::parachain { auto &core = _core.state; if (std::holds_alternative(core)) { return outcome::success(); - - } else if (std::holds_alternative(core)) { + } + if (std::holds_alternative(core)) { SL_TRACE(log_, "Precompile for occupied availability core"); stats.occupied_precompiled_count++; } else if (std::holds_alternative(core)) { diff --git a/core/parachain/pvf/pool.cpp b/core/parachain/pvf/pool.cpp index d5780773f0..2c64b76eb9 100644 --- a/core/parachain/pvf/pool.cpp +++ b/core/parachain/pvf/pool.cpp @@ -12,35 +12,38 @@ #include "runtime/common/uncompress_code_if_needed.hpp" namespace kagome::parachain { - inline auto &metric_pvf_preparation_time() { - static metrics::HistogramTimer metric{ - "kagome_pvf_preparation_time", - "Time spent in preparing PVF artifacts in seconds", - { - 0.1, - 0.5, - 1.0, - 2.0, - 3.0, - 10.0, - 20.0, - 30.0, - 60.0, - 120.0, - 240.0, - 360.0, - 480.0, - }, - }; - return metric; - } + namespace { + inline auto &metric_pvf_preparation_time() { + static metrics::HistogramTimer metric{ + "kagome_pvf_preparation_time", + "Time spent in preparing PVF artifacts in seconds", + { + 0.1, + 0.5, + 1.0, + 2.0, + 3.0, + 10.0, + 20.0, + 30.0, + 60.0, + 120.0, + 240.0, + 360.0, + 480.0, + }, + }; + return metric; + } - metrics::HistogramHelper metric_code_size{ - "kagome_parachain_candidate_validation_code_size", - "The size of the decompressed WASM validation blob used for checking a " - "candidate", - metrics::exponentialBuckets(16384, 2, 10), - }; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) + metrics::HistogramHelper metric_code_size{ + "kagome_parachain_candidate_validation_code_size", + "The size of the decompressed WASM validation blob used for checking a " + "candidate", + metrics::exponentialBuckets(16384, 2, 10), + }; + } // namespace PvfPool::PvfPool(const application::AppConfiguration &app_config, std::shared_ptr module_factory, @@ -60,6 +63,7 @@ namespace kagome::parachain { code_hash, [&]() mutable -> runtime::RuntimeCodeProvider::Result { OUTCOME_TRY(code, runtime::uncompressCodeIfNeeded(code_zstd)); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) metric_code_size.observe(code.size()); return std::make_shared(code); }, diff --git a/core/parachain/pvf/precheck.cpp b/core/parachain/pvf/precheck.cpp index e1f26683c1..ad278e318f 100644 --- a/core/parachain/pvf/precheck.cpp +++ b/core/parachain/pvf/precheck.cpp @@ -111,10 +111,10 @@ namespace kagome::parachain { accepted = res.has_value(); } PvfCheckStatement statement{ - *accepted, - code_hash, - signer->getSessionIndex(), - signer->validatorIndex(), + .accept = accepted.value(), + .subject = code_hash, + .session_index = signer->getSessionIndex(), + .validator_index = signer->validatorIndex(), }; OUTCOME_TRY(signature, signer->signRaw(statement.signable())); offchain_worker_pool_->addWorker(offchain_worker_factory_->make()); diff --git a/core/parachain/pvf/pvf_impl.cpp b/core/parachain/pvf/pvf_impl.cpp index 072bcc6124..2726d00b23 100644 --- a/core/parachain/pvf/pvf_impl.cpp +++ b/core/parachain/pvf/pvf_impl.cpp @@ -29,6 +29,7 @@ #include "runtime/runtime_code_provider.hpp" #include "runtime/runtime_context.hpp" #include "runtime/runtime_instances_pool.hpp" +#include "runtime/wasm_compiler_definitions.hpp" // this header-file is generated #include "scale/std_variant.hpp" #define _CB_TRY_VOID(tmp, expr) \ @@ -81,6 +82,7 @@ namespace kagome::parachain { using primitives::BlockNumber; using runtime::PersistedValidationData; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) metrics::HistogramTimer metric_pvf_execution_time{ "kagome_pvf_execution_time", "Time spent in executing PVFs", @@ -116,18 +118,17 @@ namespace kagome::parachain { if (app_conf.runtimeInterpreter() == application::AppConfiguration::RuntimeInterpreter::WasmEdge) { return RuntimeEngine::kWasmEdgeInterpreted; - } else { - return RuntimeEngine::kBinaryen; } - } else { // Execution method Compiled while WasmEdge is compile-enabled - return RuntimeEngine::kWasmEdgeCompiled; + return RuntimeEngine::kBinaryen; } + // Execution method Compiled while WasmEdge is compile-enabled + return RuntimeEngine::kWasmEdgeCompiled; + #else if (interpreted) { // WasmEdge is compile-disabled return RuntimeEngine::kBinaryen; - } else { - return RuntimeEngine::kWAVM; } + return RuntimeEngine::kWAVM; #endif } @@ -136,7 +137,7 @@ namespace kagome::parachain { HeadData parent_head; ParachainBlock block_data; - BlockNumber relay_parent_number; + BlockNumber relay_parent_number{}; Hash256 relay_parent_storage_root; }; @@ -179,6 +180,7 @@ namespace kagome::parachain { }; SL_INFO(log_, "pvf runtime engine {}", + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) engines[fmt::underlying(pvf_runtime_engine(*app_configuration_))]); } @@ -342,14 +344,15 @@ namespace kagome::parachain { return cb(executor_->call(ctx, name, params)); } workers_->execute({ - pvf_pool_->getCachePath(code_hash, executor_params), - scale::encode(params).value(), - [cb{std::move(cb)}](outcome::result r) { - if (r.has_error()) { - return cb(r.error()); - } - cb(scale::decode(r.value())); - }, + .code_path = pvf_pool_->getCachePath(code_hash, executor_params), + .args = scale::encode(params).value(), + .cb = + [cb{std::move(cb)}](outcome::result r) { + if (r.has_error()) { + return cb(r.error()); + } + cb(scale::decode(r.value())); + }, }); } diff --git a/core/parachain/pvf/secure_mode_precheck.cpp b/core/parachain/pvf/secure_mode_precheck.cpp index 00f4d48e21..39801d7487 100644 --- a/core/parachain/pvf/secure_mode_precheck.cpp +++ b/core/parachain/pvf/secure_mode_precheck.cpp @@ -75,10 +75,11 @@ namespace kagome::parachain { namespace process_v2 = boost::process::v2; boost::asio::readable_pipe pipe{io_context}; // input passed as CLI arguments to enable users to manually run the check - process_v2::process process{io_context, - exePath().c_str(), - {"check-secure-mode", cache_dir.c_str()}, - process_v2::process_stdio{{}, pipe, {}}}; + process_v2::process process{ + io_context, + exePath().c_str(), + {"check-secure-mode", cache_dir.c_str()}, + process_v2::process_stdio{.in = {}, .out = pipe, .err = {}}}; Buffer output; boost::system::error_code ec; boost::asio::read(pipe, boost::asio::dynamic_buffer(output), ec); @@ -112,6 +113,7 @@ namespace kagome::parachain { } kagome::log::setLoggingSystem(logging_system); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) auto result = checkSecureMode(std::filesystem::path{argv[2]}); auto enc_result = scale::encode(result); if (!enc_result) { @@ -120,6 +122,7 @@ namespace kagome::parachain { return EXIT_FAILURE; } std::cout.write(qtils::byte2str(enc_result.value().data()), + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) enc_result.value().size()); return 0; } diff --git a/core/parachain/pvf/workers.cpp b/core/parachain/pvf/workers.cpp index 3efe41ad28..ec0ba616a1 100644 --- a/core/parachain/pvf/workers.cpp +++ b/core/parachain/pvf/workers.cpp @@ -121,10 +121,10 @@ namespace kagome::parachain { max_{app_config.pvfMaxWorkers()}, timeout_{app_config.pvfSubprocessDeadline()}, worker_config_{ - pvf_runtime_engine(app_config), - app_config.runtimeCacheDirPath(), - app_config.log(), - app_config.disableSecureMode(), + .engine = pvf_runtime_engine(app_config), + .cache_dir = app_config.runtimeCacheDirPath(), + .log_params = app_config.log(), + .force_disable_secure_mode = app_config.disableSecureMode(), } {} void PvfWorkers::execute(Job &&job) { @@ -155,10 +155,9 @@ namespace kagome::parachain { } void PvfWorkers::findFree(Job &&job) { - auto it = - std::find_if(free_.begin(), free_.end(), [&](const Worker &worker) { - return worker.code_path == job.code_path; - }); + auto it = std::ranges::find_if(free_, [&](const Worker &worker) { + return worker.code_path == job.code_path; + }); if (it == free_.end()) { it = free_.begin(); } diff --git a/core/parachain/validator/backing_implicit_view.cpp b/core/parachain/validator/backing_implicit_view.cpp index bc614c69c4..09c9c509a2 100644 --- a/core/parachain/validator/backing_implicit_view.cpp +++ b/core/parachain/validator/backing_implicit_view.cpp @@ -118,9 +118,9 @@ namespace kagome::parachain { std::vector relevant_paras; relevant_paras.reserve(min_relay_parents_raw.size()); - for (size_t i = 0; i < min_relay_parents_raw.size(); ++i) { - min_min = std::min(min_relay_parents_raw[i].second, min_min); - relevant_paras.emplace_back(min_relay_parents_raw[i].first); + for (auto &min_relay_parent : min_relay_parents_raw) { + min_min = std::min(min_relay_parent.second, min_min); + relevant_paras.emplace_back(min_relay_parent.first); } const size_t expected_ancestry_len = diff --git a/core/parachain/validator/fragment_tree.hpp b/core/parachain/validator/fragment_tree.hpp index faa999971e..546bd6eb3e 100644 --- a/core/parachain/validator/fragment_tree.hpp +++ b/core/parachain/validator/fragment_tree.hpp @@ -415,12 +415,12 @@ namespace kagome::parachain::fragment { Option candidateChild( const CandidateHash &candidate_hash) const { - auto it = - std::find_if(children.begin(), - children.end(), - [&](const std::pair &p) { - return p.second == candidate_hash; - }); + auto it = std::ranges::find_if( + children.begin(), + children.end(), + [&](const std::pair &p) { + return p.second == candidate_hash; + }); if (it != children.end()) { return it->first; } @@ -465,11 +465,12 @@ namespace kagome::parachain::fragment { Option> getPendingAvailability(const CandidateHash &candidate_hash) const { - auto it = std::find_if(pending_availability.begin(), - pending_availability.end(), - [&](const PendingAvailability &c) { - return c.candidate_hash == candidate_hash; - }); + auto it = + std::ranges::find_if(pending_availability.begin(), + pending_availability.end(), + [&](const PendingAvailability &c) { + return c.candidate_hash == candidate_hash; + }); if (it != pending_availability.end()) { return {{*it}}; } @@ -872,13 +873,13 @@ namespace kagome::parachain::fragment { || is_type(nodes.back().parent)) { nodes.emplace_back(std::move(node)); } else { - nodes.insert( - std::find_if(nodes.begin(), + nodes.insert(std::ranges::find_if( + nodes.begin(), nodes.end(), [](const auto &item) { return !is_type(item.parent); }), - std::move(node)); + std::move(node)); } }, [&](const NodePointerStorage &ptr) { diff --git a/core/parachain/validator/impl/fragment_tree.cpp b/core/parachain/validator/impl/fragment_tree.cpp index 06efe17f65..ad44105256 100644 --- a/core/parachain/validator/impl/fragment_tree.cpp +++ b/core/parachain/validator/impl/fragment_tree.cpp @@ -69,25 +69,26 @@ namespace kagome::parachain::fragment { for (const auto &ancestor : ancestors) { if (prev == 0) { return Scope::Error::UNEXPECTED_ANCESTOR; - } else if (ancestor.number != prev - 1) { + } + if (ancestor.number != prev - 1) { return Scope::Error::UNEXPECTED_ANCESTOR; - } else if (prev == base_constraints.min_relay_parent_number) { + } + if (prev == base_constraints.min_relay_parent_number) { break; - } else { - prev = ancestor.number; - ancestors_by_hash.emplace(ancestor.hash, ancestor); - ancestors_map.emplace(ancestor.number, ancestor); } + prev = ancestor.number; + ancestors_by_hash.emplace(ancestor.hash, ancestor); + ancestors_map.emplace(ancestor.number, ancestor); } return Scope{ - para, - relay_parent, - ancestors_map, - ancestors_by_hash, - pending_availability, - base_constraints, - max_depth, + .para = para, + .relay_parent = relay_parent, + .ancestors = ancestors_map, + .ancestors_by_hash = ancestors_by_hash, + .pending_availability = pending_availability, + .base_constraints = base_constraints, + .max_depth = max_depth, }; } @@ -215,17 +216,17 @@ namespace kagome::parachain::fragment { if (modifications.dmp_messages_processed > new_constraint.dmp_remaining_messages.size()) { return Error::DMP_MESSAGE_UNDERFLOW; - } else { - new_constraint.dmp_remaining_messages.erase( - new_constraint.dmp_remaining_messages.begin(), - new_constraint.dmp_remaining_messages.begin() - + modifications.dmp_messages_processed); } + new_constraint.dmp_remaining_messages.erase( + new_constraint.dmp_remaining_messages.begin(), + new_constraint.dmp_remaining_messages.begin() + + modifications.dmp_messages_processed); + if (modifications.code_upgrade_applied) { if (auto new_code = std::move(new_constraint.future_validation_code)) { BOOST_ASSERT(!new_constraint.future_validation_code); - new_constraint.validation_code_hash = std::move(new_code->second); + new_constraint.validation_code_hash = new_code->second; } else { return Error::APPLIED_NONEXISTENT_CODE_UPGRADE; } diff --git a/core/parachain/validator/impl/parachain_observer_impl.cpp b/core/parachain/validator/impl/parachain_observer_impl.cpp index a035e976bf..4495ec5ec4 100644 --- a/core/parachain/validator/impl/parachain_observer_impl.cpp +++ b/core/parachain/validator/impl/parachain_observer_impl.cpp @@ -46,13 +46,13 @@ namespace kagome::parachain { std::move(collation_msg), [&](network::CollatorDeclaration &&collation_decl) { onDeclare(peer_id, - std::move(collation_decl.collator_id), - std::move(collation_decl.para_id), - std::move(collation_decl.signature)); + collation_decl.collator_id, + collation_decl.para_id, + collation_decl.signature); }, [&](network::CollatorAdvertisement &&collation_adv) { onAdvertise(peer_id, - std::move(collation_adv.relay_parent), + collation_adv.relay_parent, std::nullopt, network::CollationVersion::V1); }, @@ -69,19 +69,18 @@ namespace kagome::parachain { [&](kagome::network::vstaging::CollatorProtocolMessageDeclare &&collation_decl) { onDeclare(peer_id, - std::move(collation_decl.collator_id), - std::move(collation_decl.para_id), - std::move(collation_decl.signature)); + collation_decl.collator_id, + collation_decl.para_id, + collation_decl.signature); }, [&](kagome::network::vstaging:: CollatorProtocolMessageAdvertiseCollation &&collation_adv) { onAdvertise( peer_id, - std::move(collation_adv.relay_parent), - std::make_pair( - std::move(collation_adv.candidate_hash), - std::move(collation_adv.parent_head_data_hash)), + collation_adv.relay_parent, + std::make_pair(collation_adv.candidate_hash, + collation_adv.parent_head_data_hash), network::CollationVersion::VStaging); }, [&](auto &&) { @@ -117,6 +116,7 @@ namespace kagome::parachain { outcome::result ParachainObserverImpl::OnPovRequest( network::RequestPov request) { + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) return processor_->getPov(std::move(request)); } diff --git a/core/parachain/validator/impl/parachain_processor.cpp b/core/parachain/validator/impl/parachain_processor.cpp index 92cccfa14c..03ac28fd66 100644 --- a/core/parachain/validator/impl/parachain_processor.cpp +++ b/core/parachain/validator/impl/parachain_processor.cpp @@ -43,7 +43,6 @@ auto name = (op); \ if (!name) { \ return; \ - } else { \ } #endif // TRY_GET_OR_RET @@ -180,7 +179,7 @@ namespace kagome::parachain { per_session_(RefCache::create()), peer_use_count_( std::make_shared()), - slots_util_(std::move(slots_util)), + slots_util_(slots_util), babe_config_repo_(std::move(babe_config_repo)), chain_sub_{std::move(chain_sub_engine)}, worker_pool_handler_{worker_thread_pool.handler(app_state_manager)}, @@ -924,13 +923,13 @@ namespace kagome::parachain { ParachainProcessorImpl::PerSessionState::PerSessionState( SessionIndex _session, - const runtime::SessionInfo &_session_info, + runtime::SessionInfo _session_info, Groups &&_groups, grid::Views &&_grid_view, ValidatorIndex _our_index, std::shared_ptr peers) : session{_session}, - session_info{_session_info}, + session_info{std::move(_session_info)}, groups{std::move(_groups)}, grid_view{std::move(_grid_view)}, our_index{_our_index}, @@ -1383,7 +1382,7 @@ namespace kagome::parachain { return network::PendingCollationFetch{ .collation_event = std::move(collation_event), - .candidate_receipt = std::move(value.receipt), + .candidate_receipt = value.receipt, .pov = std::move(value.pov), .maybe_parent_head_data = std::nullopt, }; @@ -1409,7 +1408,7 @@ namespace kagome::parachain { return network::PendingCollationFetch{ .collation_event = std::move(collation_event), - .candidate_receipt = std::move(value.receipt), + .candidate_receipt = value.receipt, .pov = std::move(value.pov), .maybe_parent_head_data = std::move(value.parent_head_data), }; @@ -1750,13 +1749,14 @@ namespace kagome::parachain { }(); se->forEachPeer(protocol, [&](const network::PeerId &peer) { - if (group_set.count(peer) == 0) { + if (not group_set.contains(peer)) { any.emplace_back(peer); } }); auto lucky = kMinGossipPeers - std::min(group.size(), kMinGossipPeers); if (lucky != 0) { std::shuffle(any.begin(), any.end(), random_); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) any.erase(any.begin() + std::min(any.size(), lucky), any.end()); } else { any.clear(); @@ -1901,14 +1901,12 @@ namespace kagome::parachain { switch (version) { case network::CollationVersion::VStaging: { - messages.emplace_back(network::VersionedValidatorProtocolMessage{ - network::vstaging::ValidatorProtocolMessage{ - network::vstaging::StatementDistributionMessage{ - network::vstaging:: - StatementDistributionMessageStatement{ - .relay_parent = relay_parent, - .compact = statement, - }}}}); + messages.emplace_back(network::vstaging::ValidatorProtocolMessage{ + network::vstaging::StatementDistributionMessage{ + network::vstaging::StatementDistributionMessageStatement{ + .relay_parent = relay_parent, + .compact = statement, + }}}); } break; default: { SL_ERROR( @@ -2376,7 +2374,7 @@ namespace kagome::parachain { const auto is_confirmed = candidates_.is_confirmed(candidate_hash); CHECK_OR_RET(relay_parent_state.local_validator); - enum DirectTargetKind { + enum DirectTargetKind : uint8_t { Cluster, Grid, }; @@ -2421,11 +2419,9 @@ namespace kagome::parachain { relay_parent_state.per_session_state->value().groups, originator, compact_statement)) { - const auto can_use_grid = - !cluster_relevant - || std::find( - all_cluster_targets.begin(), all_cluster_targets.end(), v) - == all_cluster_targets.end(); + const auto can_use_grid = !cluster_relevant + || std::ranges::find(all_cluster_targets, v) + == all_cluster_targets.end(); if (!can_use_grid) { continue; } @@ -3128,10 +3124,7 @@ namespace kagome::parachain { candidate_hash, peer_id); self->validateAsync( - std::move(candidate), - std::move(*p), - std::move(pvd), - relay_parent); + candidate, std::move(*p), std::move(pvd), relay_parent); }); } } @@ -3174,48 +3167,39 @@ namespace kagome::parachain { } auto &active = local_validator->active; - auto [validator_id, is_cluster] = - [&]() -> std::pair, bool> { - std::optional validator_id; - bool is_cluster = false; - - do { - auto audi = query_audi_->get(peer_id); - if (!audi) { - SL_TRACE(logger_, "No audi. (peer={})", peer_id); - break; - } - - ValidatorIndex v = 0; - for (; v < session_info.discovery_keys.size(); ++v) { - if (session_info.discovery_keys[v] == *audi) { - SL_TRACE(logger_, - "Captured validator. (relay_parent={}, candidate_hash={})", - confirmed->get().relay_parent(), - request.candidate_hash); - break; - } - } + std::optional validator_id; + bool is_cluster; // NOLINT(cppcoreguidelines-init-variables) + [&] { + auto audi = query_audi_->get(peer_id); + if (not audi.has_value()) { + SL_TRACE(logger_, "No audi. (peer={})", peer_id); + return; + } - if (v >= session_info.discovery_keys.size()) { + ValidatorIndex v = 0; + for (; v < session_info.discovery_keys.size(); ++v) { + if (session_info.discovery_keys[v] == audi.value()) { + SL_TRACE(logger_, + "Captured validator. (relay_parent={}, candidate_hash={})", + confirmed->get().relay_parent(), + request.candidate_hash); break; } + } - if (active - && active->cluster_tracker.can_request(v, request.candidate_hash)) { - validator_id = v; - is_cluster = true; - break; - } + if (v >= session_info.discovery_keys.size()) { + return; + } - if (local_validator->grid_tracker.can_request(v, - request.candidate_hash)) { - validator_id = v; - break; - } - } while (false); + if (active + and active->cluster_tracker.can_request(v, request.candidate_hash)) { + validator_id = v; + is_cluster = true; - return {validator_id, is_cluster}; + } else if (local_validator->grid_tracker.can_request( + v, request.candidate_hash)) { + validator_id = v; + } }(); if (!validator_id) { @@ -3731,13 +3715,11 @@ namespace kagome::parachain { return backing_store_->get(relay_parent); } - BlockNumber block_number; - if (auto r = get_block_number_under_construction(relay_parent); - r.has_error()) { + auto r = get_block_number_under_construction(relay_parent); + if (r.has_error()) { return {}; - } else { - block_number = r.value(); } + BlockNumber block_number = r.value(); using Ancestors = std::unordered_set; const auto &availability_cores = @@ -3885,9 +3867,8 @@ namespace kagome::parachain { if (candidate.candidate.commitments.opt_para_runtime) { if (with_validation_code) { break; - } else { - with_validation_code = true; } + with_validation_code = true; } merged_candidates.emplace_back(candidate); @@ -3928,14 +3909,14 @@ namespace kagome::parachain { validity_vote, [](const BackingStore::ValidityVoteIssued &val) { return network::ValidityAttestation{ - network::ValidityAttestation::Implicit{}, - ((ValidatorSignature &)val), + .kind = network::ValidityAttestation::Implicit{}, + .signature = ((ValidatorSignature &)val), }; }, [](const BackingStore::ValidityVoteValid &val) { return network::ValidityAttestation{ - network::ValidityAttestation::Explicit{}, - ((ValidatorSignature &)val), + .kind = network::ValidityAttestation::Explicit{}, + .signature = ((ValidatorSignature &)val), }; }); @@ -3973,9 +3954,9 @@ namespace kagome::parachain { const auto v_threshold = std::min(len, size_t(minimum_backing_votes)); return attested(data.candidate, data, v_threshold); - } else { - SL_TRACE(logger_, "No candidate info. (relay_parent={})", relay_parent); } + + SL_TRACE(logger_, "No candidate info. (relay_parent={})", relay_parent); return std::nullopt; } @@ -4019,9 +4000,9 @@ namespace kagome::parachain { return std::nullopt; } } - std::sort(vote_positions.begin(), - vote_positions.end(), - [](const auto &l, const auto &r) { return l.second < r.second; }); + std::ranges::sort(vote_positions, [](const auto &l, const auto &r) { + return l.second < r.second; + }); std::vector validity_votes; validity_votes.reserve(vote_positions.size()); @@ -4435,7 +4416,7 @@ namespace kagome::parachain { /// TODO(iceseer): /// https://github.com/paritytech/polkadot/blob/master/primitives/src/v2/mod.rs#L1535-L1545 auto sign_result = - parachain_state.table_context.validator->sign(std::move(payload)); + parachain_state.table_context.validator->sign(std::forward(payload)); if (sign_result.has_error()) { logger_->error( "Unable to sign Commited Candidate Receipt. Failed with error: {}", @@ -4457,7 +4438,7 @@ namespace kagome::parachain { if (stream_engine->reserveOutgoing(peer_id, protocol)) { protocol->newOutgoingStream( peer_id, - [callback{std::forward(callback)}, + [callback = std::forward(callback), protocol, peer_id, wptr{weak_from_this()}](auto &&stream_result) mutable { @@ -4762,6 +4743,7 @@ namespace kagome::parachain { } bool ParachainProcessorImpl::isValidatingNode() const { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) return (app_config_.roles().flags.authority == 1); } @@ -5050,21 +5032,21 @@ namespace kagome::parachain { parachain_state->get().awaiting_validation.erase(candidate_hash); auto q{std::move(validate_and_second_result)}; if constexpr (kMode == ValidationTaskType::kSecond) { - onValidationComplete(std::move(q)); + onValidationComplete(q); } else { - onAttestComplete(std::move(q)); + onAttestComplete(q); } } template void ParachainProcessorImpl::validateAsync( - network::CandidateReceipt &&candidate, + network::CandidateReceipt candidate, network::ParachainBlock &&pov, runtime::PersistedValidationData &&pvd, const primitives::BlockHash &relay_parent) { REINVOKE(*main_pool_handler_, validateAsync, - std::move(candidate), + candidate, std::move(pov), std::move(pvd), relay_parent); @@ -5174,7 +5156,7 @@ namespace kagome::parachain { const auto candidate_hash = result.candidate.hash(*hasher_); parachain_state->get().fallbacks.erase(candidate_hash); - if (parachain_state->get().issued_statements.count(candidate_hash) == 0) { + if (not parachain_state->get().issued_statements.contains(candidate_hash)) { if (result.result) { if (const auto r = sign_import_and_distribute_statement( @@ -5262,7 +5244,7 @@ namespace kagome::parachain { &active_leaves, ParachainId para_id) { if (!relay_parent_mode) { - return active_leaves.count(relay_parent) != 0ull; + return active_leaves.contains(relay_parent); } for (const auto &[hash, mode] : active_leaves) { @@ -5300,8 +5282,7 @@ namespace kagome::parachain { } if (!relay_parent_mode) { - if (peer_data.collator_state->advertisements.count(on_relay_parent) - != 0ull) { + if (peer_data.collator_state->advertisements.contains(on_relay_parent)) { return Error::DUPLICATE; } @@ -5400,7 +5381,7 @@ namespace kagome::parachain { collations.status = CollationStatus::WaitingOnValidation; validateAsync( - std::move(pending_collation_fetch.candidate_receipt), + pending_collation_fetch.candidate_receipt, std::move(pending_collation_fetch.pov), std::move(pvd), relay_parent); @@ -5429,7 +5410,7 @@ namespace kagome::parachain { for (auto depth : depths) { if (auto it = leaf_state.seconded_at_depth.find(candidate_para.get()); it != leaf_state.seconded_at_depth.end() - && it->second.count(depth) != 0ull) { + && it->second.contains(depth)) { return false; } } @@ -5442,9 +5423,8 @@ namespace kagome::parachain { const auto allowed_parents_for_para = implicit_view.knownAllowedRelayParentsUnder(head, {candidate_para.get()}); - if (std::find(allowed_parents_for_para.begin(), - allowed_parents_for_para.end(), - candidate_relay_parent.get()) + if (std::ranges::find(allowed_parents_for_para, + candidate_relay_parent.get()) == allowed_parents_for_para.end()) { continue; } @@ -5470,7 +5450,7 @@ namespace kagome::parachain { if (head == candidate_relay_parent.get()) { if (auto it = leaf_state.seconded_at_depth.find(candidate_para.get()); it != leaf_state.seconded_at_depth.end() - && it->second.count(0) != 0ull) { + && it->second.contains(0)) { return std::nullopt; } if (!proc_response(std::vector{0ull}, head, leaf_state)) { @@ -5691,7 +5671,7 @@ namespace kagome::parachain { .relay_parent = relay_parent, .para_id = para_id, .peer_id = peer_id, - .prospective_candidate = std::move(pc), + .prospective_candidate = pc, .commitments_hash = {}, }; @@ -5709,14 +5689,13 @@ namespace kagome::parachain { collator_id); } break; case CollationStatus::Waiting: { - std::ignore = fetchCollation(std::move(pending_collation), collator_id); + std::ignore = fetchCollation(pending_collation, collator_id); } break; case CollationStatus::Seconded: { if (relay_parent_mode) { // Limit is not reached, it's allowed to second another // collation. - std::ignore = - fetchCollation(std::move(pending_collation), collator_id); + std::ignore = fetchCollation(pending_collation, collator_id); } else { SL_TRACE(logger_, "A collation has already been seconded. (peer_id={}, para " @@ -5760,8 +5739,7 @@ namespace kagome::parachain { const PendingCollation &pc, const CollatorId &id, network::CollationVersion version) { - if (our_current_state_.collation_requests_cancel_handles.count(pc) - != 0ull) { + if (our_current_state_.collation_requests_cancel_handles.contains(pc)) { SL_WARN(logger_, "Already requested. (relay parent={}, para id={})", pc.relay_parent, @@ -5814,7 +5792,7 @@ namespace kagome::parachain { pc.para_id, pc.relay_parent); - our_current_state_.collation_requests_cancel_handles.insert(std::move(pc)); + our_current_state_.collation_requests_cancel_handles.insert(pc); const auto maybe_candidate_hash = utils::map(pc.prospective_candidate, [](const auto &v) { return std::cref(v.candidate_hash); }); @@ -5828,9 +5806,7 @@ namespace kagome::parachain { .para_id = pc.para_id, }; router_->getReqCollationProtocol()->request( - peer_id, - std::move(fetch_collation_request), - std::move(response_callback)); + peer_id, fetch_collation_request, std::move(response_callback)); } else if (network::CollationVersion::VStaging == version && maybe_candidate_hash) { network::vstaging::CollationFetchingRequest fetch_collation_request{ @@ -5839,9 +5815,7 @@ namespace kagome::parachain { .candidate_hash = maybe_candidate_hash->get(), }; router_->getReqCollationProtocol()->request( - peer_id, - std::move(fetch_collation_request), - std::move(response_callback)); + peer_id, fetch_collation_request, std::move(response_callback)); } else { UNREACHABLE; } diff --git a/core/parachain/validator/parachain_processor.hpp b/core/parachain/validator/parachain_processor.hpp index 7f8ea6e3ae..628895b6ef 100644 --- a/core/parachain/validator/parachain_processor.hpp +++ b/core/parachain/validator/parachain_processor.hpp @@ -414,7 +414,7 @@ namespace kagome::parachain { std::shared_ptr peers; PerSessionState(SessionIndex _session, - const runtime::SessionInfo &_session_info, + runtime::SessionInfo _session_info, Groups &&_groups, grid::Views &&_grid_view, ValidatorIndex _our_index, @@ -523,7 +523,7 @@ namespace kagome::parachain { * @param n_validators The number of validators in the network. */ template - void validateAsync(network::CandidateReceipt &&candidate, + void validateAsync(network::CandidateReceipt candidate, network::ParachainBlock &&pov, runtime::PersistedValidationData &&pvd, const primitives::BlockHash &relay_parent); diff --git a/core/parachain/validator/prospective_parachains.hpp b/core/parachain/validator/prospective_parachains.hpp index eba3e9ce0e..53313a0b80 100644 --- a/core/parachain/validator/prospective_parachains.hpp +++ b/core/parachain/validator/prospective_parachains.hpp @@ -635,14 +635,14 @@ namespace kagome::parachain { std::pair> response; response.reserve(candidates.size()); - std::transform(candidates.begin(), - candidates.end(), - std::back_inserter(response), - [](const HypotheticalCandidate &candidate) - -> std::pair { - return {candidate, {}}; - }); + std::ranges::transform( + candidates, + std::back_inserter(response), + [](const HypotheticalCandidate &candidate) + -> std::pair { + return {candidate, {}}; + }); const auto &required_active_leaf = fragment_tree_relay_parent; for (const auto &[active_leaf, leaf_view] : view.active_leaves) { diff --git a/core/parachain/validator/signer.cpp b/core/parachain/validator/signer.cpp index 7d38cf8158..15386ee83c 100644 --- a/core/parachain/validator/signer.cpp +++ b/core/parachain/validator/signer.cpp @@ -12,7 +12,8 @@ namespace kagome::parachain { const primitives::BlockHash &relay_parent) { OUTCOME_TRY(session_index, parachain_api->session_index_for_child(relay_parent)); - return SigningContext{session_index, relay_parent}; + return SigningContext{.session_index = session_index, + .relay_parent = relay_parent}; } ValidatorSigner::ValidatorSigner( diff --git a/core/primitives/arithmetic_error.hpp b/core/primitives/arithmetic_error.hpp index 58f6f494bd..f90e8cd996 100644 --- a/core/primitives/arithmetic_error.hpp +++ b/core/primitives/arithmetic_error.hpp @@ -21,16 +21,16 @@ namespace kagome::primitives { DivisionByZero, }; - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &s, const ArithmeticError &v) { // index shift is required for compatibility with rust implementation. // std::error_code policy preserves 0 index for success cases. return s << static_cast(v) - 1; } - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &s, ArithmeticError &v) { uint8_t value = 0u; s >> value; diff --git a/core/primitives/block.hpp b/core/primitives/block.hpp index 9549f02e63..8097a81d13 100644 --- a/core/primitives/block.hpp +++ b/core/primitives/block.hpp @@ -27,7 +27,8 @@ namespace kagome::primitives { SCALE_TIE(2); BlockHeaderReflection header; ///< block header - const BlockBody &body; ///< extrinsics collection + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const BlockBody &body; ///< extrinsics collection }; } // namespace kagome::primitives diff --git a/core/primitives/block_data.hpp b/core/primitives/block_data.hpp index d17a226b08..539f0ca2a5 100644 --- a/core/primitives/block_data.hpp +++ b/core/primitives/block_data.hpp @@ -32,11 +32,13 @@ namespace kagome::primitives { struct BlockDataFlags { static BlockDataFlags allSet(primitives::BlockHash hash) { - return BlockDataFlags{std::move(hash), true, true, true, true, true}; + // NOLINTNEXTLINE(modernize-use-designated-initializers) + return BlockDataFlags{hash, true, true, true, true, true}; } static BlockDataFlags allUnset(primitives::BlockHash hash) { - return BlockDataFlags{std::move(hash), false, false, false, false, false}; + // NOLINTNEXTLINE(modernize-use-designated-initializers) + return BlockDataFlags{hash, false, false, false, false, false}; } primitives::BlockHash hash; diff --git a/core/primitives/block_header.hpp b/core/primitives/block_header.hpp index 01fab04d78..35c06d968a 100644 --- a/core/primitives/block_header.hpp +++ b/core/primitives/block_header.hpp @@ -69,11 +69,13 @@ namespace kagome::primitives { }; struct BlockHeaderReflection { + // NOLINTBEGIN(cppcoreguidelines-avoid-const-or-ref-data-members) const BlockHash &parent_hash; const BlockNumber &number; const storage::trie::RootHash &state_root; const common::Hash256 &extrinsics_root; std::span digest; + // NOLINTEND(cppcoreguidelines-avoid-const-or-ref-data-members) BlockHeaderReflection(const BlockHeader &origin) : parent_hash(origin.parent_hash), @@ -96,12 +98,14 @@ namespace kagome::primitives { }; struct GenesisBlockHeader { + // NOLINTBEGIN(cppcoreguidelines-avoid-const-or-ref-data-members) const BlockHeader header; const BlockHash hash; + // NOLINTEND(cppcoreguidelines-avoid-const-or-ref-data-members) }; - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &s, const BlockHeaderReflection &bhr) { return s << bhr.parent_hash << CompactInteger(bhr.number) << bhr.state_root << bhr.extrinsics_root << bhr.digest; @@ -114,8 +118,8 @@ namespace kagome::primitives { * @param v value to output * @return reference to stream */ - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &s, const BlockHeader &bh) { return s << bh.parent_hash << CompactInteger(bh.number) << bh.state_root << bh.extrinsics_root << bh.digest; @@ -128,8 +132,8 @@ namespace kagome::primitives { * @param v value to output * @return reference to stream */ - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &s, BlockHeader &bh) { CompactInteger number_compact; s >> bh.parent_hash >> number_compact >> bh.state_root >> bh.extrinsics_root diff --git a/core/primitives/digest.hpp b/core/primitives/digest.hpp index 0b7679cc2e..b6c75a402b 100644 --- a/core/primitives/digest.hpp +++ b/core/primitives/digest.hpp @@ -91,10 +91,10 @@ namespace kagome::primitives { msg.digest = std::move(payload); } else if (engine_id == primitives::kUnsupportedEngineId_POL1) { OUTCOME_TRY(payload, scale::decode(data)); - msg.digest = std::move(payload); + msg.digest = payload; } else if (engine_id == primitives::kBeefyEngineId) { OUTCOME_TRY(payload, scale::decode(data)); - msg.digest = std::move(payload); + msg.digest = payload; } else { BOOST_ASSERT_MSG(false, "Invalid consensus engine id"); } diff --git a/core/primitives/event_types.hpp b/core/primitives/event_types.hpp index 643e38549e..5fb451ef15 100644 --- a/core/primitives/event_types.hpp +++ b/core/primitives/event_types.hpp @@ -34,7 +34,7 @@ namespace kagome::primitives::events { template using ref_t = std::reference_wrapper; - enum struct ChainEventType : uint32_t { + enum struct ChainEventType : uint8_t { kNewHeads = 1, kFinalizedHeads = 2, kAllHeads = 3, @@ -43,7 +43,7 @@ namespace kagome::primitives::events { kDeactivateAfterFinalization = 6, }; - enum struct SyncStateEventType : uint32_t { kSyncState = 1 }; + enum struct SyncStateEventType : uint8_t { kSyncState = 1 }; using HeadsEventParams = ref_t; using RuntimeVersionEventParams = ref_t; @@ -51,10 +51,10 @@ namespace kagome::primitives::events { struct RemoveAfterFinalizationParams { struct HeaderInfo { primitives::BlockHash hash; - primitives::BlockNumber number; + primitives::BlockNumber number{}; }; std::vector removed; - primitives::BlockNumber finalized; + primitives::BlockNumber finalized{}; }; using ChainEventParams = boost::variant outcome::result putData(InherentIdentifier identifier, const T &inherent) { - auto [it, inserted] = - data.try_emplace(std::move(identifier), common::Buffer()); + auto [it, inserted] = data.try_emplace(identifier, common::Buffer()); if (inserted) { it->second = common::Buffer(::scale::encode(inherent).value()); return outcome::success(); @@ -93,8 +92,8 @@ namespace kagome::primitives { * @param v value to output * @return reference to stream */ - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &s, const InherentData &v) { const auto &data = v.data; std::vector> vec; @@ -113,8 +112,8 @@ namespace kagome::primitives { * @param v value to decode * @return reference to stream */ - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &s, InherentData &v) { std::vector> vec; s >> vec; diff --git a/core/primitives/math.hpp b/core/primitives/math.hpp index 6a9c938b25..7d6846d041 100644 --- a/core/primitives/math.hpp +++ b/core/primitives/math.hpp @@ -51,8 +51,8 @@ namespace kagome::math { return e; } - template >, bool> = true> + template + requires std::is_integral_v> constexpr auto toLE(const T &value) { #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ constexpr size_t size = sizeof(std::decay_t); diff --git a/core/primitives/runtime_dispatch_info.hpp b/core/primitives/runtime_dispatch_info.hpp index 681c15d398..d0e1f21bd7 100644 --- a/core/primitives/runtime_dispatch_info.hpp +++ b/core/primitives/runtime_dispatch_info.hpp @@ -59,8 +59,8 @@ namespace kagome::primitives { Mandatory }; - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &stream, DispatchClass &dispatch_class) { uint8_t dispatch_class_byte; stream >> dispatch_class_byte; @@ -68,8 +68,8 @@ namespace kagome::primitives { return stream; } - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &stream, DispatchClass dispatch_class) { return stream << dispatch_class; } diff --git a/core/primitives/ss58_codec.cpp b/core/primitives/ss58_codec.cpp index 737a9efc5d..b6e7f810b3 100644 --- a/core/primitives/ss58_codec.cpp +++ b/core/primitives/ss58_codec.cpp @@ -52,7 +52,7 @@ namespace kagome::primitives { return Ss58Error::INVALID_CHECKSUM; } - size_t type_size = (ss58_account_id[0] < 64) ? 1 : 2; + auto type_size = (ss58_account_id[0] < 64) ? 1 : 2; if (ss58_account_id.size() - kSs58ChecksumLength - type_size != AccountId::size()) { diff --git a/core/primitives/ss58_codec.hpp b/core/primitives/ss58_codec.hpp index 66dcb28365..558ca011c6 100644 --- a/core/primitives/ss58_codec.hpp +++ b/core/primitives/ss58_codec.hpp @@ -17,7 +17,10 @@ namespace kagome::crypto { namespace kagome::primitives { - enum class Ss58Error { INVALID_LENGTH = 1, INVALID_CHECKSUM }; + enum class Ss58Error : uint8_t { + INVALID_LENGTH = 1, + INVALID_CHECKSUM, + }; constexpr size_t kSs58ChecksumLength = 2; diff --git a/core/primitives/strobe.hpp b/core/primitives/strobe.hpp index 19e20139ca..73dbfcb19f 100644 --- a/core/primitives/strobe.hpp +++ b/core/primitives/strobe.hpp @@ -148,15 +148,11 @@ namespace kagome::primitives { current_state_{*(buffer_ + kBufferSize + 2ull)} {} Strobe(const Strobe &other) : Strobe() { - std::copy(std::begin(other.raw_data), - std::end(other.raw_data), - std::begin(raw_data)); + std::ranges::copy(other.raw_data, std::begin(raw_data)); } Strobe &operator=(const Strobe &other) { - std::copy(std::begin(other.raw_data), - std::end(other.raw_data), - std::begin(raw_data)); + std::ranges::copy(other.raw_data, std::begin(raw_data)); return *this; } diff --git a/core/primitives/token_error.hpp b/core/primitives/token_error.hpp index 2f82f95b54..95ab602eab 100644 --- a/core/primitives/token_error.hpp +++ b/core/primitives/token_error.hpp @@ -29,16 +29,16 @@ namespace kagome::primitives { Unsupported, }; - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &s, const TokenError &v) { // index shift is required for compatibility with rust implementation. // std::error_code policy preserves 0 index for success cases. return s << static_cast(v) - 1; } - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &s, TokenError &v) { uint8_t value = 0u; s >> value; diff --git a/core/primitives/transaction_validity.hpp b/core/primitives/transaction_validity.hpp index f008806bff..f85acf2bf3 100644 --- a/core/primitives/transaction_validity.hpp +++ b/core/primitives/transaction_validity.hpp @@ -131,7 +131,7 @@ namespace kagome::primitives { /// The sending address is disabled or known to be invalid. BadSigner, }; - Kind kind; + Kind kind{}; uint8_t custom_value{}; bool operator==(const InvalidTransaction &other) const { @@ -140,8 +140,8 @@ namespace kagome::primitives { } }; - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &s, const InvalidTransaction &v) { // -1 is needed for compatibility with Rust; indices of error codes start // from 0 there, while in kagome they must start from 1 because of @@ -153,8 +153,8 @@ namespace kagome::primitives { return s; } - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &s, InvalidTransaction &v) { uint8_t value = 0u; s >> value; @@ -193,8 +193,8 @@ namespace kagome::primitives { uint8_t custom_value{}; }; - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &s, const UnknownTransaction &v) { // -1 is needed for compatibility with Rust; indices of error codes start // from 0 there, while in kagome they must start from 1 because of @@ -206,8 +206,8 @@ namespace kagome::primitives { return s; } - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &s, UnknownTransaction &v) { uint8_t value = 0u; s >> value; diff --git a/core/primitives/version.cpp b/core/primitives/version.cpp index 68c8cdaa53..495fd4c759 100644 --- a/core/primitives/version.cpp +++ b/core/primitives/version.cpp @@ -15,14 +15,14 @@ namespace { // We break DI principle here since we need to use hasher in decode scale // operator overload and we cannot inject it there - static std::unique_ptr kHasher = + static const std::unique_ptr kHasher = std::make_unique(); } // namespace namespace kagome::primitives::detail { std::optional coreVersionFromApis(const ApisVec &apis) { - auto result = std::find_if(apis.begin(), apis.end(), [](auto &api) { + auto result = std::ranges::find_if(apis, [](auto &api) { static auto api_id = kHasher->blake2b_64(common::Buffer::fromString("Core")); return api.first == api_id; diff --git a/core/primitives/version.hpp b/core/primitives/version.hpp index f6f0c0cfee..4e1f46d8e9 100644 --- a/core/primitives/version.hpp +++ b/core/primitives/version.hpp @@ -6,12 +6,12 @@ #pragma once -#include #include #include #include #include "common/blob.hpp" +#include "scale/tie.hpp" namespace kagome::primitives { /** @@ -44,6 +44,8 @@ namespace kagome::primitives { * `impl_version` since they change the semantics of the runtime. */ struct Version { + SCALE_TIE(8); + /** * Identifies the different Substrate runtimes. There'll be at least * polkadot and node. @@ -82,14 +84,7 @@ namespace kagome::primitives { /// Version of the state implementation used by this runtime. uint8_t state_version = 0u; - bool operator==(const Version &rhs) const { - return spec_name == rhs.spec_name and impl_name == rhs.impl_name - and authoring_version == rhs.authoring_version - and impl_version == rhs.impl_version and apis == rhs.apis - and spec_version == rhs.spec_version - and transaction_version == rhs.transaction_version - and state_version == rhs.state_version; - } + bool operator==(const Version &rhs) const = default; /** * `Decode` while giving a "version hint" @@ -105,6 +100,13 @@ namespace kagome::primitives { */ static outcome::result decode( scale::ScaleDecoderStream &s, std::optional core_version); + + friend scale::ScaleDecoderStream &operator>>(scale::ScaleDecoderStream &s, + Version &v) { + // `.value()` may throw, `scale::decode` will catch that + v = Version::decode(s, std::nullopt).value(); + return s; + } }; namespace detail { @@ -116,33 +118,4 @@ namespace kagome::primitives { std::optional coreVersionFromApis(const ApisVec &apis); } // namespace detail - /** - * @brief outputs object of type Version to stream - * @tparam Stream output stream type - * @param s stream reference - * @param v value to output - * @return reference to stream - */ - template > - Stream &operator<<(Stream &s, const Version &v) { - return s << v.spec_name << v.impl_name << v.authoring_version - << v.spec_version << v.impl_version << v.apis - << v.transaction_version << v.state_version; - } - - /** - * @brief decodes object of type Version from stream - * @tparam Stream input stream type - * @param s stream reference - * @param v value to decode - * @return reference to stream - */ - template > - Stream &operator>>(Stream &s, Version &v) { - // `.value()` may throw, `scale::decode` will catch that - v = Version::decode(s, std::nullopt).value(); - return s; - } } // namespace kagome::primitives diff --git a/core/runtime/CMakeLists.txt b/core/runtime/CMakeLists.txt index 410617169a..a4a487d589 100644 --- a/core/runtime/CMakeLists.txt +++ b/core/runtime/CMakeLists.txt @@ -8,26 +8,48 @@ add_subdirectory(common) add_subdirectory(binaryen) add_subdirectory(wabt) +set(DEFINITION_PATH "${CMAKE_CURRENT_BINARY_DIR}/wasm_compiler_definitions.hpp") +add_library(wasm_compiler_definitions INTERFACE ${DEFINITION_PATH}) +disable_clang_tidy(wasm_compiler_definitions) + add_library(wasm_compiler INTERFACE) if ("${WASM_COMPILER}" STREQUAL "WAVM") add_subdirectory(wavm) target_link_libraries(wasm_compiler INTERFACE runtime_wavm) - target_compile_definitions(wasm_compiler INTERFACE - KAGOME_WASM_COMPILER_WAVM=1 - KAGOME_WASM_COMPILER_WASM_EDGE=0 - ) + add_custom_command( + OUTPUT "${DEFINITION_PATH}" + COMMAND echo "/// This header was generated by cmake\\n" > ${DEFINITION_PATH} + COMMAND echo "#define KAGOME_WASM_COMPILER_WAVM 1" >> ${DEFINITION_PATH} + COMMAND echo "#define KAGOME_WASM_COMPILER_WASM_EDGE 0" >> ${DEFINITION_PATH} + COMMENT "Generate wasm_compiler_definitions.hpp" + VERBATIM + ) elseif ("${WASM_COMPILER}" STREQUAL "WasmEdge") add_subdirectory(wasm_edge) target_link_libraries(wasm_compiler INTERFACE runtime_wasm_edge) - target_compile_definitions(wasm_compiler INTERFACE - KAGOME_WASM_COMPILER_WAVM=0 - KAGOME_WASM_COMPILER_WASM_EDGE=1 + set(DEFINITION_PATH "${CMAKE_CURRENT_BINARY_DIR}/wasm_compiler_definitions.hpp") + add_custom_command( + OUTPUT "${DEFINITION_PATH}" + COMMAND echo "/// This header was generated by cmake\\n" > ${DEFINITION_PATH} + COMMAND echo "#define KAGOME_WASM_COMPILER_WAVM 0" >> ${DEFINITION_PATH} + COMMAND echo "#define KAGOME_WASM_COMPILER_WASM_EDGE 1" >> ${DEFINITION_PATH} + COMMAND echo "#define WASMEDGE_ID \"${WASMEDGE_ID}\"" >> ${DEFINITION_PATH} + COMMENT "Generate wasm_compiler_definitions.hpp" + VERBATIM ) else() fatal_error("Unknown WASM_COMPILER: ${WASM_COMPILER}") endif() +add_dependencies(wasm_compiler wasm_compiler_definitions) kagome_install(wasm_compiler) +if (NOT TARGET generated) + add_custom_target(generated + COMMENT "Building generated files..." + ) +endif() +add_dependencies(generated wasm_compiler_definitions) + add_subdirectory(runtime_api/impl) diff --git a/core/runtime/binaryen/instance_environment_factory.cpp b/core/runtime/binaryen/instance_environment_factory.cpp index 454904729f..858fc3b0ac 100644 --- a/core/runtime/binaryen/instance_environment_factory.cpp +++ b/core/runtime/binaryen/instance_environment_factory.cpp @@ -36,10 +36,10 @@ namespace kagome::runtime::binaryen { auto rei = std::make_shared(host_api); new_memory_provider->setExternalInterface(rei); return BinaryenInstanceEnvironment{ - InstanceEnvironment{std::move(new_memory_provider), - std::move(new_storage_provider), - std::move(host_api), - [](auto &) {}}, - std::move(rei)}; + .env = InstanceEnvironment{std::move(new_memory_provider), + std::move(new_storage_provider), + std::move(host_api), + [](auto &) {}}, + .rei = std::move(rei)}; } } // namespace kagome::runtime::binaryen diff --git a/core/runtime/binaryen/module/module_impl.cpp b/core/runtime/binaryen/module/module_impl.cpp index edef612d83..55e4c275ac 100644 --- a/core/runtime/binaryen/module/module_impl.cpp +++ b/core/runtime/binaryen/module/module_impl.cpp @@ -11,15 +11,12 @@ #include #include -#include "common/int_serialization.hpp" #include "runtime/binaryen/binaryen_memory_provider.hpp" #include "runtime/binaryen/instance_environment_factory.hpp" #include "runtime/binaryen/module/module_instance_impl.hpp" #include "runtime/binaryen/runtime_external_interface.hpp" #include "storage/trie/polkadot_trie/trie_error.hpp" -using namespace kagome::common::literals; - OUTCOME_CPP_DEFINE_CATEGORY(kagome::runtime::binaryen, ModuleImpl::Error, e) { using Error = kagome::runtime::binaryen::ModuleImpl::Error; switch (e) { diff --git a/core/runtime/binaryen/module/module_instance_impl.cpp b/core/runtime/binaryen/module/module_instance_impl.cpp index 11f4295f45..9a5e1d7142 100644 --- a/core/runtime/binaryen/module/module_instance_impl.cpp +++ b/core/runtime/binaryen/module/module_instance_impl.cpp @@ -117,7 +117,7 @@ namespace kagome::runtime::binaryen { return RuntimeExecutionError::EXPORT_FUNCTION_NOT_FOUND; } - WasmSpan span; + WasmSpan span; // NOLINT(cppcoreguidelines-init-variables) try { span = module_instance_->callExport(wasm::Name{name.data()}, args_list) .geti64(); @@ -177,10 +177,12 @@ namespace kagome::runtime::binaryen { > parent_->module_->memory.initial * wasm::Memory::kPageSize) { throw std::runtime_error("invalid offset when initializing memory"); } - callback(offset, - common::BufferView( - reinterpret_cast(segment.data.data()), - segment.data.size())); + callback( + offset, + common::BufferView( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + reinterpret_cast(segment.data.data()), + segment.data.size())); } } diff --git a/core/runtime/binaryen/runtime_external_interface.cpp b/core/runtime/binaryen/runtime_external_interface.cpp index 24059eef06..555c54f108 100644 --- a/core/runtime/binaryen/runtime_external_interface.cpp +++ b/core/runtime/binaryen/runtime_external_interface.cpp @@ -55,7 +55,7 @@ namespace { (host_api->*mf)((arguments.at(I).*literalMemFun())()...)); } else { (host_api->*mf)((arguments.at(I).*literalMemFun())()...); - return wasm::Literal(); + return {}; } } @@ -289,9 +289,8 @@ namespace kagome::runtime::binaryen { } if (func->imported()) { return callImport(func, arguments); - } else { - return instance.callFunctionInternal(func->name, arguments); } + return instance.callFunctionInternal(func->name, arguments); } } // namespace kagome::runtime::binaryen diff --git a/core/runtime/common/core_api_factory_impl.cpp b/core/runtime/common/core_api_factory_impl.cpp index 66439b7222..7705045e05 100644 --- a/core/runtime/common/core_api_factory_impl.cpp +++ b/core/runtime/common/core_api_factory_impl.cpp @@ -18,9 +18,9 @@ namespace kagome::runtime { using primitives::Version; class GetVersion : public RestrictedCore { public: - GetVersion(const Version &version) : version_{version} {} + GetVersion(Version version) : version_{std::move(version)} {} - outcome::result version() { + outcome::result version() override { return version_; } @@ -31,7 +31,7 @@ namespace kagome::runtime { CoreApiFactoryImpl::CoreApiFactoryImpl( std::shared_ptr hasher, LazySPtr instance_pool) - : hasher_{std::move(hasher)}, instance_pool_{std::move(instance_pool)} {} + : hasher_{std::move(hasher)}, instance_pool_{instance_pool} {} outcome::result> CoreApiFactoryImpl::make( BufferView code_zstd, diff --git a/core/runtime/common/executor.cpp b/core/runtime/common/executor.cpp index 17c7aa45b1..6f48a4993d 100644 --- a/core/runtime/common/executor.cpp +++ b/core/runtime/common/executor.cpp @@ -23,6 +23,6 @@ namespace kagome::runtime { Executor::Executor( std::shared_ptr ctx_factory, std::optional> cache) - : cache_{cache}, ctx_factory_{ctx_factory} {} + : cache_{std::move(cache)}, ctx_factory_{std::move(ctx_factory)} {} } // namespace kagome::runtime diff --git a/core/runtime/common/memory_allocator.cpp b/core/runtime/common/memory_allocator.cpp index c787c79c3f..19e1a30421 100644 --- a/core/runtime/common/memory_allocator.cpp +++ b/core/runtime/common/memory_allocator.cpp @@ -50,7 +50,7 @@ namespace kagome::runtime { size = std::max(size, kMinAllocate); size = math::nextHighPowerOf2(size); uint32_t order = std::countr_zero(size) - std::countr_zero(kMinAllocate); - uint32_t head_ptr; + uint32_t head_ptr; // NOLINT(cppcoreguidelines-init-variables) if (auto &list = free_lists_.at(order)) { head_ptr = *list; if (*list + sizeof(Header) + size > memory_->size()) { diff --git a/core/runtime/common/memory_allocator.hpp b/core/runtime/common/memory_allocator.hpp index e9559a83be..e39fa65424 100644 --- a/core/runtime/common/memory_allocator.hpp +++ b/core/runtime/common/memory_allocator.hpp @@ -19,7 +19,7 @@ namespace kagome::runtime { // https://github.com/paritytech/substrate/blob/743981a083f244a090b40ccfb5ce902199b55334/primitives/allocator/src/freeing_bump.rs#L56 constexpr uint8_t kAlignment = 8; constexpr size_t kDefaultHeapBase = [] { - using namespace kagome::common::literals; + using kagome::common::literals::operator""_MB; return 1_MB; // 1Mb }(); diff --git a/core/runtime/common/memory_error.hpp b/core/runtime/common/memory_error.hpp index cb38a30bb9..4afb78ddd8 100644 --- a/core/runtime/common/memory_error.hpp +++ b/core/runtime/common/memory_error.hpp @@ -8,7 +8,7 @@ #include "outcome/outcome.hpp" namespace kagome::runtime { - enum class MemoryError { + enum class MemoryError : uint8_t { ERROR, }; } // namespace kagome::runtime diff --git a/core/runtime/common/module_repository_impl.cpp b/core/runtime/common/module_repository_impl.cpp index 15e83c71d4..c4bbb4eb89 100644 --- a/core/runtime/common/module_repository_impl.cpp +++ b/core/runtime/common/module_repository_impl.cpp @@ -39,12 +39,13 @@ namespace kagome::runtime { runtime_upgrade_tracker_{std::move(runtime_upgrade_tracker)}, trie_storage_{std::move(trie_storage)}, module_factory_{std::move(module_factory)}, - code_provider_{code_provider}, + code_provider_{std::move(code_provider)}, cache_{4}, logger_{log::createLogger("Module Repository", "runtime")} { BOOST_ASSERT(runtime_instances_pool_); BOOST_ASSERT(runtime_upgrade_tracker_); BOOST_ASSERT(module_factory_); + BOOST_ASSERT(code_provider_); } outcome::result> diff --git a/core/runtime/common/runtime_context.cpp b/core/runtime/common/runtime_context.cpp index 24cd13a0ce..18960dfb2a 100644 --- a/core/runtime/common/runtime_context.cpp +++ b/core/runtime/common/runtime_context.cpp @@ -32,8 +32,6 @@ OUTCOME_CPP_DEFINE_CATEGORY(kagome::runtime, Error, e) { } namespace kagome::runtime { - using namespace kagome::common::literals; - RuntimeContext::RuntimeContext( std::shared_ptr module_instance) : module_instance{std::move(module_instance)} { diff --git a/core/runtime/common/runtime_execution_error.hpp b/core/runtime/common/runtime_execution_error.hpp index 618054b956..c9dbb19aab 100644 --- a/core/runtime/common/runtime_execution_error.hpp +++ b/core/runtime/common/runtime_execution_error.hpp @@ -13,7 +13,7 @@ namespace kagome::runtime { * @brief RuntimeExecutionError enum provides error codes for storage * transactions mechanism */ - enum class RuntimeExecutionError { // 0 is reserved for success + enum class RuntimeExecutionError : uint8_t { // 0 is reserved for success NO_TRANSACTIONS_WERE_STARTED = 1, EXPORT_FUNCTION_NOT_FOUND }; diff --git a/core/runtime/common/runtime_instances_pool.cpp b/core/runtime/common/runtime_instances_pool.cpp index f7b7af9918..b0a2ed29bc 100644 --- a/core/runtime/common/runtime_instances_pool.cpp +++ b/core/runtime/common/runtime_instances_pool.cpp @@ -25,13 +25,17 @@ namespace kagome::runtime { public: BorrowedInstance(std::weak_ptr pool, const common::Hash256 &hash, - const RuntimeContext::ContextParams &config, + RuntimeContext::ContextParams config, std::shared_ptr instance) : pool_{std::move(pool)}, hash_{hash}, - config_{config}, + config_{std::move(config)}, instance_{std::move(instance)} {} - ~BorrowedInstance() { + BorrowedInstance(const BorrowedInstance &) = delete; + BorrowedInstance(BorrowedInstance &&) = delete; + BorrowedInstance &operator=(const BorrowedInstance &) = delete; + BorrowedInstance &operator=(BorrowedInstance &&) = delete; + ~BorrowedInstance() override { if (auto pool = pool_.lock()) { pool->release(hash_, config_, std::move(instance_)); } @@ -172,7 +176,7 @@ namespace kagome::runtime { lock.lock(); pool_opt = pools_.get(key); if (!pool_opt) { - pool_opt = std::ref(pools_.put(key, InstancePool{module, {}})); + pool_opt = std::ref(pools_.put(key, InstancePool{.module = module})); } } BOOST_ASSERT(pool_opt); @@ -228,7 +232,7 @@ namespace kagome::runtime { Key key{code_hash, config}; auto entry = pools_.get(key); if (not entry) { - entry = pools_.put(key, {instance->getModule(), {}}); + entry = pools_.put(key, {.module = instance->getModule()}); } entry->get().instances.emplace_back(std::move(instance)); } diff --git a/core/runtime/common/runtime_upgrade_tracker_impl.cpp b/core/runtime/common/runtime_upgrade_tracker_impl.cpp index 73c0b209c6..6348a2a756 100644 --- a/core/runtime/common/runtime_upgrade_tracker_impl.cpp +++ b/core/runtime/common/runtime_upgrade_tracker_impl.cpp @@ -6,6 +6,8 @@ #include "runtime/common/runtime_upgrade_tracker_impl.hpp" +#include + #include "blockchain/block_header_repository.hpp" #include "blockchain/block_storage.hpp" #include "blockchain/block_tree.hpp" @@ -127,18 +129,17 @@ namespace kagome::runtime { OUTCOME_TRY(res, push(block.hash)); SL_DEBUG( logger_, "Pick runtime state at block {} for the same block", block); - return std::move(res.first); + return res.first; } KAGOME_PROFILE_START(blocks_with_runtime_upgrade_search) auto block_number = block.number; - auto latest_upgrade = - std::upper_bound(runtime_upgrades_.begin(), - runtime_upgrades_.end(), - block_number, - [](auto block_number, const auto &upgrade_data) { - return block_number < upgrade_data.block.number; - }); + auto latest_upgrade = boost::range::upper_bound( + runtime_upgrades_, + block_number, + [](auto block_number, const auto &upgrade_data) { + return block_number < upgrade_data.block.number; + }); KAGOME_PROFILE_END(blocks_with_runtime_upgrade_search) if (latest_upgrade == runtime_upgrades_.begin()) { @@ -176,9 +177,8 @@ namespace kagome::runtime { outcome::result RuntimeUpgradeTrackerImpl::getLastCodeUpdateBlockInfo( const storage::trie::RootHash &state) const { - auto it = std::find_if( - runtime_upgrades_.begin(), - runtime_upgrades_.end(), + auto it = std::ranges::find_if( + runtime_upgrades_, [&state](const auto &item) { return state == item.state; }); if (it != runtime_upgrades_.end()) { return it->block; @@ -223,21 +223,20 @@ namespace kagome::runtime { OUTCOME_TRY(header, header_repo_->getBlockHeader(hash)); primitives::BlockInfo block_info{header.number, hash}; - bool is_new_upgrade = std::find_if(runtime_upgrades_.begin(), - runtime_upgrades_.end(), - [&](const RuntimeUpgradeData &rud) { - return rud.block == block_info; - }) - == runtime_upgrades_.end(); + bool is_new_upgrade = + std::ranges::find_if(runtime_upgrades_, + [&](const RuntimeUpgradeData &rud) { + return rud.block == block_info; + }) + == runtime_upgrades_.end(); if (is_new_upgrade) { - runtime_upgrades_.emplace_back(block_info, std::move(header.state_root)); + runtime_upgrades_.emplace_back(block_info, header.state_root); - std::sort(runtime_upgrades_.begin(), - runtime_upgrades_.end(), - [](const auto &lhs, const auto &rhs) { - return lhs.block.number < rhs.block.number; - }); + std::ranges::sort(runtime_upgrades_, + [](const auto &lhs, const auto &rhs) { + return lhs.block.number < rhs.block.number; + }); save(); return std::make_pair(header.state_root, true); } diff --git a/core/runtime/common/trie_storage_provider_impl.cpp b/core/runtime/common/trie_storage_provider_impl.cpp index 4418f9a384..7546f5324a 100644 --- a/core/runtime/common/trie_storage_provider_impl.cpp +++ b/core/runtime/common/trie_storage_provider_impl.cpp @@ -59,8 +59,9 @@ namespace kagome::runtime { child_batches_.clear(); base_batch_ = batch; transaction_stack_.clear(); - transaction_stack_.emplace_back( - Transaction{std::make_shared(base_batch_), {}}); + transaction_stack_.emplace_back(Transaction{ + .main_batch = std::make_shared(base_batch_), + .child_batches = {}}); } std::shared_ptr @@ -74,11 +75,9 @@ namespace kagome::runtime { outcome::result>> TrieStorageProviderImpl::findChildBatchAt( const common::Buffer &root_path) const { - for (auto transaction_it = transaction_stack_.rbegin(); - transaction_it != transaction_stack_.rend(); - transaction_it++) { - if (auto it = transaction_it->child_batches.find(root_path); - it != transaction_it->child_batches.end()) { + for (auto &transaction : transaction_stack_) { + if (auto it = transaction.child_batches.find(root_path); + it != transaction.child_batches.end()) { return it->second; } } @@ -189,7 +188,8 @@ namespace kagome::runtime { outcome::result TrieStorageProviderImpl::startTransaction() { transaction_stack_.emplace_back(Transaction{ - std::make_shared(getCurrentBatch()), {}}); + .main_batch = std::make_shared(getCurrentBatch()), + .child_batches = {}}); SL_TRACE(logger_, "Start storage transaction, depth {}", transaction_stack_.size()); @@ -233,12 +233,11 @@ namespace kagome::runtime { if (not child and starts_with_child_storage_key(prefix)) { return result; } - storage::trie::TrieBatch *overlay; - if (child) { - overlay = &getMutableChildBatchAt(*child).value().get(); - } else { - overlay = getCurrentBatch().get(); - } + + storage::trie::TrieBatch *overlay = + child ? &getMutableChildBatchAt(*child).value().get() + : getCurrentBatch().get(); + // https://github.com/paritytech/polkadot-sdk/blob/c973fe86f8c668462186c95655a58fda04508e9a/substrate/primitives/state-machine/src/overlayed_changes/mod.rs#L396-L399 overlay->clearPrefix(prefix).value(); std::unique_ptr cursor; diff --git a/core/runtime/common/uncompress_code_if_needed.cpp b/core/runtime/common/uncompress_code_if_needed.cpp index 350e7c2f0d..968c59f837 100644 --- a/core/runtime/common/uncompress_code_if_needed.cpp +++ b/core/runtime/common/uncompress_code_if_needed.cpp @@ -25,6 +25,7 @@ namespace kagome::runtime { // @see // https://github.com/paritytech/substrate/blob/polkadot-v0.9.8/primitives/maybe-compressed-blob/src/lib.rs#L28 constexpr uint8_t kZstdPrefixSize = 8; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) constexpr uint8_t kZstdPrefix[kZstdPrefixSize] = { 0x52, 0xBC, 0x53, 0x76, 0x46, 0xDB, 0x8E, 0x05}; // @see diff --git a/core/runtime/module_instance.hpp b/core/runtime/module_instance.hpp index c0b16e2b45..49e5d244db 100644 --- a/core/runtime/module_instance.hpp +++ b/core/runtime/module_instance.hpp @@ -34,7 +34,7 @@ namespace kagome::runtime { */ class ModuleInstance { public: - enum class Error { + enum class Error : uint8_t { ABSENT_HEAP_BASE = 1, HEAP_BASE_TOO_LOW, INVALID_CALL_RESULT, @@ -54,7 +54,7 @@ namespace kagome::runtime { static outcome::result decodedCall( [[maybe_unused]] std::string_view method_name, outcome::result &&result) { - OUTCOME_TRY(value, result); + OUTCOME_TRY(value, std::move(result)); if constexpr (std::is_void_v) { return outcome::success(); } else { diff --git a/core/runtime/ptr_size.hpp b/core/runtime/ptr_size.hpp index 487626e049..f25b774447 100644 --- a/core/runtime/ptr_size.hpp +++ b/core/runtime/ptr_size.hpp @@ -16,7 +16,7 @@ namespace kagome::runtime { * bits are the address and next 32 bits are the size of the returned buffer. */ struct PtrSize { - constexpr PtrSize() : ptr{0}, size{0} {} + constexpr PtrSize() = default; explicit PtrSize(WasmSpan v) { std::tie(ptr, size) = splitSpan(v); diff --git a/core/runtime/runtime_api/impl/beefy.cpp b/core/runtime/runtime_api/impl/beefy.cpp index 1dcb1aaf46..e3cd831e2b 100644 --- a/core/runtime/runtime_api/impl/beefy.cpp +++ b/core/runtime/runtime_api/impl/beefy.cpp @@ -21,7 +21,7 @@ namespace kagome::runtime { auto r = executor_->call>( ctx, "BeefyApi_beefy_genesis"); if (r) { - return std::move(r.value()); + return r.value(); } if (r.error() == RuntimeExecutionError::EXPORT_FUNCTION_NOT_FOUND) { return std::nullopt; diff --git a/core/runtime/runtime_api/impl/lru.hpp b/core/runtime/runtime_api/impl/lru.hpp index 3bc0b26c91..5b0b458190 100644 --- a/core/runtime/runtime_api/impl/lru.hpp +++ b/core/runtime/runtime_api/impl/lru.hpp @@ -105,11 +105,11 @@ namespace kagome::runtime { } lru_.exclusiveAccess([&](typename decltype(lru_)::Type &lru_) { lru_.erase_if([&](const Key &key, const std::shared_ptr &) { - return std::find_if(blocks.begin(), - blocks.end(), - [&](const primitives::BlockHash &block) { - return block == std::get<0>(key); - }) + return std::ranges::find_if(blocks.begin(), + blocks.end(), + [&](const primitives::BlockHash &block) { + return block == std::get<0>(key); + }) != blocks.end(); }); }); diff --git a/core/runtime/runtime_api/impl/offchain_worker_api.cpp b/core/runtime/runtime_api/impl/offchain_worker_api.cpp index 8252d8f7c1..e8d7bc2de8 100644 --- a/core/runtime/runtime_api/impl/offchain_worker_api.cpp +++ b/core/runtime/runtime_api/impl/offchain_worker_api.cpp @@ -42,6 +42,7 @@ namespace kagome::runtime { // but offchain workers runs when node is validating if (app_config_.offchainWorkerMode() == application::AppConfiguration::OffchainWorkerMode::WhenValidating) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) if (app_config_.roles().flags.authority != 1) { return outcome::success(); } @@ -49,9 +50,7 @@ namespace kagome::runtime { auto label = fmt::format("#{}", block); - auto func = [block = std::move(block), - header = std::move(header), - executor = executor_] { + auto func = [block, header, executor = executor_] { auto res = [&]() -> outcome::result { OUTCOME_TRY(ctx, executor->ctx().ephemeralAt(block)); return executor->call( diff --git a/core/runtime/runtime_api/impl/parachain_host.cpp b/core/runtime/runtime_api/impl/parachain_host.cpp index 07a74ed59e..79e07c90dc 100644 --- a/core/runtime/runtime_api/impl/parachain_host.cpp +++ b/core/runtime/runtime_api/impl/parachain_host.cpp @@ -193,10 +193,9 @@ namespace kagome::runtime { if (auto self = wptr.lock()) { std::vector removed; removed.reserve(event.removed.size()); - std::transform(event.removed.begin(), - event.removed.end(), - std::back_inserter(removed), - [](const auto &bi) { return bi.hash; }); + std::ranges::transform(event.removed, + std::back_inserter(removed), + [](const auto &bi) { return bi.hash; }); self->clearCaches(removed); } }); @@ -244,7 +243,7 @@ namespace kagome::runtime { return executor_->call>>( - ctx, "ParachainHost_disputes"); // TODO ensure if it works + ctx, "ParachainHost_disputes"); // TODO(harrm): ensure if it works } outcome::result> diff --git a/core/runtime/runtime_api/impl/parachain_host_types_serde.cpp b/core/runtime/runtime_api/impl/parachain_host_types_serde.cpp index 12dcb986db..1cb457ae26 100644 --- a/core/runtime/runtime_api/impl/parachain_host_types_serde.cpp +++ b/core/runtime/runtime_api/impl/parachain_host_types_serde.cpp @@ -50,7 +50,7 @@ namespace kagome::runtime { ::scale::ScaleEncoderStream &operator<<(::scale::ScaleEncoderStream &s, const CandidateBacked &val) { - s << static_cast(val) << val.group_index; + s << static_cast(val) << val.group_index; return s; } @@ -61,7 +61,7 @@ namespace kagome::runtime { ::scale::ScaleEncoderStream &operator<<(::scale::ScaleEncoderStream &s, const CandidateIncluded &val) { - s << static_cast(val); + s << static_cast(val); s << val.group_index; return s; } diff --git a/core/runtime/runtime_api/impl/session_keys_api.cpp b/core/runtime/runtime_api/impl/session_keys_api.cpp index 2d18b4d1aa..fea07625be 100644 --- a/core/runtime/runtime_api/impl/session_keys_api.cpp +++ b/core/runtime/runtime_api/impl/session_keys_api.cpp @@ -20,7 +20,7 @@ namespace kagome::runtime { std::optional seed) { OUTCOME_TRY(ctx, executor_->ctx().ephemeralAt(block_hash)); return executor_->call>( - ctx, "SessionKeys_generate_session_keys", std::move(seed)); + ctx, "SessionKeys_generate_session_keys", seed); } outcome::result>> diff --git a/core/runtime/runtime_api/impl/tagged_transaction_queue.cpp b/core/runtime/runtime_api/impl/tagged_transaction_queue.cpp index 34f7084b5b..73fa489b44 100644 --- a/core/runtime/runtime_api/impl/tagged_transaction_queue.cpp +++ b/core/runtime/runtime_api/impl/tagged_transaction_queue.cpp @@ -15,7 +15,7 @@ namespace kagome::runtime { std::shared_ptr executor, LazySPtr block_tree) : executor_{std::move(executor)}, - block_tree_(std::move(block_tree)), + block_tree_(block_tree), logger_{log::createLogger("TaggedTransactionQueue", "runtime")} { BOOST_ASSERT(executor_); } diff --git a/core/runtime/runtime_api/impl/transaction_payment_api.cpp b/core/runtime/runtime_api/impl/transaction_payment_api.cpp index a80f79399f..5bcbea0eb1 100644 --- a/core/runtime/runtime_api/impl/transaction_payment_api.cpp +++ b/core/runtime/runtime_api/impl/transaction_payment_api.cpp @@ -28,7 +28,9 @@ namespace kagome::runtime { std::shared_ptr executor, std::shared_ptr core_api, std::shared_ptr hasher) - : executor_{std::move(executor)}, core_api_{core_api}, hasher_{hasher} { + : executor_{std::move(executor)}, + core_api_{std::move(core_api)}, + hasher_{std::move(hasher)} { BOOST_ASSERT(executor_); BOOST_ASSERT(core_api_); BOOST_ASSERT(hasher_); @@ -46,12 +48,10 @@ namespace kagome::runtime { const auto &c_transaction_payment_api_hash = transaction_payment_api_hash; // to create memory storage to push in // lambda - auto res = std::find_if(runtime_version.apis.begin(), - runtime_version.apis.end(), - [&](auto &api_version) { - return api_version.first - == c_transaction_payment_api_hash; - }); + auto res = + std::ranges::find_if(runtime_version.apis, [&](auto &api_version) { + return api_version.first == c_transaction_payment_api_hash; + }); if (res == runtime_version.apis.end()) { return Error::TRANSACTION_PAYMENT_API_NOT_FOUND; } @@ -64,7 +64,7 @@ namespace kagome::runtime { result, executor_->call>( ctx, "TransactionPaymentApi_query_info", ext.data, len)); - + return result; } diff --git a/core/runtime/runtime_context.hpp b/core/runtime/runtime_context.hpp index 18fb33551e..b3a4cd80eb 100644 --- a/core/runtime/runtime_context.hpp +++ b/core/runtime/runtime_context.hpp @@ -37,7 +37,8 @@ namespace kagome::runtime { RuntimeContext(const RuntimeContext &) = delete; RuntimeContext &operator=(const RuntimeContext &) = delete; - RuntimeContext(RuntimeContext &&) = default; + RuntimeContext(RuntimeContext &&) noexcept = default; + RuntimeContext &operator=(RuntimeContext &&) noexcept = delete; ~RuntimeContext(); @@ -103,33 +104,33 @@ namespace kagome::runtime { std::shared_ptr module_repo, std::shared_ptr header_repo); - virtual outcome::result fromBatch( + outcome::result fromBatch( std::shared_ptr module_instance, std::shared_ptr batch) const override; - virtual outcome::result persistent( + outcome::result persistent( std::shared_ptr module_instance, const storage::trie::RootHash &state, std::optional> changes_tracker_opt) const override; - virtual outcome::result persistentAt( + outcome::result persistentAt( const primitives::BlockHash &block_hash, std::optional> changes_tracker_opt = {}) const override; - virtual outcome::result ephemeral( + outcome::result ephemeral( std::shared_ptr module_instance, const storage::trie::RootHash &state) const override; - virtual outcome::result ephemeralAt( + outcome::result ephemeralAt( const primitives::BlockHash &block_hash) const override; - virtual outcome::result ephemeralAt( + outcome::result ephemeralAt( const primitives::BlockHash &block_hash, const storage::trie::RootHash &state) const override; - virtual outcome::result ephemeralAtGenesis() const override; + outcome::result ephemeralAtGenesis() const override; private: std::shared_ptr module_repo_; diff --git a/core/runtime/runtime_upgrade_tracker.hpp b/core/runtime/runtime_upgrade_tracker.hpp index 9070d8fa42..48940498f6 100644 --- a/core/runtime/runtime_upgrade_tracker.hpp +++ b/core/runtime/runtime_upgrade_tracker.hpp @@ -31,7 +31,9 @@ namespace kagome::runtime { const storage::trie::RootHash &state) const = 0; }; - enum class RuntimeUpgradeTrackerError { NOT_FOUND = 1 }; + enum class RuntimeUpgradeTrackerError : uint8_t { + NOT_FOUND = 1, + }; } // namespace kagome::runtime diff --git a/core/runtime/types.hpp b/core/runtime/types.hpp index 0c4859f588..2f60677a17 100644 --- a/core/runtime/types.hpp +++ b/core/runtime/types.hpp @@ -18,7 +18,7 @@ namespace kagome::runtime { /** * @brief type of wasm log levels */ - enum class WasmLogLevel { + enum class WasmLogLevel : uint8_t { Off, Error, Warn, @@ -75,7 +75,7 @@ namespace kagome::runtime { return {minor_part, major_part}; } - enum class Error { + enum class Error : uint8_t { COMPILATION_FAILED = 1, INSTRUMENTATION_FAILED, }; diff --git a/core/runtime/wabt/instrument.cpp b/core/runtime/wabt/instrument.cpp index 9a0986efa1..63f4f5832f 100644 --- a/core/runtime/wabt/instrument.cpp +++ b/core/runtime/wabt/instrument.cpp @@ -6,6 +6,8 @@ #include "runtime/wabt/instrument.hpp" +#include + #include "runtime/wabt/stack_limiter.hpp" #include "runtime/wabt/util.hpp" @@ -20,6 +22,7 @@ namespace kagome::runtime { if (not memory) { continue; } + // NOLINTNEXTLINE(modernize-use-ranges,boost-use-ranges) if (std::any_of(module.fields.begin(), module.fields.end(), [&](const wabt::ModuleField &field) { @@ -27,13 +30,11 @@ namespace kagome::runtime { })) { return WabtError{"unexpected MemoryModuleField"}; } - auto import_it = std::find( - module.imports.begin(), module.imports.end(), import->import.get()); + auto import_it = std::ranges::find(module.imports, import->import.get()); if (import_it == module.imports.end()) { return WabtError{"inconsistent Module.imports"}; } - auto memory_it = std::find( - module.memories.begin(), module.memories.end(), &memory->memory); + auto memory_it = std::ranges::find(module.memories, &memory->memory); if (memory_it == module.memories.end()) { return WabtError{"inconsistent Module.memories"}; } @@ -41,9 +42,9 @@ namespace kagome::runtime { memory2->memory.page_limits = memory->memory.page_limits; auto export_ = std::make_unique(); export_->export_ = { - import->import->field_name, - wabt::ExternalKind::Memory, - wabt::Var{0, {}}, + .name = import->import->field_name, + .kind = wabt::ExternalKind::Memory, + .var = wabt::Var{0, {}}, }; module.imports.erase(import_it); module.memories.erase(memory_it); @@ -58,8 +59,8 @@ namespace kagome::runtime { WabtOutcome setupMemoryAccordingToHeapAllocStrategy( wabt::Module &module, const HeapAllocStrategy &config) { - for (auto it = module.fields.begin(); it != module.fields.end(); ++it) { - auto memory = dynamic_cast(&*it); + for (auto &field : module.fields) { + auto memory = dynamic_cast(&field); if (not memory) { continue; } diff --git a/core/runtime/wabt/stack_limiter.cpp b/core/runtime/wabt/stack_limiter.cpp index 68d036638d..5a5a9111ce 100644 --- a/core/runtime/wabt/stack_limiter.cpp +++ b/core/runtime/wabt/stack_limiter.cpp @@ -109,9 +109,7 @@ namespace kagome::runtime { wabt::ExprList::iterator>; explicit Stack(log::Logger logger) - : height_{ACTIVATION_FRAME_COST}, - frames_{}, - logger_{std::move(logger)} {} + : height_{ACTIVATION_FRAME_COST}, logger_{std::move(logger)} {} WabtOutcome unreachable() { if (frames_.empty()) { @@ -207,9 +205,8 @@ namespace kagome::runtime { if (height_ - num < frames_.back().start_height) { if (!frames_.back().is_polymorphic) { return WabtError{"Popping values not pushed in the current frame"}; - } else { - return outcome::success(); } + return outcome::success(); } if (height_ < num) { return WabtError{"Stack underflow"}; @@ -224,7 +221,7 @@ namespace kagome::runtime { WabtOutcome advance() { bool is_over = false; - do { + do { // NOLINT(cppcoreguidelines-avoid-do-while) auto &frame = frames_.back(); is_over = frame.getExprList().end() == frame.current_expr; if (!is_over) { @@ -236,7 +233,7 @@ namespace kagome::runtime { frame.top_expr)) { auto &branch = std::get(frame.top_expr); - if (branch.curr_branch == true && !branch.expr->false_.empty()) { + if (branch.curr_branch and not branch.expr->false_.empty()) { branch.curr_branch = false; frame.current_expr = branch.expr->false_.begin(); break; @@ -276,7 +273,7 @@ namespace kagome::runtime { private: uint32_t height_ = ACTIVATION_FRAME_COST; - std::vector frames_; + std::vector frames_{}; log::Logger logger_; }; @@ -495,6 +492,7 @@ namespace kagome::runtime { } struct InstrumentCallCtx { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) const wabt::Var &stack_height; wabt::Var callee_idx; uint32_t callee_stack_cost; @@ -522,6 +520,7 @@ namespace kagome::runtime { std::make_unique(wabt::Opcode::I32GtU)); auto if_it = exprs.insert(call_it, std::make_unique()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) auto &if_expr = static_cast(*if_it); wabt::ExprList if_exprs; if_exprs.push_back(std::make_unique()); @@ -592,10 +591,10 @@ namespace kagome::runtime { if (auto cost = stack_costs.at(call->var.index()); cost != 0) { top_frame.current_expr = instrument_call( InstrumentCallCtx{ - stack_height, - call->var, - stack_costs.at(call->var.index()), - stack_limit, + .stack_height = stack_height, + .callee_idx = call->var, + .callee_stack_cost = stack_costs.at(call->var.index()), + .stack_limit = stack_limit, }, top_frame.getExprList(), top_frame.current_expr); @@ -643,6 +642,7 @@ namespace kagome::runtime { using wabt::ExprType; switch (expr.type()) { case ExprType::RefFunc: { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) auto &ref = static_cast(expr); assert(ref.var.is_index()); if (!module.IsImport(wabt::ExternalKind::Func, ref.var)) { @@ -681,8 +681,10 @@ namespace kagome::runtime { wabt::Var v{thunked, {}}; thunk.push_back(std::make_unique(v)); instrument_call( - InstrumentCallCtx{ - stack_height, v, stack_costs.at(thunked), stack_limit}, + InstrumentCallCtx{.stack_height = stack_height, + .callee_idx = v, + .callee_stack_cost = stack_costs.at(thunked), + .stack_limit = stack_limit}, thunk, std::prev(thunk.end())); @@ -713,6 +715,7 @@ namespace kagome::runtime { using wabt::ExprType; switch (expr.type()) { case ExprType::RefFunc: { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) auto &ref = static_cast(expr); if (!module.IsImport(wabt::ExternalKind::Func, ref.var)) { ref.var.set_index(thunked_to_thunk.at(ref.var.index())); diff --git a/core/runtime/wabt/version.cpp b/core/runtime/wabt/version.cpp index 37ed002750..72a62ebddf 100644 --- a/core/runtime/wabt/version.cpp +++ b/core/runtime/wabt/version.cpp @@ -13,9 +13,8 @@ namespace kagome::runtime { BufferView wasm) { OUTCOME_TRY(module, wabtDecode(wasm)); auto custom_section_contents = [&](std::string_view name) { - auto it = std::find_if( - module.customs.begin(), - module.customs.end(), + auto it = std::ranges::find_if( + module.customs, [&](const wabt::Custom §ion) { return section.name == name; }); return it != module.customs.end() ? std::make_optional(BufferView{it->data}) diff --git a/core/runtime/wasm_edge/CMakeLists.txt b/core/runtime/wasm_edge/CMakeLists.txt index f00d80b245..b1e96bd53f 100644 --- a/core/runtime/wasm_edge/CMakeLists.txt +++ b/core/runtime/wasm_edge/CMakeLists.txt @@ -1,10 +1,12 @@ -add_library(runtime_wasm_edge module_factory_impl.cpp memory_impl.cpp) +add_library(runtime_wasm_edge + module_factory_impl.cpp + memory_impl.cpp +) target_link_libraries(runtime_wasm_edge memory_allocator runtime_common zstd::libzstd_static WasmEdge::WasmEdge - ) -target_compile_definitions(runtime_wasm_edge PRIVATE WASMEDGE_ID="${WASMEDGE_ID}") +) kagome_install(runtime_wasm_edge) diff --git a/core/runtime/wasm_edge/module_factory_impl.cpp b/core/runtime/wasm_edge/module_factory_impl.cpp index a0140dce16..140c01607b 100644 --- a/core/runtime/wasm_edge/module_factory_impl.cpp +++ b/core/runtime/wasm_edge/module_factory_impl.cpp @@ -21,6 +21,7 @@ #include "runtime/module_factory.hpp" #include "runtime/module_instance.hpp" #include "runtime/runtime_context.hpp" +#include "runtime/wasm_compiler_definitions.hpp" // this header-file is generated #include "runtime/wasm_edge/memory_impl.hpp" #include "runtime/wasm_edge/register_host_api.hpp" #include "runtime/wasm_edge/wrappers.hpp" @@ -31,7 +32,7 @@ static_assert(std::string_view{WASMEDGE_ID}.size() == 40, "WASMEDGE_ID should be set to WasmEdge repository SHA1 hash"); namespace kagome::runtime::wasm_edge { - enum class Error { + enum class Error : uint8_t { INVALID_VALUE_TYPE = 1, }; @@ -52,7 +53,7 @@ namespace kagome::runtime::wasm_edge { static const auto kMemoryName = WasmEdge_StringCreateByCString("memory"); - class WasmEdgeErrCategory final : public std::error_category { + static const class final : public std::error_category { public: const char *name() const noexcept override { return "WasmEdge"; @@ -62,9 +63,7 @@ namespace kagome::runtime::wasm_edge { auto res = WasmEdge_ResultGen(WasmEdge_ErrCategory_WASM, code); return WasmEdge_ResultGetMessage(res); } - }; - - WasmEdgeErrCategory wasm_edge_err_category; + } wasm_edge_err_category; std::error_code make_error_code(WasmEdge_Result res) { BOOST_ASSERT(WasmEdge_ResultGetCategory(res) == WasmEdge_ErrCategory_WASM); @@ -72,6 +71,7 @@ namespace kagome::runtime::wasm_edge { wasm_edge_err_category}; } + // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define WasmEdge_UNWRAP(expr) \ if (auto _wasm_edge_res = (expr); !WasmEdge_ResultOK(_wasm_edge_res)) { \ return make_error_code(_wasm_edge_res); \ @@ -117,10 +117,10 @@ namespace kagome::runtime::wasm_edge { std::shared_ptr host_instance, InstanceEnvironment env, const common::Hash256 &code_hash) - : module_{module}, + : module_{std::move(module)}, instance_{std::move(instance_ctx)}, - host_instance_{host_instance}, - executor_{executor}, + host_instance_{std::move(host_instance)}, + executor_{std::move(executor)}, env_{std::move(env)}, code_hash_{code_hash} { BOOST_ASSERT(module_ != nullptr); @@ -149,8 +149,9 @@ namespace kagome::runtime::wasm_edge { .get() .storeBuffer(encoded_args)}; } - std::array params{WasmEdge_ValueGenI32(args_ptrsize.ptr), - WasmEdge_ValueGenI32(args_ptrsize.size)}; + std::array params{ + WasmEdge_ValueGenI32(static_cast(args_ptrsize.ptr)), + WasmEdge_ValueGenI32(static_cast(args_ptrsize.size))}; std::array returns{WasmEdge_ValueGenI64(0)}; String wasm_name = WasmEdge_StringCreateByBuffer(name.data(), name.size()); @@ -225,6 +226,8 @@ namespace kagome::runtime::wasm_edge { std::shared_ptr executor_; log::Logger log_ = log::createLogger("ModuleInstance", "runtime"); InstanceEnvironment env_; + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) const common::Hash256 code_hash_; }; @@ -235,10 +238,10 @@ namespace kagome::runtime::wasm_edge { std::shared_ptr host_api_factory, std::shared_ptr storage, std::shared_ptr serializer) - : core_factory_{core_factory}, - host_api_factory_{host_api_factory}, - storage_{storage}, - serializer_{serializer} {} + : core_factory_{std::move(core_factory)}, + host_api_factory_{std::move(host_api_factory)}, + storage_{std::move(storage)}, + serializer_{std::move(serializer)} {} InstanceEnvironment make(std::shared_ptr memory_provider) { auto storage_provider = @@ -321,6 +324,8 @@ namespace kagome::runtime::wasm_edge { auto memory_ctx = WasmEdge_ModuleInstanceFindMemory(instance_ctx.raw(), kMemoryName); BOOST_ASSERT(memory_ctx); + + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) static_cast(memory_provider.get()) ->setMemory(memory_ctx); } @@ -339,6 +344,8 @@ namespace kagome::runtime::wasm_edge { log::Logger log_ = log::createLogger("Module", "runtime"); const WasmEdge_MemoryTypeContext *memory_type_; ASTModuleContext module_; + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) const common::Hash256 code_hash_; friend class ModuleInstanceImpl; @@ -362,10 +369,10 @@ namespace kagome::runtime::wasm_edge { std::shared_ptr serializer, std::shared_ptr core_factory, Config config) - : hasher_{hasher}, - host_api_factory_{host_api_factory}, - storage_{storage}, - serializer_{serializer}, + : hasher_{std::move(hasher)}, + host_api_factory_{std::move(host_api_factory)}, + storage_{std::move(storage)}, + serializer_{std::move(serializer)}, core_factory_{std::move(core_factory)}, log_{log::createLogger("ModuleFactory", "runtime")}, config_{config} { @@ -412,6 +419,7 @@ namespace kagome::runtime::wasm_edge { auto code_hash = hasher_->blake2b_256(code); OUTCOME_TRY(configure_ctx, configureCtx()); LoaderContext loader_ctx = WasmEdge_LoaderCreate(configure_ctx.raw()); + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) WasmEdge_ASTModuleContext *module_ctx; WasmEdge_UNWRAP_COMPILE_ERR(WasmEdge_LoaderParseFromFile( loader_ctx.raw(), &module_ctx, path_compiled.c_str())); @@ -446,11 +454,11 @@ namespace kagome::runtime::wasm_edge { auto env_factory = std::make_shared( core_factory_, host_api_factory_, storage_, serializer_); - return std::shared_ptr{new ModuleImpl{std::move(module), - std::move(executor), - env_factory, - import_memory_type, - code_hash}}; + return std::make_shared(std::move(module), + std::move(executor), + std::move(env_factory), + import_memory_type, + code_hash); } } // namespace kagome::runtime::wasm_edge diff --git a/core/runtime/wavm/module.cpp b/core/runtime/wavm/module.cpp index e9adc28a3c..c85fe51101 100644 --- a/core/runtime/wavm/module.cpp +++ b/core/runtime/wavm/module.cpp @@ -88,11 +88,12 @@ namespace kagome::runtime::wavm { #pragma GCC diagnostic pop #endif bool imports_memory = - std::find_if(ir_module.imports.cbegin(), - ir_module.imports.cend(), - [](auto &import) { - return import.kind == WAVM::IR::ExternKind::memory; - }) + std::ranges::find_if(ir_module.imports.cbegin(), + ir_module.imports.cend(), + [](auto &import) { + return import.kind + == WAVM::IR::ExternKind::memory; + }) != ir_module.imports.cend(); auto memory_origin = imports_memory ? InstanceEnvironmentFactory::MemoryOrigin::EXTERNAL diff --git a/core/scale/big_fixed_integers.hpp b/core/scale/big_fixed_integers.hpp index 2279e705f2..153c332c03 100644 --- a/core/scale/big_fixed_integers.hpp +++ b/core/scale/big_fixed_integers.hpp @@ -84,9 +84,8 @@ namespace scale { template using Compact = IntWrapper; - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &stream, Fixed &fixed) { for (size_t i = 0; i < Fixed::kByteSize * 8; i += 8) { *fixed |= N(stream.nextByte()) << i; @@ -94,9 +93,8 @@ namespace scale { return stream; } - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &stream, const Fixed &fixed) { constexpr size_t bits = Fixed::kByteSize * 8; for (size_t i = 0; i < bits; i += 8) { @@ -105,9 +103,8 @@ namespace scale { return stream; } - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &stream, Compact &compact) { scale::CompactInteger n; stream >> n; @@ -115,9 +112,8 @@ namespace scale { return stream; } - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &stream, const Compact &compact) { scale::CompactInteger n = *compact; stream << n; diff --git a/core/scale/libp2p_types.cpp b/core/scale/libp2p_types.cpp index 31fefd1e63..b763939316 100644 --- a/core/scale/libp2p_types.cpp +++ b/core/scale/libp2p_types.cpp @@ -11,7 +11,8 @@ namespace scale { - PeerInfoSerializable::PeerInfoSerializable() : PeerInfo{dummyPeerId(), {}} {} + PeerInfoSerializable::PeerInfoSerializable() + : PeerInfo{.id = dummyPeerId(), .addresses = {}} {} libp2p::peer::PeerId PeerInfoSerializable::dummyPeerId() { // some valid dummy peer id @@ -24,6 +25,7 @@ namespace scale { scale::ScaleEncoderStream &operator<<( scale::ScaleEncoderStream &s, const libp2p::peer::PeerInfo &peer_info) { std::vector addresses; + addresses.reserve(peer_info.addresses.size()); for (const auto &addr : peer_info.addresses) { addresses.emplace_back(addr.getStringAddress()); } @@ -39,14 +41,13 @@ namespace scale { peer_info.id = std::move(peer_id_res.value()); std::vector multi_addrs; multi_addrs.reserve(addresses.size()); - std::for_each( - addresses.begin(), addresses.end(), [&multi_addrs](const auto &addr) { - // filling in only supported kinds of addresses - auto res = libp2p::multi::Multiaddress::create(addr); - if (res) { - multi_addrs.emplace_back(std::move(res.value())); - } - }); + std::ranges::for_each(addresses, [&multi_addrs](const auto &addr) { + // filling in only supported kinds of addresses + auto res = libp2p::multi::Multiaddress::create(addr); + if (res) { + multi_addrs.emplace_back(std::move(res.value())); + } + }); peer_info.addresses = std::move(multi_addrs); return s; } diff --git a/core/scale/std_variant.hpp b/core/scale/std_variant.hpp index 6a3222c287..8ce88a16db 100644 --- a/core/scale/std_variant.hpp +++ b/core/scale/std_variant.hpp @@ -31,11 +31,13 @@ namespace scale { template requires Stream::is_decoder_stream Stream &operator>>(Stream &stream, std::variant &variant) { - uint8_t index; + uint8_t index; // NOLINT(cppcoreguidelines-init-variables) stream >> index; using Decoder = void (*)(Stream &stream, std::variant &variant); + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) constexpr Decoder decoders[]{ make_decoder()...}; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) decoders[index](stream, variant); return stream; } diff --git a/core/scale/tie.hpp b/core/scale/tie.hpp index cdc50693ba..5601c67b67 100644 --- a/core/scale/tie.hpp +++ b/core/scale/tie.hpp @@ -45,6 +45,7 @@ namespace scale { typename = decltype(std::declval>>() .as_tie())> + // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) auto as_tie(T &&v, F &&f) { return f(const_cast> &>(v) .as_tie()); @@ -54,6 +55,7 @@ namespace scale { template ::scale_tie> + // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) auto as_tie(T &&v, F &&f) { if constexpr (N == 0) { return std::tie(); diff --git a/core/storage/database_error.hpp b/core/storage/database_error.hpp index db613c7b40..5a7ba3d097 100644 --- a/core/storage/database_error.hpp +++ b/core/storage/database_error.hpp @@ -13,7 +13,7 @@ namespace kagome::storage { /** * @brief universal database interface error */ - enum class DatabaseError : int { + enum class DatabaseError : int { // NOLINT(performance-enum-size) OK = 0, NOT_FOUND = 1, CORRUPTION = 2, diff --git a/core/storage/in_memory/cursor.hpp b/core/storage/in_memory/cursor.hpp index 904277c176..52b7b79ae9 100644 --- a/core/storage/in_memory/cursor.hpp +++ b/core/storage/in_memory/cursor.hpp @@ -66,6 +66,7 @@ namespace kagome::storage { return isValid(); } + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) InMemoryStorage &db; std::optional> kv; }; diff --git a/core/storage/in_memory/in_memory_batch.hpp b/core/storage/in_memory/in_memory_batch.hpp index d2a7717ddd..f73e2c42c6 100644 --- a/core/storage/in_memory/in_memory_batch.hpp +++ b/core/storage/in_memory/in_memory_batch.hpp @@ -18,7 +18,7 @@ namespace kagome::storage { outcome::result put(const BufferView &key, BufferOrView &&value) override { - entries[key.toHex()] = value.intoBuffer(); + entries[key.toHex()] = std::move(value).intoBuffer(); return outcome::success(); } @@ -41,6 +41,7 @@ namespace kagome::storage { private: std::map entries; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) InMemoryStorage &db; }; } // namespace kagome::storage diff --git a/core/storage/in_memory/in_memory_storage.cpp b/core/storage/in_memory/in_memory_storage.cpp index 94ba45710d..e1862a3a65 100644 --- a/core/storage/in_memory/in_memory_storage.cpp +++ b/core/storage/in_memory/in_memory_storage.cpp @@ -41,7 +41,7 @@ namespace kagome::storage { size_ -= old_value_size; } size_ += value.size(); - storage[key.toHex()] = value.intoBuffer(); + storage[key.toHex()] = std::move(value).intoBuffer(); return outcome::success(); } diff --git a/core/storage/map_prefix/prefix.hpp b/core/storage/map_prefix/prefix.hpp index d8ef612f9b..48d42b5b5e 100644 --- a/core/storage/map_prefix/prefix.hpp +++ b/core/storage/map_prefix/prefix.hpp @@ -26,6 +26,7 @@ namespace kagome::storage { std::optional key() const override; std::optional value() const override; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) MapPrefix ↦ std::unique_ptr cursor; }; @@ -39,6 +40,7 @@ namespace kagome::storage { outcome::result commit() override; void clear() override; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) MapPrefix ↦ std::unique_ptr batch; }; diff --git a/core/storage/predefined_keys.hpp b/core/storage/predefined_keys.hpp index 5967ec210e..751d594747 100644 --- a/core/storage/predefined_keys.hpp +++ b/core/storage/predefined_keys.hpp @@ -11,7 +11,7 @@ #include namespace kagome::storage { - using namespace common::literals; + using common::literals::operator""_buf; inline const common::Buffer kRuntimeCodeKey = ":code"_buf; inline const common::Buffer kRuntimeHeappagesKey = ":heappages"_buf; diff --git a/core/storage/rocksdb/rocksdb.cpp b/core/storage/rocksdb/rocksdb.cpp index 067ded4107..cbb69245cb 100644 --- a/core/storage/rocksdb/rocksdb.cpp +++ b/core/storage/rocksdb/rocksdb.cpp @@ -18,7 +18,7 @@ #include "utils/mkdirs.hpp" namespace kagome::storage { - namespace fs = filesystem; + namespace fs = std::filesystem; RocksDb::RocksDb() : logger_(log::createLogger("RocksDB", "storage")) { ro_.fill_cache = false; @@ -56,15 +56,17 @@ namespace kagome::storage { // calculate state cache size per space const auto memory_budget = memory_budget_mib * 1024 * 1024; - const uint32_t trie_space_cache_size = memory_budget * 0.9; + const auto trie_space_cache_size = + static_cast(memory_budget * 0.9); const uint32_t other_spaces_cache_size = (memory_budget - trie_space_cache_size) / (storage::Space::kTotal - 1); std::vector column_family_descriptors; + column_family_descriptors.reserve(Space::kTotal); for (auto i = 0; i < Space::kTotal; ++i) { - column_family_descriptors.emplace_back(rocksdb::ColumnFamilyDescriptor{ + column_family_descriptors.emplace_back( spaceName(static_cast(i)), configureColumn(i != Space::kTrieNode ? other_spaces_cache_size - : trie_space_cache_size)}); + : trie_space_cache_size)); } std::vector existing_families; @@ -78,14 +80,14 @@ namespace kagome::storage { return status_as_error(res); } for (auto &family : existing_families) { - if (std::find_if(column_family_descriptors.begin(), - column_family_descriptors.end(), - [&family](rocksdb::ColumnFamilyDescriptor &desc) { - return desc.name == family; - }) + if (std::ranges::find_if( + column_family_descriptors, + [&family](rocksdb::ColumnFamilyDescriptor &desc) { + return desc.name == family; + }) == column_family_descriptors.end()) { - column_family_descriptors.emplace_back(rocksdb::ColumnFamilyDescriptor{ - family, configureColumn(other_spaces_cache_size)}); + column_family_descriptors.emplace_back( + family, configureColumn(other_spaces_cache_size)); } } @@ -113,12 +115,11 @@ namespace kagome::storage { return spaces_[space]; } auto space_name = spaceName(space); - auto column = - std::find_if(column_family_handles_.begin(), - column_family_handles_.end(), - [&space_name](const ColumnFamilyHandlePtr &handle) { - return handle->GetName() == space_name; - }); + auto column = std::ranges::find_if( + column_family_handles_, + [&space_name](const ColumnFamilyHandlePtr &handle) { + return handle->GetName() == space_name; + }); if (column_family_handles_.end() == column) { throw DatabaseError::INVALID_ARGUMENT; } @@ -130,17 +131,16 @@ namespace kagome::storage { void RocksDb::dropColumn(kagome::storage::Space space) { auto space_name = spaceName(space); - auto column_it = - std::find_if(column_family_handles_.begin(), - column_family_handles_.end(), - [&space_name](const ColumnFamilyHandlePtr &handle) { - return handle->GetName() == space_name; - }); + auto column_it = std::ranges::find_if( + column_family_handles_, + [&space_name](const ColumnFamilyHandlePtr &handle) { + return handle->GetName() == space_name; + }); if (column_family_handles_.end() == column_it) { throw DatabaseError::INVALID_ARGUMENT; } auto &handle = *column_it; - auto e = [this](rocksdb::Status status) { + auto e = [this](const rocksdb::Status &status) { if (!status.ok()) { logger_->error("DB operation failed: {}", status.ToString()); throw status_as_error(status); @@ -267,7 +267,7 @@ namespace kagome::storage { BufferOrView &&value) { OUTCOME_TRY(rocks, use()); auto status = rocks->db_->Put( - rocks->wo_, column_, make_slice(key), make_slice(value)); + rocks->wo_, column_, make_slice(key), make_slice(std::move(value))); if (status.ok()) { return outcome::success(); } diff --git a/core/storage/rocksdb/rocksdb.hpp b/core/storage/rocksdb/rocksdb.hpp index 0fc184d86f..ab57020a12 100644 --- a/core/storage/rocksdb/rocksdb.hpp +++ b/core/storage/rocksdb/rocksdb.hpp @@ -120,6 +120,7 @@ namespace kagome::storage { outcome::result> use() const; std::weak_ptr storage_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) const RocksDb::ColumnFamilyHandlePtr &column_; log::Logger logger_; }; diff --git a/core/storage/rocksdb/rocksdb_batch.cpp b/core/storage/rocksdb/rocksdb_batch.cpp index 59867f4704..4910dfad84 100644 --- a/core/storage/rocksdb/rocksdb_batch.cpp +++ b/core/storage/rocksdb/rocksdb_batch.cpp @@ -15,7 +15,7 @@ namespace kagome::storage { outcome::result RocksDbBatch::put(const BufferView &key, BufferOrView &&value) { - batch_.Put(db_.column_, make_slice(key), make_slice(value)); + batch_.Put(db_.column_, make_slice(key), make_slice(std::move(value))); return outcome::success(); } diff --git a/core/storage/rocksdb/rocksdb_batch.hpp b/core/storage/rocksdb/rocksdb_batch.hpp index 59101fd2b3..e19476a5a6 100644 --- a/core/storage/rocksdb/rocksdb_batch.hpp +++ b/core/storage/rocksdb/rocksdb_batch.hpp @@ -27,6 +27,7 @@ namespace kagome::storage { outcome::result remove(const BufferView &key) override; private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) RocksDbSpace &db_; rocksdb::WriteBatch batch_; }; diff --git a/core/storage/trie/child_prefix.cpp b/core/storage/trie/child_prefix.cpp index 1145e32070..d6a0a2fc11 100644 --- a/core/storage/trie/child_prefix.cpp +++ b/core/storage/trie/child_prefix.cpp @@ -10,8 +10,6 @@ #include "storage/trie/polkadot_trie/trie_node.hpp" namespace kagome::storage::trie { - ChildPrefix::ChildPrefix() : state_{0} {} - ChildPrefix::ChildPrefix(bool v) : state_{v ? kTrue : kFalse} {} void ChildPrefix::match(uint8_t nibble) { diff --git a/core/storage/trie/child_prefix.hpp b/core/storage/trie/child_prefix.hpp index 6b75cb3909..49319bdc1f 100644 --- a/core/storage/trie/child_prefix.hpp +++ b/core/storage/trie/child_prefix.hpp @@ -13,7 +13,7 @@ namespace kagome::storage::trie { * ":child_storage:" prefix matcher */ struct ChildPrefix { - ChildPrefix(); + ChildPrefix() = default; ChildPrefix(bool v); void match(uint8_t nibble); diff --git a/core/storage/trie/compact_decode.cpp b/core/storage/trie/compact_decode.cpp index 4b72696da9..99d79fe9b6 100644 --- a/core/storage/trie/compact_decode.cpp +++ b/core/storage/trie/compact_decode.cpp @@ -48,7 +48,12 @@ namespace kagome::storage::trie { db.emplace(hash, std::make_pair(std::move(value), nullptr)); node->setValue({std::nullopt, hash}); } - cursor.push({node, 0, false, {}}); + cursor.push({ + .node = node, + .branch = 0, + .child = false, + .t = {}, + }); return outcome::success(); }; OUTCOME_TRY(push()); diff --git a/core/storage/trie/compact_decode.hpp b/core/storage/trie/compact_decode.hpp index ed48f635e5..f1b3889f35 100644 --- a/core/storage/trie/compact_decode.hpp +++ b/core/storage/trie/compact_decode.hpp @@ -14,7 +14,7 @@ namespace kagome::storage::trie { struct TrieNode; - enum class CompactDecodeError { + enum class CompactDecodeError : uint8_t { INCOMPLETE_PROOF = 1, }; diff --git a/core/storage/trie/compact_encode.cpp b/core/storage/trie/compact_encode.cpp index 582d9509bb..c0e8bbe2c4 100644 --- a/core/storage/trie/compact_encode.cpp +++ b/core/storage/trie/compact_encode.cpp @@ -42,7 +42,11 @@ namespace kagome::storage::trie { } auto &level = levels.back(); auto &proof = proofs[levels.size() - 1]; - level.push({std::move(node), std::nullopt, level.child, proof.size()}); + level.push({ + .node = std::move(node), + .child = level.child, + .t = proof.size(), + }); proof.emplace_back(); if (compact) { proof.back().putUint8(kEscapeCompactHeader); diff --git a/core/storage/trie/impl/ephemeral_trie_batch_impl.hpp b/core/storage/trie/impl/ephemeral_trie_batch_impl.hpp index f44cfd427c..745ae06cd9 100644 --- a/core/storage/trie/impl/ephemeral_trie_batch_impl.hpp +++ b/core/storage/trie/impl/ephemeral_trie_batch_impl.hpp @@ -32,7 +32,7 @@ namespace kagome::storage::trie { outcome::result commit(StateVersion version) override; protected: - virtual outcome::result> createFromTrieHash( + outcome::result> createFromTrieHash( const RootHash &trie_hash) override; private: diff --git a/core/storage/trie/impl/persistent_trie_batch_impl.hpp b/core/storage/trie/impl/persistent_trie_batch_impl.hpp index 16d5ae0ffd..a0d64ac754 100644 --- a/core/storage/trie/impl/persistent_trie_batch_impl.hpp +++ b/core/storage/trie/impl/persistent_trie_batch_impl.hpp @@ -25,7 +25,7 @@ namespace kagome::storage::trie { class PersistentTrieBatchImpl final : public TrieBatchBase { public: - enum class Error { + enum class Error : uint8_t { NO_TRIE = 1, }; @@ -47,7 +47,7 @@ namespace kagome::storage::trie { outcome::result remove(const BufferView &key) override; protected: - virtual outcome::result> createFromTrieHash( + outcome::result> createFromTrieHash( const RootHash &trie_hash) override; private: diff --git a/core/storage/trie/impl/topper_trie_batch_impl.cpp b/core/storage/trie/impl/topper_trie_batch_impl.cpp index 62d8428bde..48813eec8d 100644 --- a/core/storage/trie/impl/topper_trie_batch_impl.cpp +++ b/core/storage/trie/impl/topper_trie_batch_impl.cpp @@ -84,7 +84,7 @@ namespace kagome::storage::trie { outcome::result TopperTrieBatchImpl::put(const BufferView &key, BufferOrView &&value) { - cache_.insert_or_assign(Buffer{key}, value.intoBuffer()); + cache_.insert_or_assign(Buffer{key}, std::move(value).intoBuffer()); return outcome::success(); } diff --git a/core/storage/trie/impl/topper_trie_batch_impl.hpp b/core/storage/trie/impl/topper_trie_batch_impl.hpp index 95ec49ea93..97bd487ea4 100644 --- a/core/storage/trie/impl/topper_trie_batch_impl.hpp +++ b/core/storage/trie/impl/topper_trie_batch_impl.hpp @@ -17,7 +17,7 @@ namespace kagome::storage::trie { : public TrieBatch, public std::enable_shared_from_this { public: - enum class Error { + enum class Error : uint8_t { PARENT_EXPIRED = 1, CHILD_BATCH_NOT_SUPPORTED, COMMIT_NOT_SUPPORTED, @@ -43,10 +43,10 @@ namespace kagome::storage::trie { outcome::result writeBack(); - virtual outcome::result commit(StateVersion version) override; + outcome::result commit(StateVersion version) override; - virtual outcome::result>> - createChildBatch(common::BufferView path) override; + outcome::result>> createChildBatch( + common::BufferView path) override; outcome::result apply(storage::BufferStorage &map); diff --git a/core/storage/trie/impl/trie_batch_base.hpp b/core/storage/trie/impl/trie_batch_base.hpp index 6b3ea8d0ac..13ff6a2855 100644 --- a/core/storage/trie/impl/trie_batch_base.hpp +++ b/core/storage/trie/impl/trie_batch_base.hpp @@ -25,10 +25,12 @@ namespace kagome::storage::trie { std::shared_ptr trie); TrieBatchBase(const TrieBatchBase &) = delete; - TrieBatchBase(TrieBatchBase &&) = default; + TrieBatchBase(TrieBatchBase &&) noexcept = default; + + ~TrieBatchBase() override = default; TrieBatchBase &operator=(const TrieBatchBase &) = delete; - TrieBatchBase &operator=(TrieBatchBase &&) = default; + TrieBatchBase &operator=(TrieBatchBase &&) noexcept = default; outcome::result get(const BufferView &key) const override; outcome::result> tryGet( @@ -36,8 +38,8 @@ namespace kagome::storage::trie { std::unique_ptr trieCursor() override; outcome::result contains(const BufferView &key) const override; - virtual outcome::result>> - createChildBatch(common::BufferView path) override; + outcome::result>> createChildBatch( + common::BufferView path) override; protected: virtual outcome::result> createFromTrieHash( diff --git a/core/storage/trie/on_read.hpp b/core/storage/trie/on_read.hpp index 6bd7ea5e63..02a1c90d8f 100644 --- a/core/storage/trie/on_read.hpp +++ b/core/storage/trie/on_read.hpp @@ -35,6 +35,7 @@ namespace kagome::storage::trie { */ auto vec() { std::vector vec; + vec.reserve(db.size()); for (auto &p : db) { vec.emplace_back(std::move(p.second)); } diff --git a/core/storage/trie/polkadot_trie/polkadot_trie_cursor.hpp b/core/storage/trie/polkadot_trie/polkadot_trie_cursor.hpp index b39c8a370f..6f7674caf8 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_cursor.hpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_cursor.hpp @@ -15,8 +15,6 @@ namespace kagome::storage::trie { class PolkadotTrieCursor : public BufferStorageCursor { public: - virtual ~PolkadotTrieCursor() override = default; - /** * Seek the first element with key not less than \arg key * @return true if the trie is not empty diff --git a/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.cpp b/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.cpp index 36245d2f0f..76fc287a28 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.cpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.cpp @@ -149,10 +149,9 @@ namespace kagome::storage::trie { (int)child_idx); if (child_idx > sought_nibbles[mismatch_pos]) { return nextNodeWithValueInSubTree(*child); - } else { - return seekLowerBoundInternal( - *child, sought_nibbles.subspan(mismatch_pos + 1)); } + return seekLowerBoundInternal( + *child, sought_nibbles.subspan(mismatch_pos + 1)); } } } @@ -314,9 +313,8 @@ namespace kagome::storage::trie { for (const auto &node_idx : search_state.getPath()) { const auto &node = node_idx.parent; auto idx = node_idx.child_idx; - std::copy(node.getKeyNibbles().begin(), - node.getKeyNibbles().end(), - std::back_inserter(key_nibbles)); + std::ranges::copy(node.getKeyNibbles(), + std::back_inserter(key_nibbles)); key_nibbles.putUint8(idx); } key_nibbles.put(search_state.getCurrent().getKeyNibbles()); @@ -337,9 +335,9 @@ namespace kagome::storage::trie { const auto &value_opt = search_state->getCurrent().getValue(); if (value_opt) { // TODO(turuslan): #1470, return error - if (auto r = - trie_->retrieveValue(const_cast(value_opt)); - !r) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + auto r = trie_->retrieveValue(const_cast(value_opt)); + if (r.has_error()) { SL_WARN(log_, "PolkadotTrieCursorImpl::value {}: {}", common::hex_lower_0x(collectKey()), diff --git a/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.hpp b/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.hpp index e72b9c4838..458568da5f 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.hpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.hpp @@ -17,7 +17,7 @@ namespace kagome::storage::trie { class PolkadotTrieCursorImpl : public PolkadotTrieCursor { public: - enum class Error { + enum class Error : uint8_t { // cursor stumbled upon a node with a type invalid in the given context // (e.g. a leaf node where a branch node should've been) INVALID_NODE_TYPE = 1, @@ -83,6 +83,7 @@ namespace kagome::storage::trie { TriePathEntry(const BranchNode &parent, uint8_t child_idx) : parent{parent}, child_idx{child_idx} {} + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) const BranchNode &parent; uint8_t child_idx; }; diff --git a/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp b/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp index 83a8e83ffb..e99444d764 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp @@ -36,11 +36,11 @@ namespace kagome::storage::trie { static outcome::result> createAt( std::shared_ptr root, - PolkadotTrie::NodeRetrieveFunction node_retriever, + const PolkadotTrie::NodeRetrieveFunction &node_retriever, PolkadotTrie::ValueRetrieveFunction value_retriever) { OUTCOME_TRY(root_node, node_retriever(root)); - return std::unique_ptr{ - new OpaqueNodeStorage{node_retriever, value_retriever, root_node}}; + return std::make_unique( + node_retriever, std::move(value_retriever), std::move(root_node)); } [[nodiscard]] const std::shared_ptr &getRoot() { @@ -60,6 +60,7 @@ namespace kagome::storage::trie { // SAFETY: changing a parent's opaque child node from a handle to a node // to the actual node doesn't break it's const correctness, because opaque // nodes are meant to hide their content + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) auto &mut_parent = const_cast(parent); auto &opaque_child = parent.children.at(idx); OUTCOME_TRY(child, retrieve_node_(opaque_child)); @@ -84,12 +85,12 @@ namespace kagome::storage::trie { } // namespace kagome::storage::trie namespace { + // NOLINTNEXTLINE(google-build-using-namespace) using namespace kagome::storage::trie; uint32_t getCommonPrefixLength(const NibblesView &first, const NibblesView &second) { - auto &&[it, _] = - std::mismatch(first.begin(), first.end(), second.begin(), second.end()); + auto &&[it, _] = std::ranges::mismatch(first, second); return it - first.begin(); } @@ -177,6 +178,7 @@ namespace { logger, "deleteNode: go to child {:x}", (int)sought_key[length]); OUTCOME_TRY(deleteNode( logger, child, sought_key.subspan(length + 1), node_storage)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) branch.children[sought_key[length]] = child; } OUTCOME_TRY(handleDeletion(logger, node, node_storage)); @@ -220,8 +222,7 @@ namespace { return outcome::success(); } - if (std::greater_equal()(parent->getKeyNibbles().size(), - prefix.size())) { + if (std::greater_equal<>()(parent->getKeyNibbles().size(), prefix.size())) { // if this is the node to be detached -- detach it if (std::equal( prefix.begin(), prefix.end(), parent->getKeyNibbles().begin())) { @@ -230,6 +231,7 @@ namespace { auto &branch = dynamic_cast(*parent); for (uint8_t child_idx = 0; child_idx < branch.kMaxChildren; child_idx++) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) if (branch.children[child_idx] != nullptr) { OUTCOME_TRY(child_node, node_storage.getChild(branch, child_idx)); OUTCOME_TRY(detachNode(logger, @@ -241,6 +243,7 @@ namespace { callback, trie, node_storage)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) branch.children[child_idx] = child_node; } } @@ -287,6 +290,7 @@ namespace { callback, trie, node_storage)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) branch.children[prefix[length]] = child_node; OUTCOME_TRY(handleDeletion(logger, parent, node_storage)); } @@ -297,8 +301,9 @@ namespace { } // namespace namespace kagome::storage::trie { - PolkadotTrieImpl::PolkadotTrieImpl(PolkadotTrieImpl &&) = default; - PolkadotTrieImpl &PolkadotTrieImpl::operator=(PolkadotTrieImpl &&) = default; + // PolkadotTrieImpl::PolkadotTrieImpl(PolkadotTrieImpl &&) noexcept = + // default; PolkadotTrieImpl &PolkadotTrieImpl::operator=(PolkadotTrieImpl + // &&) = default; std::shared_ptr PolkadotTrieImpl::createEmpty( RetrieveFunctions retrieve_functions) { @@ -309,7 +314,7 @@ namespace kagome::storage::trie { std::shared_ptr PolkadotTrieImpl::create( NodePtr root, RetrieveFunctions retrieve_functions) { return std::shared_ptr( - new PolkadotTrieImpl{root, std::move(retrieve_functions)}); + new PolkadotTrieImpl{std::move(root), std::move(retrieve_functions)}); } PolkadotTrieImpl::PolkadotTrieImpl(RetrieveFunctions retrieve_functions) @@ -324,10 +329,10 @@ namespace kagome::storage::trie { : nodes_{std::make_unique( std::move(retrieve_functions.retrieve_node), std::move(retrieve_functions.retrieve_value), - root)}, + std::move(root))}, logger_{log::createLogger("PolkadotTrie", "trie")} {} - PolkadotTrieImpl::~PolkadotTrieImpl() {} + // PolkadotTrieImpl::~PolkadotTrieImpl() {} PolkadotTrie::ConstNodePtr PolkadotTrieImpl::getRoot() const { return nodes_->getRoot(); @@ -349,7 +354,8 @@ namespace kagome::storage::trie { OUTCOME_TRY(n, insert(root, k_enc, - std::make_shared(k_enc, value.intoBuffer()))); + std::make_shared( + k_enc, std::move(value).intoBuffer()))); nodes_->setRoot(n); return outcome::success(); @@ -487,6 +493,7 @@ namespace kagome::storage::trie { auto nibbles = KeyNibbles::fromByteBuffer(key); OUTCOME_TRY(node, getNode(nodes_->getRoot(), nibbles)); if (node && node->getValue()) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) OUTCOME_TRY(retrieveValue(const_cast(node->getValue()))); return BufferView{*node->getValue().value}; } diff --git a/core/storage/trie/polkadot_trie/polkadot_trie_impl.hpp b/core/storage/trie/polkadot_trie/polkadot_trie_impl.hpp index e5519982d4..98022d3b59 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_impl.hpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_impl.hpp @@ -18,14 +18,18 @@ namespace kagome::storage::trie { class PolkadotTrieImpl final : public PolkadotTrie { public: - enum class Error { INVALID_NODE_TYPE = 1 }; + enum class Error : uint8_t { + INVALID_NODE_TYPE = 1, + }; - PolkadotTrieImpl(PolkadotTrieImpl &&); - PolkadotTrieImpl &operator=(PolkadotTrieImpl &&); + PolkadotTrieImpl(PolkadotTrieImpl &&) noexcept = default; + PolkadotTrieImpl &operator=(PolkadotTrieImpl &&) noexcept = default; PolkadotTrieImpl(const PolkadotTrieImpl &) = delete; PolkadotTrieImpl &operator=(const PolkadotTrieImpl &) = delete; + ~PolkadotTrieImpl() override = default; + /** * Creates an empty Trie. * @param f a functor that will be used to obtain a child of a branch node @@ -48,8 +52,6 @@ namespace kagome::storage::trie { static std::shared_ptr create( NodePtr root, RetrieveFunctions retrieve_functions = {}); - ~PolkadotTrieImpl(); - NodePtr getRoot() override; ConstNodePtr getRoot() const override; diff --git a/core/storage/trie/polkadot_trie/trie_error.hpp b/core/storage/trie/polkadot_trie/trie_error.hpp index d167e74ad1..4ae1539071 100644 --- a/core/storage/trie/polkadot_trie/trie_error.hpp +++ b/core/storage/trie/polkadot_trie/trie_error.hpp @@ -12,7 +12,7 @@ namespace kagome::storage::trie { /** * @brief TrieDbError enum provides error codes for TrieDb methods */ - enum class TrieError { + enum class TrieError : uint8_t { NO_VALUE = 1, // no stored value found by the given key VALUE_RETRIEVE_NOT_PROVIDED, // attempt to retrieve a value by hash with no // corresponding callback provided diff --git a/core/storage/trie/polkadot_trie/trie_node.cpp b/core/storage/trie/polkadot_trie/trie_node.cpp index af6030bcca..c7407d0e43 100644 --- a/core/storage/trie/polkadot_trie/trie_node.cpp +++ b/core/storage/trie/polkadot_trie/trie_node.cpp @@ -6,6 +6,8 @@ #include "storage/trie/polkadot_trie/trie_node.hpp" +#include + namespace kagome::storage::trie { uint16_t BranchNode::childrenBitmap() const { uint16_t bitmap = 0u; @@ -18,8 +20,7 @@ namespace kagome::storage::trie { } uint8_t BranchNode::childrenNum() const { - return std::count_if(children.begin(), - children.end(), - [](const auto &child) { return child; }); + return boost::range::count_if(children, + [](const auto &child) { return child; }); } } // namespace kagome::storage::trie diff --git a/core/storage/trie/polkadot_trie/trie_node.hpp b/core/storage/trie/polkadot_trie/trie_node.hpp index 9e1a480023..0c3a42aca2 100644 --- a/core/storage/trie/polkadot_trie/trie_node.hpp +++ b/core/storage/trie/polkadot_trie/trie_node.hpp @@ -87,7 +87,8 @@ namespace kagome::storage::trie { if (size == common::Hash256::size()) { return MerkleValue{common::Hash256::fromSpan(merkle_value).value(), size}; - } else if (size < common::Hash256::size()) { + } + if (size < common::Hash256::size()) { common::Hash256 hash; std::copy_n(merkle_value.begin(), size, hash.begin()); return MerkleValue{hash, size}; @@ -174,7 +175,7 @@ namespace kagome::storage::trie { TrieNode(KeyNibbles key_nibbles, ValueAndHash value) : key_nibbles_{std::move(key_nibbles)}, value_{std::move(value)} {} - enum class Type { + enum class Type : uint8_t { Special, // - Leaf, // 01 BranchEmptyValue, // 10 @@ -231,6 +232,7 @@ namespace kagome::storage::trie { uint8_t getNextChildIdxFrom(uint8_t child_idx) const { while (child_idx < kMaxChildren) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) if (children[child_idx]) { return child_idx; } diff --git a/core/storage/trie/raw_cursor.hpp b/core/storage/trie/raw_cursor.hpp index a0103f3c73..452a3e13dd 100644 --- a/core/storage/trie/raw_cursor.hpp +++ b/core/storage/trie/raw_cursor.hpp @@ -37,6 +37,7 @@ namespace kagome::storage::trie { if (item.node->isBranch() and i < BranchNode::kMaxChildren) { auto &branches = dynamic_cast(*item.node).children; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) auto &branch = branches[i]; if (not branch) { throw std::logic_error{"RawCursor::update branches[branch]=null"}; @@ -92,6 +93,7 @@ namespace kagome::storage::trie { auto &branches = dynamic_cast(*item.node).children; for (; *i < BranchNode::kMaxChildren; ++*i) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) if (not branches[*i]) { continue; } diff --git a/core/storage/trie/serialization/codec.hpp b/core/storage/trie/serialization/codec.hpp index f3b4f30c3f..ef9c5b767a 100644 --- a/core/storage/trie/serialization/codec.hpp +++ b/core/storage/trie/serialization/codec.hpp @@ -19,6 +19,7 @@ namespace kagome::storage::trie { */ class Codec { public: + // NOLINTBEGIN(cppcoreguidelines-avoid-const-or-ref-data-members) struct ChildData { const TrieNode &child; const MerkleValue &merkle_value; @@ -29,11 +30,15 @@ namespace kagome::storage::trie { common::Hash256 hash; const common::Buffer &value; }; + // NOLINTEND(cppcoreguidelines-avoid-const-or-ref-data-members) + using Visitee = std::variant; using ChildVisitor = std::function(Visitee)>; static constexpr auto NoopChildVisitor = - [](Visitee) -> outcome::result { return outcome::success(); }; + [](const Visitee &) -> outcome::result { + return outcome::success(); + }; virtual ~Codec() = default; diff --git a/core/storage/trie/serialization/polkadot_codec.cpp b/core/storage/trie/serialization/polkadot_codec.cpp index 2b85843401..20d78cc04a 100644 --- a/core/storage/trie/serialization/polkadot_codec.cpp +++ b/core/storage/trie/serialization/polkadot_codec.cpp @@ -95,6 +95,7 @@ namespace kagome::storage::trie { if (auto dummy = dynamic_cast(&node); dummy != nullptr) { return dummy->db_key; } + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) auto &trie_node = static_cast(node); OUTCOME_TRY(enc, encodeNode(trie_node, version, child_visitor)); return merkleValue(enc); @@ -127,9 +128,6 @@ namespace kagome::storage::trie { return Error::TOO_MANY_NIBBLES; } - uint8_t head; - uint8_t partial_length_mask; // max partial key length - auto type = getType(node); if (shouldBeHashed(node.getValue(), version)) { if (node.isBranch()) { @@ -139,6 +137,11 @@ namespace kagome::storage::trie { } } + uint8_t head; // NOLINT(cppcoreguidelines-init-variables) + + // max partial key length + uint8_t partial_length_mask; // NOLINT(cppcoreguidelines-init-variables) + // set bits of type switch (type) { case TrieNode::Type::Leaf: @@ -315,7 +318,7 @@ namespace kagome::storage::trie { outcome::result> PolkadotCodec::decodeHeader(BufferStream &stream) const { - TrieNode::Type type; + TrieNode::Type type; // NOLINT(cppcoreguidelines-init-variables) if (not stream.hasMore(1)) { return Error::INPUT_TOO_SMALL; } @@ -351,7 +354,7 @@ namespace kagome::storage::trie { if (pk_length == partial_key_length_mask) { uint8_t read_length{}; - do { + do { // NOLINT(cppcoreguidelines-avoid-do-while) if (not stream.hasMore(1)) { return Error::INPUT_TOO_SMALL; } diff --git a/core/storage/trie/serialization/polkadot_codec.hpp b/core/storage/trie/serialization/polkadot_codec.hpp index b2e49585e1..b2c15b79d6 100644 --- a/core/storage/trie/serialization/polkadot_codec.hpp +++ b/core/storage/trie/serialization/polkadot_codec.hpp @@ -24,7 +24,7 @@ namespace kagome::storage::trie { using Buffer = common::Buffer; using BufferView = common::BufferView; - enum class Error { + enum class Error : uint8_t { SUCCESS = 0, TOO_MANY_NIBBLES, ///< number of nibbles in key is >= 2**16 UNKNOWN_NODE_TYPE, ///< node type is unknown diff --git a/core/storage/trie/serialization/trie_serializer_impl.cpp b/core/storage/trie/serialization/trie_serializer_impl.cpp index fc546d78e5..2faa0cac32 100644 --- a/core/storage/trie/serialization/trie_serializer_impl.cpp +++ b/core/storage/trie/serialization/trie_serializer_impl.cpp @@ -79,11 +79,10 @@ namespace kagome::storage::trie { if (child_data->merkle_value.isHash()) { return batch->put(child_data->merkle_value.asBuffer(), std::move(child_data->encoding)); - } else { - return outcome::success(); // nodes which encoding is shorter - // than its hash are not stored in - // the DB separately } + return outcome::success(); // nodes which encoding is shorter + // than its hash are not stored in + // the DB separately } auto value_data = std::get(visitee); // value_data.value is a reference to a buffer stored outside of @@ -136,7 +135,7 @@ namespace kagome::storage::trie { if (on_node_loaded) { on_node_loaded(hash, value); } - return value.intoBuffer(); + return std::move(value).intoBuffer(); }); } diff --git a/core/storage/trie/trie_batches.hpp b/core/storage/trie/trie_batches.hpp index 6bcb203dcc..6c6b177066 100644 --- a/core/storage/trie/trie_batches.hpp +++ b/core/storage/trie/trie_batches.hpp @@ -14,8 +14,6 @@ namespace kagome::storage::trie { class TrieBatch : public BufferStorage { public: - ~TrieBatch() override = default; - std::unique_ptr cursor() final { return trieCursor(); } diff --git a/core/storage/trie/types.hpp b/core/storage/trie/types.hpp index e81d2456be..85e960123e 100644 --- a/core/storage/trie/types.hpp +++ b/core/storage/trie/types.hpp @@ -12,7 +12,7 @@ namespace kagome::storage::trie { using RootHash = common::Hash256; - enum class StateVersion { V0, V1 }; + enum class StateVersion : uint8_t { V0, V1 }; /// blake2b_256(0x00) constexpr RootHash kEmptyRootHash{{ diff --git a/core/storage/trie_pruner/impl/trie_pruner_impl.cpp b/core/storage/trie_pruner/impl/trie_pruner_impl.cpp index 64cad89c31..ea3da3d5e8 100644 --- a/core/storage/trie_pruner/impl/trie_pruner_impl.cpp +++ b/core/storage/trie_pruner/impl/trie_pruner_impl.cpp @@ -37,12 +37,11 @@ OUTCOME_CPP_DEFINE_CATEGORY(kagome::storage::trie_pruner, namespace kagome::storage::trie_pruner { - template , - F, - common::BufferView, - const trie::RootHash &>, - bool> = true> + template + requires std::is_invocable_r_v, + F, + common::BufferView, + const trie::RootHash &> outcome::result forEachChildTrie(const trie::PolkadotTrie &parent, const F &f) { auto child_tries = parent.trieCursor(); @@ -66,11 +65,11 @@ namespace kagome::storage::trie_pruner { std::shared_ptr storage, std::shared_ptr hasher, std::shared_ptr config) - : node_storage_{node_storage}, - serializer_{serializer}, - codec_{codec}, - storage_{storage}, - hasher_{hasher}, + : node_storage_{std::move(node_storage)}, + serializer_{std::move(serializer)}, + codec_{std::move(codec)}, + storage_{std::move(storage)}, + hasher_{std::move(hasher)}, pruning_depth_{config->statePruningDepth()}, thorough_pruning_{config->enableThoroughPruning()} { BOOST_ASSERT(node_storage_ != nullptr); @@ -111,10 +110,10 @@ namespace kagome::storage::trie_pruner { return true; } - class Encoder { + class Encoder { // NOLINT(cppcoreguidelines-special-member-functions) public: explicit Encoder(const trie::Codec &codec, log::Logger logger) - : codec{codec}, logger{logger} {} + : codec{codec}, logger{std::move(logger)} {} ~Encoder() { SL_DEBUG(logger, "Encode called {} times", encode_called); @@ -158,6 +157,7 @@ namespace kagome::storage::trie_pruner { } private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) const trie::Codec &codec; size_t encode_called = 0; log::Logger logger; @@ -286,8 +286,9 @@ namespace kagome::storage::trie_pruner { } } if (node->isBranch()) { - auto branch = static_cast(*node); - for (auto opaque_child : branch.children) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) + const auto &branch = static_cast(*node); + for (const auto &opaque_child : branch.children) { if (opaque_child != nullptr) { auto dummy_child = dynamic_cast(opaque_child.get()); @@ -418,8 +419,9 @@ namespace kagome::storage::trie_pruner { bool is_new_branch_node = node != nullptr && node->isBranch() && ref_count == 1; if (is_new_branch_node) { - auto branch = static_cast(node.get()); - for (auto opaque_child : branch->children) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) + const auto &branch = static_cast(node.get()); + for (const auto &opaque_child : branch->children) { if (opaque_child != nullptr) { OUTCOME_TRY(child, serializer_->retrieveNode(opaque_child)); OUTCOME_TRY(child_merkle_val, diff --git a/core/storage/trie_pruner/impl/trie_pruner_impl.hpp b/core/storage/trie_pruner/impl/trie_pruner_impl.hpp index 9bf4d8642c..d52ddb9887 100644 --- a/core/storage/trie_pruner/impl/trie_pruner_impl.hpp +++ b/core/storage/trie_pruner/impl/trie_pruner_impl.hpp @@ -47,7 +47,7 @@ namespace kagome::storage::trie_pruner { class TriePrunerImpl final : public TriePruner { public: - enum class Error { + enum class Error : uint8_t { LAST_PRUNED_BLOCK_IS_LAST_FINALIZED = 1, }; @@ -71,18 +71,16 @@ namespace kagome::storage::trie_pruner { bool prepare(); - virtual outcome::result addNewState( - const storage::trie::RootHash &state_root, - trie::StateVersion version) override; + outcome::result addNewState(const storage::trie::RootHash &state_root, + trie::StateVersion version) override; - virtual outcome::result addNewState( - const trie::PolkadotTrie &new_trie, - trie::StateVersion version) override; + outcome::result addNewState(const trie::PolkadotTrie &new_trie, + trie::StateVersion version) override; - virtual outcome::result pruneFinalized( + outcome::result pruneFinalized( const primitives::BlockHeader &state) override; - virtual outcome::result pruneDiscarded( + outcome::result pruneDiscarded( const primitives::BlockHeader &state) override; std::optional getLastPrunedBlock() const override { diff --git a/core/telemetry/endpoint.hpp b/core/telemetry/endpoint.hpp index 616383bfa4..9b2a76d70d 100644 --- a/core/telemetry/endpoint.hpp +++ b/core/telemetry/endpoint.hpp @@ -25,7 +25,7 @@ namespace kagome::telemetry { return uri_; } - uint8_t verbosity() { + uint8_t verbosity() const { return verbosity_level_; } diff --git a/core/telemetry/impl/connection_impl.cpp b/core/telemetry/impl/connection_impl.cpp index 166504070a..24e62e3388 100644 --- a/core/telemetry/impl/connection_impl.cpp +++ b/core/telemetry/impl/connection_impl.cpp @@ -16,12 +16,12 @@ namespace kagome::telemetry { TelemetryConnectionImpl::TelemetryConnectionImpl( std::shared_ptr io_context, - const TelemetryEndpoint &endpoint, + TelemetryEndpoint endpoint, OnConnectedCallback callback, std::shared_ptr message_pool, std::shared_ptr scheduler) : io_context_{std::move(io_context)}, - endpoint_{endpoint}, + endpoint_{std::move(endpoint)}, callback_{std::move(callback)}, message_pool_{std::move(message_pool)}, scheduler_{std::move(scheduler)}, @@ -188,7 +188,7 @@ namespace kagome::telemetry { void TelemetryConnectionImpl::onResolve( boost::beast::error_code ec, - boost::asio::ip::tcp::resolver::results_type results) { + const boost::asio::ip::tcp::resolver::results_type &results) { if (ec) { SL_ERROR(log_, "Unable to resolve host: {}", ec); reconnect(); @@ -204,7 +204,8 @@ namespace kagome::telemetry { void TelemetryConnectionImpl::onConnect( boost::beast::error_code ec, - boost::asio::ip::tcp::resolver::results_type::endpoint_type endpoint) { + const boost::asio::ip::tcp::resolver::results_type::endpoint_type + &endpoint) { if (ec) { SL_ERROR(log_, "Unable to connect to endpoint: {}", ec); reconnect(); diff --git a/core/telemetry/impl/connection_impl.hpp b/core/telemetry/impl/connection_impl.hpp index 4fab55a9f6..5879033a90 100644 --- a/core/telemetry/impl/connection_impl.hpp +++ b/core/telemetry/impl/connection_impl.hpp @@ -55,12 +55,16 @@ namespace kagome::telemetry { */ TelemetryConnectionImpl( std::shared_ptr io_context, - const TelemetryEndpoint &endpoint, + TelemetryEndpoint endpoint, OnConnectedCallback callback, std::shared_ptr message_pool, std::shared_ptr scheduler); TelemetryConnectionImpl(const TelemetryConnectionImpl &) = delete; - TelemetryConnectionImpl(TelemetryConnectionImpl &&) = delete; + TelemetryConnectionImpl(TelemetryConnectionImpl &&) noexcept = delete; + TelemetryConnectionImpl &operator=(const TelemetryConnectionImpl &) = + delete; + TelemetryConnectionImpl &operator=(TelemetryConnectionImpl &&) noexcept = + delete; /// Initiate connection process void connect() override; @@ -102,11 +106,12 @@ namespace kagome::telemetry { void write(WsStreamT &ws, MessageHandle message_handle); void onResolve(boost::beast::error_code ec, - boost::asio::ip::tcp::resolver::results_type results); + const boost::asio::ip::tcp::resolver::results_type &results); void onConnect( boost::beast::error_code ec, - boost::asio::ip::tcp::resolver::results_type::endpoint_type endpoint); + const boost::asio::ip::tcp::resolver::results_type::endpoint_type + &endpoint); template void setOptionsAndRunWsHandshake(WsStreamT &ws); diff --git a/core/telemetry/impl/message_pool.cpp b/core/telemetry/impl/message_pool.cpp index f9cb799327..9291cc709b 100644 --- a/core/telemetry/impl/message_pool.cpp +++ b/core/telemetry/impl/message_pool.cpp @@ -52,20 +52,21 @@ namespace kagome::telemetry { MessagePool::RefCount MessagePool::add_ref(MessageHandle handle) { bool handle_is_valid = - (handle < pool_.size()) and (free_slots_.count(handle) == 0); + (handle < pool_.size()) and not free_slots_.contains(handle); if (not handle_is_valid) { return 0; // zero references for bad handle } std::lock_guard lock(mutex_); // allowed to call only over already occupied slots - BOOST_ASSERT(free_slots_.count(handle) == 0); + BOOST_ASSERT(not free_slots_.contains(handle)); auto &entry = pool_[handle]; + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) return ++entry.ref_count; } MessagePool::RefCount MessagePool::release(MessageHandle handle) { bool handle_is_valid = - (handle < pool_.size()) and (free_slots_.count(handle) == 0); + (handle < pool_.size()) and not free_slots_.contains(handle); if (not handle_is_valid) { return 0; // zero references for bad handle } @@ -76,13 +77,14 @@ namespace kagome::telemetry { entry.data_size = 0; free_slots_.emplace(handle); } + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) return entry.ref_count; } boost::asio::mutable_buffer MessagePool::operator[]( MessageHandle handle) const { bool handle_is_valid = - (handle < pool_.size()) and (free_slots_.count(handle) == 0); + (handle < pool_.size()) and not free_slots_.contains(handle); if (not handle_is_valid) { throw std::runtime_error("Bad access through invalid handle"); } @@ -92,9 +94,9 @@ namespace kagome::telemetry { // The buffer will remain valid till all holders request its release. // The handle cannot be reassigned prior to complete release. // => There is no chance to get dangling pointers inside boost buffers. - auto &entry = pool_[handle]; - return boost::asio::buffer(const_cast(entry.data.data()), - entry.data_size); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + auto &entry = const_cast(pool_[handle]); + return boost::asio::buffer(entry.data.data(), entry.data_size); } std::size_t MessagePool::capacity() const { diff --git a/core/telemetry/impl/service_impl.cpp b/core/telemetry/impl/service_impl.cpp index ba28d1302a..d1a69acd35 100644 --- a/core/telemetry/impl/service_impl.cpp +++ b/core/telemetry/impl/service_impl.cpp @@ -12,7 +12,7 @@ #define RAPIDJSON_NO_SIZETYPEDEFINE namespace rapidjson { - typedef ::std::size_t SizeType; + using SizeType = size_t; } #include #include @@ -194,11 +194,13 @@ namespace kagome::telemetry { last_imported_.is_set = false; auto msg = blockNotification(last_imported_.block, last_imported_.origin); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) last_imported_msg = message_pool_->push(msg, refs); } // prepare last finalized message if there is a need to if (last_finalized_.reported < last_finalized_.block.number) { auto msg = blockNotification(last_finalized_.block, std::nullopt); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) last_finalized_msg = message_pool_->push(msg, refs); last_finalized_.reported = last_finalized_.block.number; } @@ -222,7 +224,9 @@ namespace kagome::telemetry { } std::optional system_msg_1, system_msg_2; auto refs = connections_.size(); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) system_msg_1 = message_pool_->push(systemIntervalMessage1(), refs); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) system_msg_2 = message_pool_->push(systemIntervalMessage2(), refs); for (auto &conn : connections_) { @@ -257,6 +261,7 @@ namespace kagome::telemetry { payload .AddMember( "authority", + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) static_cast(app_configuration_.roles().flags.authority), allocator) .AddMember("chain", str_val(chain_spec_.name()), allocator) @@ -344,6 +349,7 @@ namespace kagome::telemetry { "best", str_val(fmt::format("{:l}", info.hash)), allocator); if (origin.has_value()) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) height.SetInt(info.number); rapidjson::Value origin_val; using o = BlockOrigin; @@ -404,9 +410,13 @@ namespace kagome::telemetry { finalized_hash; { std::lock_guard lock(cache_mutex_); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) height.SetInt(last_imported_.block.number); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) finalized_height.SetInt(last_finalized_.block.number); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) tx_count.SetInt(tx_pool_->getStatus().ready_num); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) state_size.SetInt(buffer_storage_->byteSizeHint().value_or(0)); best_hash = str_val(fmt::format("{:l}", last_imported_.block.hash)); finalized_hash = str_val(fmt::format("{:l}", last_finalized_.block.hash)); @@ -447,8 +457,11 @@ namespace kagome::telemetry { // we are not actually measuring bandwidth. the following will just let us // see the history of active peers count change in the telemetry UI auto peers_to_bandwidth = active_peers * 1'000'000; + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) bandwidth_down.SetInt(peers_to_bandwidth); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) bandwidth_up.SetInt(peers_to_bandwidth); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) peers_count.SetInt(active_peers); // fields order is preserved the same way substrate orders it diff --git a/core/telemetry/service.hpp b/core/telemetry/service.hpp index 71e94eb02e..a27b8dac21 100644 --- a/core/telemetry/service.hpp +++ b/core/telemetry/service.hpp @@ -17,7 +17,7 @@ namespace kagome::telemetry { * * https://github.com/paritytech/substrate/blob/42b2d623d058197aebc3c737fb44fbbf278a85b4/primitives/consensus/common/src/lib.rs#L64 */ - enum class BlockOrigin { + enum class BlockOrigin : uint8_t { /// Genesis block built into the client. kGenesis, diff --git a/core/transaction_pool/impl/transaction_pool_impl.cpp b/core/transaction_pool/impl/transaction_pool_impl.cpp index 722948ca98..ee39cd463c 100644 --- a/core/transaction_pool/impl/transaction_pool_impl.cpp +++ b/core/transaction_pool/impl/transaction_pool_impl.cpp @@ -94,14 +94,15 @@ namespace kagome::transaction_pool { -> outcome::result { size_t length = extrinsic.data.size(); - return primitives::Transaction{extrinsic, - length, - extrinsic_hash, - v.priority, - res.first.number + v.longevity, - std::move(v.required_tags), - std::move(v.provided_tags), - v.propagate}; + return primitives::Transaction{ + .ext = extrinsic, + .bytes = length, + .hash = extrinsic_hash, + .priority = v.priority, + .valid_till = res.first.number + v.longevity, + .required_tags = std::move(v.required_tags), + .provided_tags = std::move(v.provided_tags), + .should_propagate = v.propagate}; }); } @@ -217,7 +218,7 @@ namespace kagome::transaction_pool { for (auto &requirement : state->tx->required_tags) { auto &pending_status = pool_state.dependency_graph_[requirement]; if (!pending_status.tag_provided - && pending_status.dependents.count(tx_hash) == 0) { + and not pending_status.dependents.contains(tx_hash)) { ++state->remains_required_txs_count; pending_status.dependents[tx_hash] = state; } @@ -383,7 +384,7 @@ namespace kagome::transaction_pool { void TransactionPoolImpl::setReady(PoolState &pool_state, const std::shared_ptr &tx) { if (auto [it, ok] = - pool_state.ready_txs_.emplace(tx->hash, ReadyStatus{tx, {}}); + pool_state.ready_txs_.emplace(tx->hash, ReadyStatus{.tx = tx}); ok) { if (auto key = ext_key_repo_->get(tx->hash); key.has_value()) { sub_engine_->notify(key.value(), diff --git a/core/utils/json_unquote.hpp b/core/utils/json_unquote.hpp index 9e59dd23cd..4d84856731 100644 --- a/core/utils/json_unquote.hpp +++ b/core/utils/json_unquote.hpp @@ -14,7 +14,7 @@ #define RAPIDJSON_NO_SIZETYPEDEFINE namespace rapidjson { - typedef ::std::size_t SizeType; + using SizeType = ::std::size_t; } // namespace rapidjson #include diff --git a/core/utils/kagome_db_editor.cpp b/core/utils/kagome_db_editor.cpp index 921b901cd7..eb3ad29561 100644 --- a/core/utils/kagome_db_editor.cpp +++ b/core/utils/kagome_db_editor.cpp @@ -35,12 +35,13 @@ #include "utils/profiler.hpp" namespace di = boost::di; -using namespace std::chrono_literals; -using namespace kagome; -using namespace storage::trie; +using namespace kagome; // NOLINT(google-build-using-namespace) +using namespace storage::trie; // NOLINT(google-build-using-namespace) using common::BufferOrView; using common::BufferView; +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic) + struct TrieTracker : TrieStorageBackend { TrieTracker(std::shared_ptr inner) : inner{std::move(inner)} {} @@ -76,7 +77,7 @@ struct TrieTracker : TrieStorageBackend { keys.emplace(common::Hash256::fromSpan(key).value()); } bool tracked(BufferView key) const { - return keys.count(common::Hash256::fromSpan(key).value()); + return keys.contains(common::Hash256::fromSpan(key).value()); } std::shared_ptr inner; @@ -105,7 +106,7 @@ inline auto check(T &&res) { } namespace { - std::string embedded_config(R"( + static const std::string embedded_config(R"( # ---------------- sinks: - name: console @@ -194,8 +195,9 @@ void child_storage_root_hashes(const std::unique_ptr &batch, } auto is_hash(const char *s) { - return std::strlen(s) == common::Hash256::size() * 2 + 2 - && std::equal(s, s + 2, "0x"); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + return s[0] == '0' and s[1] == 'x' + and std::strlen(s) == common::Hash256::size(); } int db_editor_main(int argc, const char **argv) { @@ -203,7 +205,12 @@ int db_editor_main(int argc, const char **argv) { backward::SignalHandling sh; #endif - Command cmd; + libp2p::common::FinalAction flush_std_streams_at_exit([] { + std::cout.flush(); + std::cerr.flush(); + }); + + Command cmd; // NOLINT(cppcoreguidelines-init-variables) if (argc == 2 or (argc == 3 && is_hash(argv[2])) or (argc == 4 and std::strcmp(argv[MODE], "compact") == 0)) { cmd = COMPACT; @@ -340,8 +347,8 @@ int db_editor_main(int argc, const char **argv) { last_finalized_block, last_finalized_block_state_root); - for (auto it = to_remove.rbegin(); it != to_remove.rend(); ++it) { - check(block_storage->removeBlock(it->hash)).value(); + for (auto &block : std::ranges::reverse_view(to_remove)) { + check(block_storage->removeBlock(block.hash)).value(); } SL_TRACE(log, "Save {} as single leaf", last_finalized_block); @@ -480,3 +487,5 @@ int db_editor_main(int argc, const char **argv) { return 0; } + +// NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic) diff --git a/core/utils/non_copyable.hpp b/core/utils/non_copyable.hpp index 9a6f488cc9..539e63f142 100644 --- a/core/utils/non_copyable.hpp +++ b/core/utils/non_copyable.hpp @@ -10,6 +10,8 @@ class NonCopyable { public: NonCopyable(const NonCopyable &) = delete; NonCopyable &operator=(const NonCopyable &) = delete; + NonCopyable(NonCopyable &&) = default; + NonCopyable &operator=(NonCopyable &&) = default; protected: NonCopyable() = default; @@ -18,7 +20,9 @@ class NonCopyable { class NonMovable { public: + NonMovable(const NonMovable &) = default; NonMovable(NonMovable &&) = delete; + NonMovable &operator=(const NonMovable &) = default; NonMovable &operator=(NonMovable &&) = delete; protected: diff --git a/core/utils/pool_handler.hpp b/core/utils/pool_handler.hpp index 68321c1ec9..7447390681 100644 --- a/core/utils/pool_handler.hpp +++ b/core/utils/pool_handler.hpp @@ -79,7 +79,7 @@ namespace kagome { } // namespace kagome #define REINVOKE(ctx, func, ...) \ - do { \ + ({ \ if (not runningInThisThread(ctx)) { \ return post(ctx, \ [weak{weak_from_this()}, \ @@ -93,13 +93,13 @@ namespace kagome { } \ }); \ } \ - } while (false) + }) /// Reinvokes function once depending on `template ` argument. /// If `true` reinvoke takes place, otherwise direct call. After reinvoke called /// function has `false` in kReinvoke. #define REINVOKE_ONCE(ctx, func, ...) \ - do { \ + ({ \ if constexpr (kReinvoke) { \ return post( \ ctx, \ @@ -114,4 +114,4 @@ namespace kagome { } \ }); \ } \ - } while (false) + }) diff --git a/core/utils/safe_object.hpp b/core/utils/safe_object.hpp index 84b73e4f7e..b1ba668c86 100644 --- a/core/utils/safe_object.hpp +++ b/core/utils/safe_object.hpp @@ -89,7 +89,7 @@ SafeObject(T &&) -> SafeObject; class WaitForSingleObject final { std::condition_variable wait_cv_; std::mutex wait_m_; - bool flag_; + bool flag_ = true; public: WaitForSingleObject(const WaitForSingleObject &) = delete; @@ -98,7 +98,8 @@ class WaitForSingleObject final { WaitForSingleObject(WaitForSingleObject &&) = delete; WaitForSingleObject &operator=(WaitForSingleObject &&) = delete; - WaitForSingleObject() : flag_{true} {} + WaitForSingleObject() = default; + ~WaitForSingleObject() = default; bool wait(std::chrono::microseconds wait_timeout) { std::unique_lock _lock(wait_m_); diff --git a/core/utils/spdlog_stderr.hpp b/core/utils/spdlog_stderr.hpp index 91e71eb3e0..7ee761872b 100644 --- a/core/utils/spdlog_stderr.hpp +++ b/core/utils/spdlog_stderr.hpp @@ -6,6 +6,8 @@ #pragma once +#include "runtime/wasm_compiler_definitions.hpp" // this header-file is generated + #if KAGOME_WASM_COMPILER_WASM_EDGE #include #include diff --git a/core/utils/storage_explorer.cpp b/core/utils/storage_explorer.cpp index 7121a742a3..c9941a7e02 100644 --- a/core/utils/storage_explorer.cpp +++ b/core/utils/storage_explorer.cpp @@ -153,7 +153,7 @@ std::optional parseBlockId(const char *string) { std::cerr << "Invalid block hash!\n"; return std::nullopt; } - id = std::move(id_hash); + id = id_hash; } else { try { id = std::stoi(string); @@ -170,12 +170,13 @@ class PrintHelpCommand final : public Command { explicit PrintHelpCommand(const CommandParser &parser) : Command{"help", "print help message"}, parser{parser} {} - virtual void execute(std::ostream &out, const ArgumentList &args) override { + void execute(std::ostream &out, const ArgumentList &args) override { assertArgumentCount(args, 1, 1); parser.printCommands(out); } private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) const CommandParser &parser; }; @@ -185,9 +186,9 @@ class InspectBlockCommand : public Command { : Command{"inspect-block", "# or hash - print info about the block with the given number " "or hash"}, - block_storage{block_storage} {} + block_storage{std::move(block_storage)} {} - virtual void execute(std::ostream &out, const ArgumentList &args) override { + void execute(std::ostream &out, const ArgumentList &args) override { assertArgumentCount(args, 2, 2); auto opt_id = parseBlockId(args[1]); if (!opt_id) { @@ -237,9 +238,9 @@ class RemoveBlockCommand : public Command { explicit RemoveBlockCommand(std::shared_ptr block_storage) : Command{"remove-block", "# or hash - remove the block from the block tree"}, - block_storage{block_storage} {} + block_storage{std::move(block_storage)} {} - virtual void execute(std::ostream &out, const ArgumentList &args) override { + void execute(std::ostream &out, const ArgumentList &args) override { assertArgumentCount(args, 2, 2); auto opt_id = parseBlockId(args[1]); if (!opt_id) { @@ -269,9 +270,9 @@ class QueryStateCommand : public Command { explicit QueryStateCommand(std::shared_ptr trie_storage) : Command{"query-state", "state_hash, key - query value at a given key and state"}, - trie_storage{trie_storage} {} + trie_storage{std::move(trie_storage)} {} - virtual void execute(std::ostream &out, const ArgumentList &args) override { + void execute(std::ostream &out, const ArgumentList &args) override { assertArgumentCount(args, 3, 3); kagome::storage::trie::RootHash state_root{}; @@ -328,9 +329,13 @@ class SearchChainCommand : public Command { BOOST_ASSERT(hasher != nullptr); } - enum class Target { Justification, AuthorityUpdate, LastBlock }; + enum class Target : uint8_t { + Justification, + AuthorityUpdate, + LastBlock, + }; - virtual void execute(std::ostream &out, const ArgumentList &args) override { + void execute(std::ostream &out, const ArgumentList &args) override { assertArgumentCount(args, 2, 4); Target target = parseTarget(args[1]); if (target == Target::LastBlock) { @@ -477,7 +482,6 @@ class SearchChainCommand : public Command { void reportAuthorityUpdate(std::ostream &out, BlockNumber digest_origin, const GrandpaDigest &digest) const { - using namespace kagome::primitives; if (auto *scheduled_change = std::get_if(&digest); scheduled_change) { out << "ScheduledChange at #" << digest_origin << " for "; @@ -519,11 +523,11 @@ class ChainInfoCommand final : public Command { public: ChainInfoCommand(std::shared_ptr block_tree) : Command{"chain-info", "Print general info about the current chain. "}, - block_tree{block_tree} { + block_tree{std::move(block_tree)} { BOOST_ASSERT(block_tree); } - virtual void execute(std::ostream &out, const ArgumentList &args) override { + void execute(std::ostream &out, const ArgumentList &args) override { if (args.size() > 1) { throwError("No arguments expected, {} arguments received", args.size()); } @@ -547,11 +551,11 @@ class ChainInfoCommand final : public Command { class DbStatsCommand : public Command { public: DbStatsCommand(std::filesystem::path db_path) - : Command("db-stats", "Print RocksDb stats"), db_path{db_path} {} + : Command("db-stats", "Print RocksDb stats"), + db_path{std::move(db_path)} {} - virtual void execute(std::ostream &out, const ArgumentList &args) override { + void execute(std::ostream &out, const ArgumentList &args) override { rocksdb::Options options; - rocksdb::DB *db; std::vector existing_families; auto res = rocksdb::DB::ListColumnFamilies( @@ -562,10 +566,13 @@ class DbStatsCommand : public Command { res.ToString()); } std::vector column_families; + column_families.reserve(existing_families.size()); for (auto &family : existing_families) { column_families.emplace_back(rocksdb::ColumnFamilyDescriptor{family, {}}); } std::vector column_handles; + + rocksdb::DB *db; // NOLINT(cppcoreguidelines-init-variables) auto status = rocksdb::DB::OpenForReadOnly( options, db_path, column_families, &column_handles, &db); if (!status.ok()) { @@ -586,21 +593,23 @@ class DbStatsCommand : public Command { 5); for (auto column_data : columns_data) { constexpr std::array sizes{"B ", "KB", "MB", "GB", "TB"}; - double size = column_data.size; + auto size = static_cast(column_data.size); int idx = 0; while (size > 1024.0) { size /= 1024.0; idx++; } - fmt::print(out, - "{:{}} | {:{}.2f} {} | {:{}} |\n", - column_data.name, - 30, - size, - 10, - sizes[idx], - column_data.file_count, - 5); + fmt::print( + out, + "{:{}} | {:{}.2f} {} | {:{}} |\n", + column_data.name, + 30, + size, + 10, + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) + sizes[idx], + column_data.file_count, + 5); } } @@ -621,20 +630,24 @@ int storage_explorer_main(int argc, const char **argv) { auto configuration = std::make_shared(); - int kagome_args_start = -1; + size_t kagome_args_start; // NOLINT(cppcoreguidelines-init-variables) + bool is_found = false; for (size_t i = 1; i < args.size(); i++) { if (strcmp(args[i], "--") == 0) { kagome_args_start = i; + is_found = true; } } - if (kagome_args_start == -1) { + if (not is_found) { std::cerr << "You must specify arguments for kagome initialization after '--'\n"; return -1; } if (!configuration->initializeFromArgs( - argc - kagome_args_start, args.subspan(kagome_args_start).data())) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) + argc - kagome_args_start, + args.subspan(kagome_args_start).data())) { std::cerr << "Failed to initialize kagome!\n"; return -1; } diff --git a/core/utils/watchdog.hpp b/core/utils/watchdog.hpp index 70cab93657..1be19cba44 100644 --- a/core/utils/watchdog.hpp +++ b/core/utils/watchdog.hpp @@ -43,6 +43,7 @@ inline uint64_t getPlatformThreadId() { #include inline uint64_t getPlatformThreadId() { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) return syscall(SYS_gettid); } @@ -118,11 +119,11 @@ namespace kagome { std::unique_lock lock{mutex_}; auto &thread = threads_[std::this_thread::get_id()]; if (not thread.count) { - thread = {Clock::now(), - 0, - std::make_shared(), - getPlatformThreadId(), - soralog::util::getThreadName()}; + thread = {.last_time = Clock::now(), + .last_count = 0, + .count = std::make_shared(), + .platform_id = getPlatformThreadId(), + .name = soralog::util::getThreadName()}; } return Ping{thread.count}; } diff --git a/housekeeping/clang-tidy-diff.sh b/housekeeping/clang-tidy-diff.sh index 13658f1653..abfd1c7cf8 100755 --- a/housekeeping/clang-tidy-diff.sh +++ b/housekeeping/clang-tidy-diff.sh @@ -14,6 +14,22 @@ if [ "${CI}" == "true" ]; then fi cd $(dirname $0)/.. +HUNTER_INCLUDE=$(cat $BUILD_DIR/_3rdParty/Hunter/install-root-dir)/include # exclude WAVM because on CI clang-tidy is run on a WasmEdge build -git diff -U0 origin/master -- . ':!core/runtime/wavm' | clang-tidy-diff.py -p1 -path ${BUILD_DIR} -iregex '(core|node)\/.*\.(h|c|hpp|cpp)' -clang-tidy-binary ${CLANG_TIDY_BIN} | tee clang-tidy.log +git diff -U0 origin/master -- . ':!core/runtime/wavm' | \ +clang-tidy-diff.py \ + -p1 \ + -path ${BUILD_DIR} \ + -iregex '(core|node)\/.*\.(h|c|hpp|cpp)' \ + -clang-tidy-binary ${CLANG_TIDY_BIN} \ + -- \ + --std=c++20 \ + -I core \ + -I $BUILD_DIR/core \ + -I $BUILD_DIR/pb/authority_discovery_proto/generated \ + -I $BUILD_DIR/pb/light_api_proto/generated \ + -I $BUILD_DIR/pb/node_api_proto/generated \ + -I $HUNTER_INCLUDE \ + -I $HUNTER_INCLUDE/binaryen \ +| tee clang-tidy.log ! grep ': error:' clang-tidy.log diff --git a/node/main.cpp b/node/main.cpp index 7d90275477..1e5c7efe9c 100644 --- a/node/main.cpp +++ b/node/main.cpp @@ -25,6 +25,8 @@ #include "log/logger.hpp" #include "parachain/pvf/kagome_pvf_worker.hpp" +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic) + using kagome::application::AppConfiguration; using kagome::application::AppConfigurationImpl; @@ -54,7 +56,7 @@ namespace { std::make_shared(*injector); if (configuration->subcommand().has_value()) { - switch (*configuration->subcommand()) { + switch (configuration->subcommand().value()) { using kagome::application::Subcommand; case Subcommand::ChainInfo: return app->chainInfo(); @@ -87,8 +89,7 @@ namespace { void wrong_usage() { std::cerr << "Wrong usage.\n" "Available subcommands: storage-explorer db-editor benchmark\n" - "Run with `--help' argument to print usage" - << std::endl; + "Run with `--help' argument to print usage\n"; } } // namespace @@ -102,6 +103,11 @@ int main(int argc, const char **argv, const char **env) { setvbuf(stdout, nullptr, _IOLBF, 0); setvbuf(stderr, nullptr, _IOLBF, 0); + libp2p::common::FinalAction flush_std_streams_at_exit([] { + std::cout.flush(); + std::cerr.flush(); + }); + if (argc > 1) { std::string_view name{argv[1]}; if (name == "pvf-worker") { @@ -120,7 +126,7 @@ int main(int argc, const char **argv, const char **env) { auto r = logging_system->configure(); if (not r.message.empty()) { - (r.has_error ? std::cerr : std::cout) << r.message << std::endl; + (r.has_error ? std::cerr : std::cout) << r.message << '\n'; } if (r.has_error) { return EXIT_FAILURE; @@ -172,3 +178,5 @@ int main(int argc, const char **argv, const char **env) { return exit_code; } + +// NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic) diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 8ee8aa272e..d4887bcd79 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -7,6 +7,7 @@ include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/node + ) add_subdirectory(core) diff --git a/test/core/api/client/ws_client.cpp b/test/core/api/client/ws_client.cpp index fe144b05eb..84ffc7f05b 100644 --- a/test/core/api/client/ws_client.cpp +++ b/test/core/api/client/ws_client.cpp @@ -55,9 +55,8 @@ namespace test { boost::system::error_code ec{}; auto x = buffer.prepare(message.size()); - std::copy(message.begin(), - message.end(), - reinterpret_cast(x.data())); // NOLINT + std::ranges::copy(message, + reinterpret_cast(x.data())); // NOLINT buffer.commit(message.size()); stream_.write(buffer.data(), ec); diff --git a/test/core/api/service/state/state_jrpc_processor_test.cpp b/test/core/api/service/state/state_jrpc_processor_test.cpp index 9cdb0ef6fa..ca5b9c9b79 100644 --- a/test/core/api/service/state/state_jrpc_processor_test.cpp +++ b/test/core/api/service/state/state_jrpc_processor_test.cpp @@ -227,10 +227,9 @@ TEST_F(StateJrpcProcessorTest, ProcessQueryStorage) { registerHandlers(); jsonrpc::Value::Array keys_json; - std::transform(keys.begin(), - keys.end(), - std::back_inserter(keys_json), - [](auto &buffer) { return "0x" + buffer.toHex(); }); + std::ranges::transform(keys, std::back_inserter(keys_json), [](auto &buffer) { + return "0x" + buffer.toHex(); + }); jsonrpc::Request::Parameters params{keys_json, "0x" + from.toHex()}; // WHEN auto result = execute(CallType::kCallType_QueryStorage, params); @@ -270,10 +269,9 @@ TEST_F(StateJrpcProcessorTest, ProcessQueryStorageAt) { registerHandlers(); jsonrpc::Value::Array keys_json; - std::transform(keys.begin(), - keys.end(), - std::back_inserter(keys_json), - [](auto &buffer) { return "0x" + buffer.toHex(); }); + std::ranges::transform(keys, std::back_inserter(keys_json), [](auto &buffer) { + return "0x" + buffer.toHex(); + }); jsonrpc::Request::Parameters params{keys_json, "0x" + at.toHex()}; // WHEN auto result = execute(CallType::kCallType_QueryStorageAt, params); diff --git a/test/core/blockchain/block_tree_test.cpp b/test/core/blockchain/block_tree_test.cpp index b5371bd2bd..e58cc1c30c 100644 --- a/test/core/blockchain/block_tree_test.cpp +++ b/test/core/blockchain/block_tree_test.cpp @@ -361,9 +361,10 @@ struct BlockTreeTest : public testing::Test { num_to_hash_.emplace(b.number, b.hash); } void delNumToHash(BlockHash hash) { - auto it = std::find_if(num_to_hash_.begin(), - num_to_hash_.end(), - [&](const auto &it) { return it.second == hash; }); + auto it = std::ranges::find_if( + num_to_hash_.begin(), num_to_hash_.end(), [&](const auto &it) { + return it.second == hash; + }); if (it == num_to_hash_.end()) { return; } diff --git a/test/core/common/blob_test.cpp b/test/core/common/blob_test.cpp index e60f7f0086..649d9b5a76 100644 --- a/test/core/common/blob_test.cpp +++ b/test/core/common/blob_test.cpp @@ -122,7 +122,7 @@ TEST(BlobTest, ToStringTest) { std::array expected{'a', 's', 'd', 'f', 'g'}; Blob<5> blob; - std::copy(expected.begin(), expected.end(), blob.begin()); + std::ranges::copy(expected, blob.begin()); ASSERT_EQ(blob.toString(), std::string(expected.begin(), expected.end())); } diff --git a/test/core/consensus/grandpa/literals.hpp b/test/core/consensus/grandpa/literals.hpp index c12b4be9f9..bc9870e15f 100644 --- a/test/core/consensus/grandpa/literals.hpp +++ b/test/core/consensus/grandpa/literals.hpp @@ -18,21 +18,21 @@ inline kagome::consensus::grandpa::VoteWeight makeVoteWeight(uint64_t w) { inline kagome::consensus::grandpa::BlockHash makeBlockHash(std::string s) { assert(s.size() <= kagome::consensus::grandpa::BlockHash::size()); kagome::consensus::grandpa::BlockHash hash{}; - std::copy(s.begin(), s.end(), hash.begin()); + std::ranges::copy(s, hash.begin()); return hash; } inline kagome::consensus::grandpa::Id makeId(std::string s) { assert(s.size() <= kagome::consensus::grandpa::Id::size()); kagome::consensus::grandpa::Id id{}; - std::copy(s.begin(), s.end(), id.begin()); + std::ranges::copy(s, id.begin()); return id; } inline kagome::crypto::Ed25519Signature makeSig(std::string s) { assert(s.size() <= kagome::crypto::Ed25519Signature::size()); kagome::crypto::Ed25519Signature sig{}; - std::copy(s.begin(), s.end(), sig.begin()); + std::ranges::copy(s, sig.begin()); return sig; } diff --git a/test/core/consensus/grandpa/vote_tracker_test.cpp b/test/core/consensus/grandpa/vote_tracker_test.cpp index c01f4f6e4b..878d9f228b 100644 --- a/test/core/consensus/grandpa/vote_tracker_test.cpp +++ b/test/core/consensus/grandpa/vote_tracker_test.cpp @@ -109,7 +109,7 @@ TEST_F(VoteTrackerTest, GetMessages) { for (auto &m : expected) { ASSERT_TRUE( - std::find_if( + std::ranges::find_if( messages.begin(), messages.end(), [&m](auto &v) { diff --git a/test/core/crypto/blake2/blake2_test.cpp b/test/core/crypto/blake2/blake2_test.cpp index 9ec6de015d..39d71bf0ed 100644 --- a/test/core/crypto/blake2/blake2_test.cpp +++ b/test/core/crypto/blake2/blake2_test.cpp @@ -51,7 +51,7 @@ TEST(Blake2b, Correctness) { inlen = b2b_in_len[j]; selftest_seq(in, inlen, inlen); // unkeyed hash - kagome::crypto::blake2b(md, outlen, NULL, 0, in, inlen); + kagome::crypto::blake2b(md, outlen, nullptr, 0, in, inlen); blake2b_update(&ctx, md, outlen); // hash the hash selftest_seq(key, outlen, outlen); // keyed hash diff --git a/test/core/network/rpc_libp2p_test.cpp b/test/core/network/rpc_libp2p_test.cpp index ebe24f4d14..09d4f5fe8d 100644 --- a/test/core/network/rpc_libp2p_test.cpp +++ b/test/core/network/rpc_libp2p_test.cpp @@ -34,15 +34,15 @@ using ScaleRPC = RPC; namespace kagome::network { /// outputs object of type BlockResponse to stream - template > + template + requires Stream::is_encoder_stream Stream &operator<<(Stream &s, const BlocksResponse &v) { return s << v.blocks; } /// decodes object of type BlockResponse from stream - template > + template + requires Stream::is_decoder_stream Stream &operator>>(Stream &s, BlocksResponse &v) { return s >> v.blocks; } diff --git a/test/core/runtime/executor_test.cpp b/test/core/runtime/executor_test.cpp index 4e74f3fd6e..06cdacae17 100644 --- a/test/core/runtime/executor_test.cpp +++ b/test/core/runtime/executor_test.cpp @@ -133,9 +133,8 @@ class ExecutorTest : public testing::Test { .WillRepeatedly(testing::Return(module_instance)); if (type == CallType::Persistent) { return ctx_factory_->persistentAt(blockchain_state.hash); - } else { - return ctx_factory_->ephemeralAt(blockchain_state.hash, storage_state); } + return ctx_factory_->ephemeralAt(blockchain_state.hash, storage_state); } protected: diff --git a/test/external-project-test/src/main.cpp b/test/external-project-test/src/main.cpp index 4946f7c0dd..c785d9af89 100644 --- a/test/external-project-test/src/main.cpp +++ b/test/external-project-test/src/main.cpp @@ -39,16 +39,22 @@ #include #include #include +#include #include #include int main() { + libp2p::common::FinalAction flush_std_streams_at_exit([] { + std::cout.flush(); + std::cerr.flush(); + }); + auto logging_system = std::make_shared( std::make_shared( std::make_shared())); auto res = logging_system->configure(); if (not res.message.empty()) { - (res.has_error ? std::cerr : std::cout) << res.message << std::endl; + (res.has_error ? std::cerr : std::cout) << res.message << '\n'; } if (res.has_error) { exit(EXIT_FAILURE); diff --git a/test/mock/core/host_api/host_api_mock.hpp b/test/mock/core/host_api/host_api_mock.hpp index 55cd4fa48d..0a7bf4b8b2 100644 --- a/test/mock/core/host_api/host_api_mock.hpp +++ b/test/mock/core/host_api/host_api_mock.hpp @@ -249,7 +249,7 @@ namespace kagome::host_api { MOCK_METHOD(void, ext_crypto_start_batch_verify_version_1, (), (override)); - MOCK_METHOD(int32_t, + MOCK_METHOD(runtime::WasmSize, ext_crypto_finish_batch_verify_version_1, (), (override)); diff --git a/test/mock/core/offchain/offchain_persistent_storage_mock.hpp b/test/mock/core/offchain/offchain_persistent_storage_mock.hpp index 570c88f16f..287bce5206 100644 --- a/test/mock/core/offchain/offchain_persistent_storage_mock.hpp +++ b/test/mock/core/offchain/offchain_persistent_storage_mock.hpp @@ -17,7 +17,12 @@ namespace kagome::offchain { MOCK_METHOD(outcome::result, set, (const common::BufferView &, common::Buffer), - (override)); + ()); + + outcome::result set(const common::BufferView &key, + common::BufferOrView value) override { + return this->set(key, value.intoBuffer()); + } MOCK_METHOD(outcome::result, clear, diff --git a/test/testutil/libp2p/message_read_writer_helper.cpp b/test/testutil/libp2p/message_read_writer_helper.cpp index 3391d43dc7..f753325c27 100644 --- a/test/testutil/libp2p/message_read_writer_helper.cpp +++ b/test/testutil/libp2p/message_read_writer_helper.cpp @@ -10,7 +10,7 @@ #include "libp2p/multi/uvarint.hpp" ACTION_P(PutBytes, bytes) { // NOLINT - std::copy(bytes.begin(), bytes.end(), arg0.begin()); + std::ranges::copy(bytes, arg0.begin()); arg2(bytes.size()); }