From 95b67357bb10f52a180d2abcf4870c17feacc611 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20M=C3=BCller?= Date: Wed, 24 Jun 2026 12:45:34 -0700 Subject: [PATCH] Revert "Update to Go 1.26" --- .github/workflows/ci.yml | 2 +- .github/workflows/flaky-test-monitor.yml | 2 +- .github/workflows/image_builds.yml | 2 +- .github/workflows/tools.yml | 2 +- README.md | 4 +- admin/command_runner.go | 5 +- admin/commands/collection/tx_rate_limiter.go | 4 +- admin/commands/common/get_config.go | 2 +- admin/commands/common/get_identity.go | 4 +- admin/commands/common/list_configs.go | 2 +- .../common/read_protocol_state_blocks.go | 6 +- .../common/read_protocol_state_blocks_test.go | 32 +- admin/commands/common/set_config.go | 2 +- admin/commands/common/set_golog_level.go | 2 +- admin/commands/common/set_log_level.go | 2 +- .../commands/execution/checkpoint_trigger.go | 2 +- admin/commands/execution/stop_at_height.go | 4 +- .../commands/execution/stop_at_height_test.go | 10 +- .../state_synchronization/execute_script.go | 4 +- .../read_execution_data.go | 4 +- .../storage/backfill_tx_error_messages.go | 6 +- .../backfill_tx_error_messages_test.go | 32 +- admin/commands/storage/helper.go | 14 +- admin/commands/storage/pebble_checkpoint.go | 2 +- admin/commands/storage/read_blocks.go | 4 +- admin/commands/storage/read_blocks_test.go | 32 +- .../storage/read_protocol_snapshot.go | 4 +- admin/commands/storage/read_range_blocks.go | 2 +- .../storage/read_range_cluster_blocks.go | 2 +- admin/commands/storage/read_results.go | 6 +- admin/commands/storage/read_results_test.go | 26 +- admin/commands/storage/read_seals.go | 6 +- admin/commands/storage/read_seals_test.go | 6 +- admin/commands/storage/read_transactions.go | 2 +- .../storage/read_transactions_test.go | 8 +- admin/commands/uploader/toggle_uploader.go | 2 +- cmd/Dockerfile | 4 +- .../node_builder/access_node_builder.go | 4 +- cmd/bootstrap/cmd/keygen.go | 2 +- cmd/bootstrap/cmd/util.go | 2 +- cmd/bootstrap/utils/key_generation.go | 6 +- cmd/bootstrap/utils/key_generation_test.go | 4 +- cmd/execution_config.go | 4 +- cmd/ledger/main.go | 4 +- cmd/scaffold_test.go | 2 +- cmd/testUtil.go | 2 +- cmd/util/cmd/atree_inlined_status/cmd.go | 5 +- .../evm_account_storage_health_test.go | 2 +- cmd/util/cmd/common/clusters.go | 2 +- cmd/util/cmd/common/print.go | 2 +- cmd/util/cmd/common/utils.go | 4 +- cmd/util/cmd/epochs/cmd/recover_test.go | 2 +- cmd/util/cmd/epochs/cmd/reset_test.go | 8 +- .../execution_state_extract_test.go | 14 +- .../extract_payloads_test.go | 6 +- .../cmd/generate-authorization-fixes/cmd.go | 2 +- .../generate-authorization-fixes/cmd_test.go | 6 +- cmd/util/cmd/read-badger/cmd/stats.go | 5 +- .../migrations/account_based_migration.go | 2 +- .../migrations/cadence_value_diff_test.go | 2 +- .../migrations/deploy_migration_test.go | 8 +- ...ilter_unreferenced_slabs_migration_test.go | 2 +- cmd/util/ledger/reporters/account_reporter.go | 8 +- .../reporters/fungible_token_tracker_test.go | 8 +- .../ledger/reporters/reporter_output_test.go | 24 +- cmd/util/ledger/util/payload_file_test.go | 10 +- cmd/util/ledger/util/payload_grouping.go | 5 +- cmd/util/ledger/util/payload_grouping_test.go | 16 +- config/config_test.go | 12 +- consensus/follower_test.go | 4 +- .../committees/consensus_committee_test.go | 4 +- .../committees/leader/leader_selection.go | 2 +- .../leader/leader_selection_test.go | 28 +- .../cruisectl/block_time_controller.go | 22 +- .../cruisectl/block_time_controller_test.go | 2 +- .../hotstuff/cruisectl/proposal_timing.go | 14 + .../eventhandler/event_handler_test.go | 8 +- .../hotstuff/integration/connect_test.go | 1 + .../hotstuff/integration/instance_test.go | 4 +- .../hotstuff/integration/integration_test.go | 4 +- .../hotstuff/integration/liveness_test.go | 10 +- .../hotstuff/pacemaker/pacemaker_test.go | 6 +- consensus/hotstuff/signature/packer_test.go | 2 +- .../weighted_signature_aggregator_test.go | 4 +- .../timeoutaggregator/timeout_aggregator.go | 2 +- .../timeout_aggregator_test.go | 2 +- .../timeout_collectors_test.go | 12 +- .../timeoutcollector/aggregation_test.go | 2 +- .../timeout_collector_test.go | 10 +- consensus/hotstuff/tracker/tracker_test.go | 12 +- consensus/hotstuff/verification/common.go | 2 +- .../voteaggregator/vote_aggregator.go | 2 +- .../voteaggregator/vote_collectors_test.go | 12 +- .../combined_vote_processor_v2_test.go | 8 +- .../combined_vote_processor_v3_test.go | 8 +- .../staking_vote_processor_test.go | 8 +- .../votecollector/statemachine_test.go | 6 +- .../hotstuff/votecollector/vote_cache_test.go | 2 +- consensus/integration/blockordelay_test.go | 8 +- consensus/integration/integration_test.go | 6 +- consensus/integration/network_test.go | 18 +- consensus/integration/slow_test.go | 4 +- crypto/go.mod | 2 +- engine/access/access_test.go | 2 +- engine/access/index/event_index_test.go | 2 +- engine/access/ingestion/engine.go | 4 +- engine/access/ingestion/engine_test.go | 2 +- .../tx_error_messages_core_test.go | 2 +- .../tx_error_messages_engine_test.go | 2 +- engine/access/ingestion2/engine.go | 2 +- engine/access/ingestion2/engine_test.go | 4 +- .../integration_unsecure_grpc_server_test.go | 2 +- engine/access/ping/engine.go | 1 + .../rest/common/models/model_block_events.go | 2 +- .../rest/common/parser/transaction_test.go | 14 +- .../experimental/get_account_transactions.go | 6 +- engine/access/rest/experimental/handler.go | 2 +- .../routes/account_ft_transfers.go | 2 +- .../routes/account_nft_transfers.go | 2 +- .../routes/account_transactions.go | 2 +- .../rest/experimental/routes/contracts.go | 8 +- .../routes/scheduled_transactions.go | 6 +- engine/access/rest/http/routes/blocks_test.go | 2 +- .../rest/http/routes/collections_test.go | 6 +- engine/access/rest/http/routes/events_test.go | 2 +- .../access/rest/http/routes/scripts_test.go | 6 +- .../rest/http/routes/transactions_test.go | 2 +- engine/access/rest/websockets/connection.go | 8 +- engine/access/rest/websockets/controller.go | 6 +- .../access/rest/websockets/controller_test.go | 50 +-- .../account_statuses_provider.go | 2 +- .../account_statuses_provider_test.go | 34 +- .../data_providers/args_validation.go | 2 +- .../data_providers/base_provider.go | 4 +- .../data_providers/block_digests_provider.go | 2 +- .../block_digests_provider_test.go | 8 +- .../data_providers/block_headers_provider.go | 2 +- .../block_headers_provider_test.go | 8 +- .../data_providers/blocks_provider.go | 2 +- .../data_providers/blocks_provider_test.go | 14 +- .../data_providers/events_provider.go | 2 +- .../data_providers/events_provider_test.go | 34 +- .../rest/websockets/data_providers/factory.go | 4 +- .../websockets/data_providers/factory_test.go | 4 +- .../mock/data_provider_factory.go | 18 +- .../models/base_data_provider.go | 6 +- ...d_and_get_transaction_statuses_provider.go | 2 +- ..._get_transaction_statuses_provider_test.go | 32 +- .../transaction_statuses_provider.go | 2 +- .../transaction_statuses_provider_test.go | 34 +- .../websockets/data_providers/unit_test.go | 20 +- .../legacy/routes/subscribe_events_test.go | 16 +- .../websockets/mock/websocket_connection.go | 28 +- engine/access/rest_api_test.go | 6 +- .../backend_stream_block_digests_test.go | 8 +- .../backend_stream_block_headers_test.go | 8 +- .../rpc/backend/backend_stream_blocks.go | 6 +- .../rpc/backend/backend_stream_blocks_test.go | 16 +- .../access/rpc/backend/events/events_test.go | 9 +- .../rpc/backend/script_executor_test.go | 2 +- .../error_messages/provider_test.go | 4 +- .../transactions/stream/stream_backend.go | 4 +- engine/access/rpc/connection/cache_test.go | 6 +- .../access/rpc/connection/connection_test.go | 16 +- .../grpc_compression_benchmark_test.go | 2 +- engine/access/rpc/connection/manager.go | 18 +- .../backend/backend_account_statuses.go | 2 +- .../backend/backend_account_statuses_test.go | 14 +- .../state_stream/backend/backend_events.go | 2 +- .../backend/backend_events_test.go | 4 +- .../backend/backend_executiondata.go | 2 +- .../backend/backend_executiondata_test.go | 8 +- .../state_stream/backend/handler_test.go | 12 +- engine/access/subscription/streamer_test.go | 6 +- .../access/subscription/subscription_test.go | 10 +- engine/broadcaster_test.go | 12 +- engine/collection/compliance/core_test.go | 2 +- engine/collection/compliance/engine_test.go | 14 +- engine/collection/ingest/engine.go | 2 +- engine/collection/ingest/rate_limiter.go | 2 +- engine/collection/ingest/rate_limiter_test.go | 4 +- engine/collection/message_hub/message_hub.go | 4 +- engine/collection/synchronization/engine.go | 10 +- .../collection/synchronization/engine_test.go | 4 +- .../synchronization/request_handler.go | 12 +- engine/common/follower/cache/cache_test.go | 6 +- .../common/follower/compliance_core_test.go | 6 +- engine/common/follower/compliance_engine.go | 4 +- engine/common/follower/integration_test.go | 4 +- engine/common/grpc/forwarder/forwarder.go | 2 +- engine/common/requester/engine.go | 14 +- engine/common/requester/engine_test.go | 2 +- engine/common/rpc/convert/events_test.go | 4 +- .../common/rpc/convert/execution_data_test.go | 1 + .../rpc/execution_node_identities_provider.go | 2 +- ...execution_node_identities_provider_test.go | 2 +- engine/common/synchronization/engine.go | 6 +- .../synchronization/engine_spam_test.go | 10 +- engine/common/synchronization/engine_test.go | 4 +- .../common/synchronization/request_handler.go | 2 +- .../synchronization/request_handler_engine.go | 8 +- .../synchronization/request_heap_test.go | 6 +- engine/common/version/version_control_test.go | 6 +- engine/common/worker/worker_builder_test.go | 6 +- .../approvals/aggregated_signatures_test.go | 4 +- .../consensus/approvals/approval_collector.go | 2 +- .../approvals/approvals_lru_cache_test.go | 6 +- .../assignment_collector_tree_test.go | 8 +- .../caching_assignment_collector_test.go | 4 +- .../approvals/request_tracker_test.go | 16 +- .../consensus/approvals/testutil/testutil.go | 2 +- engine/consensus/approvals/tracker/record.go | 5 +- .../verifying_assignment_collector_test.go | 2 +- engine/consensus/compliance/core_test.go | 2 +- engine/consensus/compliance/engine_test.go | 14 +- engine/consensus/ingestion/engine.go | 10 +- engine/consensus/ingestion/engine_test.go | 6 +- engine/consensus/matching/core_test.go | 2 +- engine/consensus/matching/engine.go | 2 +- engine/consensus/matching/engine_test.go | 6 +- engine/consensus/message_hub/message_hub.go | 4 +- engine/consensus/sealing/core.go | 17 +- engine/consensus/sealing/core_test.go | 10 +- engine/consensus/sealing/engine.go | 6 +- engine/consensus/sealing/engine_test.go | 14 +- engine/enqueue_test.go | 10 +- engine/execution/block_result.go | 5 +- engine/execution/block_result_test.go | 4 +- .../computation/committer/committer.go | 6 +- .../computation/computer/computer_test.go | 26 +- .../execution_verification_test.go | 14 +- .../computation/manager_benchmark_test.go | 6 +- engine/execution/computation/manager_test.go | 14 +- .../computation/metrics/collector_test.go | 8 +- engine/execution/ingestion/core.go | 2 +- engine/execution/ingestion/throttle.go | 5 +- .../execution/ingestion/uploader/manager.go | 1 + engine/execution/ingestion/uploader/model.go | 4 +- .../execution/ingestion/uploader/uploader.go | 2 +- engine/execution/provider/engine.go | 6 +- engine/execution/rpc/engine_test.go | 4 +- engine/execution/state/unittest/fixtures.go | 2 +- .../background_indexer_factory_test.go | 12 +- .../storehouse/checkpoint_validator.go | 2 +- .../in_memory_register_store_test.go | 6 +- .../storehouse/register_store_test.go | 6 +- engine/execution/testutil/fixtures.go | 37 +- .../fixtures_checker_heavy_contract.go | 6 +- engine/execution/testutil/fixtures_counter.go | 12 +- engine/execution/testutil/fixtures_event.go | 4 +- engine/execution/testutil/fixtures_token.go | 4 +- engine/ghost/client/ghost_client.go | 4 +- engine/protocol/api_test.go | 2 +- .../assigner/blockconsumer/consumer_test.go | 4 +- .../fetcher/chunkconsumer/consumer_test.go | 8 +- engine/verification/fetcher/engine_test.go | 4 +- engine/verification/utils/unittest/fixture.go | 2 +- engine/verification/verifier/engine.go | 10 +- engine/verification/verifier/verifiers.go | 6 +- fvm/accounts_test.go | 76 ++-- fvm/crypto/hash_test.go | 5 +- fvm/environment/accounts.go | 2 +- fvm/environment/contract_updater.go | 9 +- fvm/environment/evm_block_hash_list.go | 4 +- fvm/environment/evm_block_hash_list_test.go | 6 +- .../evm_block_store_benchmark_test.go | 2 +- fvm/environment/program_recovery.go | 8 +- fvm/environment/programs_test.go | 12 +- fvm/environment/random_generator_test.go | 8 +- fvm/environment/uuids_test.go | 16 +- fvm/evm/emulator/state/base_test.go | 6 +- fvm/evm/emulator/state/delta_test.go | 2 +- fvm/evm/emulator/state/importer.go | 19 +- fvm/evm/emulator/state/stateDB.go | 5 +- fvm/evm/emulator/state/state_growth_test.go | 6 +- .../emulator/state/updateCommitter_test.go | 4 +- fvm/evm/evm_test.go | 392 +++++++++--------- fvm/evm/handler/handler_benchmark_test.go | 4 +- fvm/evm/offchain/sync/replayer_test.go | 4 +- fvm/evm/offchain/utils/verify.go | 5 +- fvm/evm/testutils/backend.go | 17 +- fvm/evm/testutils/contract.go | 4 +- fvm/evm/types/result_test.go | 2 +- fvm/executionParameters.go | 5 +- fvm/executionParameters_test.go | 5 +- fvm/fvm_bench_test.go | 29 +- fvm/fvm_blockcontext_test.go | 22 +- fvm/fvm_signature_test.go | 31 +- fvm/fvm_test.go | 111 ++--- fvm/inspection/token_changes.go | 9 +- fvm/storage/derived/table.go | 5 +- fvm/storage/derived/table_test.go | 2 +- fvm/storage/snapshot/snapshot_tree.go | 6 +- fvm/storage/snapshot/snapshot_tree_test.go | 2 +- fvm/storage/state/spock_state_test.go | 6 +- fvm/storage/state/storage_state.go | 5 +- fvm/storage/state/transaction_state_test.go | 6 +- fvm/systemcontracts/system_contracts_test.go | 2 +- fvm/transactionVerifier.go | 7 +- go.mod | 6 +- go.sum | 8 +- insecure/go.mod | 6 +- insecure/go.sum | 8 +- integration/benchmark/cmd/manual/Dockerfile | 2 +- integration/go.mod | 6 +- integration/go.sum | 8 +- integration/localnet/client/Dockerfile | 2 +- ledger/common/hash/hash_test.go | 7 +- ledger/complete/compactor.go | 5 +- ledger/complete/compactor_test.go | 18 +- ledger/complete/ledger_benchmark_test.go | 2 +- ledger/complete/ledger_test.go | 8 +- ledger/complete/mtrie/forest_test.go | 2 +- ledger/complete/mtrie/trie/trie_test.go | 36 +- ledger/complete/mtrie/trieCache_test.go | 4 +- ledger/complete/wal/checkpoint_v6_reader.go | 10 +- ledger/complete/wal/checkpoint_v6_test.go | 14 +- ledger/complete/wal/checkpoint_v6_writer.go | 2 +- ledger/complete/wal/checkpointer.go | 8 +- .../wal/checkpointer_serialization_test.go | 2 +- ledger/complete/wal/checkpointer_test.go | 4 +- ledger/complete/wal/triequeue_test.go | 8 +- ledger/complete/wal/wal_test.go | 2 +- ledger/errors.go | 9 +- ledger/partial/ptrie/errors.go | 13 +- ledger/remote/client.go | 2 +- ledger/trie.go | 31 +- model/convert/service_event_test.go | 14 +- model/flow/address.go | 2 +- model/flow/identifier.go | 2 +- model/flow/identity_test.go | 4 +- model/flow/ledger_test.go | 2 +- model/flow/transaction_test.go | 44 +- module/block_iterator/creator_test.go | 4 +- .../block_iterator/executor/executor_test.go | 4 +- module/buffer/backend_test.go | 2 +- module/builder/collection/builder_test.go | 26 +- module/builder/consensus/builder.go | 10 +- module/builder/consensus/builder_test.go | 10 +- module/chainsync/core.go | 11 +- module/chainsync/core_test.go | 12 +- module/chunks/chunkVerifier_test.go | 1 + module/chunks/chunk_assigner_test.go | 4 +- module/component/component_manager_test.go | 28 +- module/component/run_component_test.go | 11 +- module/dkg/broker_test.go | 4 +- module/dkg/controller_test.go | 6 +- module/epochs/errors.go | 2 +- module/epochs/machine_account_test.go | 2 +- module/execution/scripts_test.go | 10 +- .../executiondatasync/execution_data/store.go | 5 +- .../execution_data/store_test.go | 10 +- .../execution_result_query_provider_test.go | 8 +- module/executiondatasync/tracker/storage.go | 5 +- module/finalizer/consensus/finalizer_test.go | 4 +- module/forest/concurrency_helpers_test.go | 2 +- module/forest/vertex.go | 2 +- module/id/filtered_provider_test.go | 6 +- module/id/fixed_provider_test.go | 19 +- module/jobqueue/consumer_behavior_test.go | 10 +- module/jobqueue/sealed_header_reader_test.go | 2 +- module/jobqueue/workerpool.go | 2 +- module/lifecycle/lifecycle_test.go | 4 +- module/limiters/concurrency_limiter_test.go | 16 +- module/mempool/chunk_requests.go | 6 +- .../consensus/exec_fork_suppressor_test.go | 2 +- .../consensus/receipt_equivalence_class.go | 2 +- module/mempool/epochs/transactions_test.go | 12 +- module/mempool/herocache/backdata/cache.go | 4 +- .../mempool/herocache/backdata/cache_test.go | 6 +- .../herocache/backdata/heropool/pool_test.go | 14 +- module/mempool/herocache/dns_cache_test.go | 4 +- .../mempool/herocache/execution_data_test.go | 8 +- module/mempool/herocache/transactions_test.go | 8 +- module/mempool/queue/heroQueue_test.go | 7 +- module/mempool/queue/heroStore_test.go | 11 +- .../stdmap/backDataHeapBenchmark_test.go | 4 +- module/mempool/stdmap/backdata/mapBackData.go | 6 +- module/mempool/stdmap/backend_test.go | 4 +- module/mempool/stdmap/chunk_requests_test.go | 2 +- module/mempool/stdmap/eject_test.go | 8 +- module/mempool/stdmap/identifier_map_test.go | 2 +- .../stdmap/incorporated_result_seals_test.go | 2 +- .../mempool/stdmap/pending_receipts_test.go | 24 +- module/metrics/example/collection/main.go | 2 +- module/metrics/example/consensus/main.go | 2 +- module/metrics/example/execution/main.go | 2 +- module/metrics/example/verification/main.go | 2 +- .../queue/concurrent_priority_queue_test.go | 30 +- module/queue/priority_queue_test.go | 2 +- module/signature/checksum_test.go | 2 +- module/signature/signer_indices_test.go | 2 +- .../indexer/extended/contracts_test.go | 9 +- .../scheduled_transaction_requester.go | 2 +- module/state_synchronization/indexer/util.go | 7 +- .../execution_data_requester_test.go | 2 +- module/util/log.go | 21 +- module/util/util_test.go | 16 +- network/alsp/internal/cache_test.go | 11 +- network/alsp/manager/manager_test.go | 32 +- network/cache/rcvcache_test.go | 8 +- network/internal/p2pfixtures/fixtures.go | 2 +- network/internal/testutils/fixtures.go | 2 +- network/internal/testutils/meshengine.go | 12 +- network/internal/testutils/testUtil.go | 4 +- network/internal/testutils/wrapper.go | 8 +- .../p2p/cache/gossipsub_spam_records_test.go | 4 +- .../p2p/cache/protocol_state_provider_test.go | 2 +- network/p2p/config/gossipsub.go | 2 +- .../p2p/connection/connection_gater_test.go | 8 +- network/p2p/connection/peerManager_test.go | 2 +- network/p2p/dht/dht_test.go | 4 +- network/p2p/dns/resolver.go | 4 +- network/p2p/dns/resolver_test.go | 12 +- .../inspector/internal/cache/cache_test.go | 4 +- .../control_message_validation_inspector.go | 20 +- ...ntrol_message_validation_inspector_test.go | 9 +- network/p2p/logging/logging_test.go | 4 +- .../node/internal/protocolPeerCache_test.go | 4 +- network/p2p/node/libp2pNode_test.go | 6 +- network/p2p/node/libp2pStream_test.go | 13 +- network/p2p/node/resourceManager_test.go | 10 +- .../internal/appSpecificScoreCache_test.go | 2 +- .../internal/subscriptionCache_test.go | 13 +- network/p2p/scoring/registry_test.go | 20 +- network/p2p/scoring/scoring_test.go | 6 +- network/p2p/test/fixtures.go | 41 +- network/p2p/test/sporking_test.go | 9 +- .../duplicate_msgs_counter_cache_test.go | 2 +- .../tracer/internal/rpc_sent_cache_test.go | 2 +- .../tracer/internal/rpc_sent_tracker_test.go | 6 +- .../translator/unstaked_translator_test.go | 4 +- .../unicast/cache/unicastConfigCache_test.go | 6 +- network/p2p/unicast/manager_test.go | 39 +- .../internal/compressedStream_test.go | 24 +- .../internal/rate_limiter_map_test.go | 3 +- network/proxy/network_test.go | 6 +- network/queue/messageQueue_test.go | 11 +- network/stub/hash.go | 2 +- network/test/cohort1/meshengine_test.go | 10 +- network/test/cohort1/network_test.go | 6 +- network/test/cohort2/blob_service_test.go | 6 +- network/test/cohort2/echoengine.go | 12 +- network/test/cohort2/echoengine_test.go | 26 +- network/test/cohort2/epochtransition_test.go | 4 +- .../cohort2/unicast_authorization_test.go | 12 +- .../authorized_sender_validator_test.go | 2 +- network/validator/target_validator.go | 8 +- state/cluster/badger/mutator_test.go | 2 +- state/cluster/badger/snapshot_test.go | 4 +- state/fork/traversal_test.go | 4 +- state/protocol/badger/snapshot_test.go | 12 +- state/protocol/badger/state_test.go | 2 +- state/protocol/datastore/params.go | 2 +- .../epochs/fallback_statemachine_test.go | 6 +- .../protocol_state/epochs/identity_ejector.go | 4 +- .../state/mutable_protocol_state_test.go | 8 +- storage/badger/operation/common.go | 18 +- storage/badger/operation/common_test.go | 6 +- storage/indexes/account_ft_transfers_test.go | 4 +- storage/indexes/account_nft_transfers_test.go | 4 +- storage/indexes/account_transactions_test.go | 4 +- storage/migration/migration.go | 2 +- storage/migration/migration_test.go | 2 +- storage/migration/sstables.go | 12 +- storage/operation/chunk_data_packs_test.go | 6 +- storage/operation/cluster_test.go | 12 +- storage/operation/iterate_bench_test.go | 4 +- storage/operation/multi_iterator_test.go | 2 +- storage/operation/stats_test.go | 6 +- storage/operation/writes_bench_test.go | 4 +- storage/operation/writes_test.go | 12 +- storage/pebble/bootstrap.go | 2 +- storage/pebble/bootstrap_test.go | 4 +- storage/pebble/registers/comparer_test.go | 1 + storage/pebble/registers_test.go | 4 +- storage/store/collections_test.go | 16 +- storage/store/headers_test.go | 2 +- .../latest_persisted_sealed_result_test.go | 8 +- .../store/light_transaction_results_test.go | 2 +- storage/store/my_receipts_test.go | 2 +- .../transaction_result_error_messages_test.go | 10 +- storage/store/transaction_results_test.go | 10 +- storage/util/logger.go | 10 +- tools/structwrite/go.mod | 2 +- tools/test_monitor/common/utility.go | 4 +- .../level1/process_summary1_results.go | 5 +- .../level2/process_summary2_results.go | 4 +- utils/binstat/binstat_external_test.go | 20 +- utils/dsl/dsl.go | 6 +- utils/grpcutils/grpc.go | 4 +- utils/helpers.go | 2 +- utils/io/filelock_test.go | 4 +- utils/io/write.go | 2 +- utils/unittest/cluster.go | 2 +- utils/unittest/encoding.go | 4 +- utils/unittest/entity.go | 13 +- utils/unittest/epoch_builder.go | 2 +- utils/unittest/events.go | 4 +- utils/unittest/fixtures.go | 80 ++-- .../unittest/fixtures/collection_guarantee.go | 2 +- utils/unittest/fixtures/service_event.go | 2 +- .../fixtures/service_event_epoch_setup.go | 8 +- utils/unittest/incorporated_results_seals.go | 2 +- utils/unittest/keys.go | 4 +- utils/unittest/lifecycle.go | 4 +- utils/unittest/locks.go | 2 +- utils/unittest/math.go | 2 +- utils/unittest/seals.go | 2 +- utils/unittest/unittest.go | 18 +- utils/unittest/utils.go | 4 +- 511 files changed, 2337 insertions(+), 2030 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bb6f0d4a967..174dbbab3a4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,7 +20,7 @@ on: workflow_dispatch: env: - GO_VERSION: "1.26" + GO_VERSION: "1.25" concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }} diff --git a/.github/workflows/flaky-test-monitor.yml b/.github/workflows/flaky-test-monitor.yml index e754ebc32fb..329342608ae 100644 --- a/.github/workflows/flaky-test-monitor.yml +++ b/.github/workflows/flaky-test-monitor.yml @@ -13,7 +13,7 @@ permissions: contents: read env: - GO_VERSION: "1.26" + GO_VERSION: "1.25" BIGQUERY_DATASET: dev_src_flow_test_metrics BIGQUERY_TABLE: skipped_tests BIGQUERY_TABLE2: test_results diff --git a/.github/workflows/image_builds.yml b/.github/workflows/image_builds.yml index 9a354626cfc..2b02568e282 100644 --- a/.github/workflows/image_builds.yml +++ b/.github/workflows/image_builds.yml @@ -16,7 +16,7 @@ on: type: string env: - GO_VERSION: "1.26" + GO_VERSION: "1.25" PRIVATE_REGISTRY_HOST: us-central1-docker.pkg.dev jobs: diff --git a/.github/workflows/tools.yml b/.github/workflows/tools.yml index c8e92a775f6..84e1d947224 100644 --- a/.github/workflows/tools.yml +++ b/.github/workflows/tools.yml @@ -14,7 +14,7 @@ on: type: boolean env: - GO_VERSION: "1.26" + GO_VERSION: "1.25" jobs: build-publish: diff --git a/README.md b/README.md index a1b759c06f1..1233ea9f153 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ The following table lists all work streams and links to their home directory and ## Installation - Clone this repository -- Install [Go](https://golang.org/doc/install) (Flow requires Go 1.26 and later) +- Install [Go](https://golang.org/doc/install) (Flow requires Go 1.25 and later) - Install [Docker](https://docs.docker.com/get-docker/), which is used for running a local network and integration tests - Make sure the [`GOPATH`](https://golang.org/cmd/go/#hdr-GOPATH_environment_variable) and `GOBIN` environment variables are set, and `GOBIN` is added to your path: @@ -220,7 +220,7 @@ flow-go is the **protocol / node** implementation. [`onflow/cadence`](https://gi Access, Collection, Consensus, Execution, and Verification. Each has its own entry point under `/cmd/`. There is also an Observer service for staking-free read-only access. ### Which Go version does flow-go require? -Go 1.26 or later. See the [Installation](#installation) section for the full environment setup. +Go 1.25 or later. See the [Installation](#installation) section for the full environment setup. ### Where is the consensus algorithm implemented? Under [`/consensus/hotstuff`](/consensus/hotstuff). HotStuff is the BFT consensus family used by Flow. diff --git a/admin/command_runner.go b/admin/command_runner.go index 0ce9a03d6c5..cd296b010f1 100644 --- a/admin/command_runner.go +++ b/admin/command_runner.go @@ -5,7 +5,6 @@ import ( "crypto/tls" "errors" "fmt" - "maps" "net" "net/http" "net/http/pprof" @@ -92,7 +91,9 @@ func (r *CommandRunnerBootstrapper) Bootstrap(logger zerolog.Logger, bindAddress } validators := make(map[string]CommandValidator) - maps.Copy(validators, r.validators) + for command, validator := range r.validators { + validators[command] = validator + } commandRunner := &CommandRunner{ handlers: handlers, diff --git a/admin/commands/collection/tx_rate_limiter.go b/admin/commands/collection/tx_rate_limiter.go index 2f725464afa..c767f080156 100644 --- a/admin/commands/collection/tx_rate_limiter.go +++ b/admin/commands/collection/tx_rate_limiter.go @@ -29,8 +29,8 @@ func NewTxRateLimitCommand(limiter *ingest.AddressRateLimiter) *TxRateLimitComma } } -func (s *TxRateLimitCommand) Handler(_ context.Context, req *admin.CommandRequest) (any, error) { - input, ok := req.Data.(map[string]any) +func (s *TxRateLimitCommand) Handler(_ context.Context, req *admin.CommandRequest) (interface{}, error) { + input, ok := req.Data.(map[string]interface{}) if !ok { return admin.NewInvalidAdminReqFormatError("expected { \"command\": \"add|remove|get|get_config|set_config\", \"addresses\": \"addresses\""), nil } diff --git a/admin/commands/common/get_config.go b/admin/commands/common/get_config.go index b47ebae5d6c..3b0983fb2ca 100644 --- a/admin/commands/common/get_config.go +++ b/admin/commands/common/get_config.go @@ -28,7 +28,7 @@ type validatedGetConfigData struct { field updatable_configs.Field } -func (s *GetConfigCommand) Handler(_ context.Context, req *admin.CommandRequest) (any, error) { +func (s *GetConfigCommand) Handler(_ context.Context, req *admin.CommandRequest) (interface{}, error) { validatedReq := req.ValidatorData.(validatedGetConfigData) curValue := validatedReq.field.Get() return curValue, nil diff --git a/admin/commands/common/get_identity.go b/admin/commands/common/get_identity.go index 3174bcd20a3..09509b76a9c 100644 --- a/admin/commands/common/get_identity.go +++ b/admin/commands/common/get_identity.go @@ -32,7 +32,7 @@ type GetIdentityCommand struct { idProvider module.IdentityProvider } -func (r *GetIdentityCommand) Handler(ctx context.Context, req *admin.CommandRequest) (any, error) { +func (r *GetIdentityCommand) Handler(ctx context.Context, req *admin.CommandRequest) (interface{}, error) { data := req.ValidatorData.(*getIdentityRequestData) if data.requestType == FlowID { @@ -53,7 +53,7 @@ func (r *GetIdentityCommand) Handler(ctx context.Context, req *admin.CommandRequ // Validator validates the request. // Returns admin.InvalidAdminReqError for invalid/malformed requests. func (r *GetIdentityCommand) Validator(req *admin.CommandRequest) error { - input, ok := req.Data.(map[string]any) + input, ok := req.Data.(map[string]interface{}) if !ok { return admin.NewInvalidAdminReqFormatError("expected map[string]any") } diff --git a/admin/commands/common/list_configs.go b/admin/commands/common/list_configs.go index dbd04fda64d..1ffe9a1e154 100644 --- a/admin/commands/common/list_configs.go +++ b/admin/commands/common/list_configs.go @@ -22,7 +22,7 @@ func NewListConfigCommand(configs *updatable_configs.Manager) *ListConfigCommand } } -func (s *ListConfigCommand) Handler(_ context.Context, _ *admin.CommandRequest) (any, error) { +func (s *ListConfigCommand) Handler(_ context.Context, _ *admin.CommandRequest) (interface{}, error) { fields := s.configs.AllFields() // create a response diff --git a/admin/commands/common/read_protocol_state_blocks.go b/admin/commands/common/read_protocol_state_blocks.go index 8ac7c0203c8..288b3cf010a 100644 --- a/admin/commands/common/read_protocol_state_blocks.go +++ b/admin/commands/common/read_protocol_state_blocks.go @@ -100,7 +100,7 @@ func (r *ReadProtocolStateBlocksCommand) getBlockByHeader(header *flow.Header) ( return block, nil } -func (r *ReadProtocolStateBlocksCommand) Handler(_ context.Context, req *admin.CommandRequest) (any, error) { +func (r *ReadProtocolStateBlocksCommand) Handler(_ context.Context, req *admin.CommandRequest) (interface{}, error) { data := req.ValidatorData.(*requestData) var result []*flow.Block var block *flow.Block @@ -132,7 +132,7 @@ func (r *ReadProtocolStateBlocksCommand) Handler(_ context.Context, req *admin.C result = append(result, block) } - var resultList []any + var resultList []interface{} bytes, err := json.Marshal(result) if err != nil { return nil, err @@ -145,7 +145,7 @@ func (r *ReadProtocolStateBlocksCommand) Handler(_ context.Context, req *admin.C // Validator validates the request. // Returns admin.InvalidAdminReqError for invalid/malformed requests. func (r *ReadProtocolStateBlocksCommand) Validator(req *admin.CommandRequest) error { - input, ok := req.Data.(map[string]any) + input, ok := req.Data.(map[string]interface{}) if !ok { return admin.NewInvalidAdminReqFormatError("expected map[string]any") } diff --git a/admin/commands/common/read_protocol_state_blocks_test.go b/admin/commands/common/read_protocol_state_blocks_test.go index 3bcb4dcc216..e17e579c3a0 100644 --- a/admin/commands/common/read_protocol_state_blocks_test.go +++ b/admin/commands/common/read_protocol_state_blocks_test.go @@ -125,7 +125,7 @@ func (suite *ReadProtocolStateBlocksSuite) TestValidateInvalidFormat() { Data: "foo", })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "blah": 123, }, })) @@ -133,22 +133,22 @@ func (suite *ReadProtocolStateBlocksSuite) TestValidateInvalidFormat() { func (suite *ReadProtocolStateBlocksSuite) TestValidateInvalidBlock() { assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": true, }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": "", }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": "uhznms", }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": "deadbeef", }, })) @@ -156,12 +156,12 @@ func (suite *ReadProtocolStateBlocksSuite) TestValidateInvalidBlock() { func (suite *ReadProtocolStateBlocksSuite) TestValidateInvalidBlockHeight() { assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": float64(-1), }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": float64(1.1), }, })) @@ -169,26 +169,26 @@ func (suite *ReadProtocolStateBlocksSuite) TestValidateInvalidBlockHeight() { func (suite *ReadProtocolStateBlocksSuite) TestValidateInvalidN() { assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": 1, "n": "foo", }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": 1, "n": float64(1.1), }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": 1, "n": float64(0), }, })) } -func (suite *ReadProtocolStateBlocksSuite) getBlocks(reqData map[string]any) []*flow.Block { +func (suite *ReadProtocolStateBlocksSuite) getBlocks(reqData map[string]interface{}) []*flow.Block { ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -208,7 +208,7 @@ func (suite *ReadProtocolStateBlocksSuite) getBlocks(reqData map[string]any) []* } func (suite *ReadProtocolStateBlocksSuite) TestHandleFinal() { - blocks := suite.getBlocks(map[string]any{ + blocks := suite.getBlocks(map[string]interface{}{ "block": "final", }) require.Len(suite.T(), blocks, 1) @@ -216,7 +216,7 @@ func (suite *ReadProtocolStateBlocksSuite) TestHandleFinal() { } func (suite *ReadProtocolStateBlocksSuite) TestHandleSealed() { - blocks := suite.getBlocks(map[string]any{ + blocks := suite.getBlocks(map[string]interface{}{ "block": "sealed", }) require.Len(suite.T(), blocks, 1) @@ -225,7 +225,7 @@ func (suite *ReadProtocolStateBlocksSuite) TestHandleSealed() { func (suite *ReadProtocolStateBlocksSuite) TestHandleHeight() { for i, block := range suite.allBlocks { - responseBlocks := suite.getBlocks(map[string]any{ + responseBlocks := suite.getBlocks(map[string]interface{}{ "block": float64(i), }) require.Len(suite.T(), responseBlocks, 1) @@ -235,7 +235,7 @@ func (suite *ReadProtocolStateBlocksSuite) TestHandleHeight() { func (suite *ReadProtocolStateBlocksSuite) TestHandleID() { for _, block := range suite.allBlocks { - responseBlocks := suite.getBlocks(map[string]any{ + responseBlocks := suite.getBlocks(map[string]interface{}{ "block": block.ID().String(), }) require.Len(suite.T(), responseBlocks, 1) @@ -244,7 +244,7 @@ func (suite *ReadProtocolStateBlocksSuite) TestHandleID() { } func (suite *ReadProtocolStateBlocksSuite) TestHandleNExceedsRootBlock() { - responseBlocks := suite.getBlocks(map[string]any{ + responseBlocks := suite.getBlocks(map[string]interface{}{ "block": "final", "n": float64(len(suite.allBlocks) + 1), }) diff --git a/admin/commands/common/set_config.go b/admin/commands/common/set_config.go index 3b37894621a..7b4381ed1c4 100644 --- a/admin/commands/common/set_config.go +++ b/admin/commands/common/set_config.go @@ -30,7 +30,7 @@ type validatedSetConfigData struct { value any } -func (s *SetConfigCommand) Handler(_ context.Context, req *admin.CommandRequest) (any, error) { +func (s *SetConfigCommand) Handler(_ context.Context, req *admin.CommandRequest) (interface{}, error) { validatedReq := req.ValidatorData.(validatedSetConfigData) oldValue := validatedReq.field.Get() diff --git a/admin/commands/common/set_golog_level.go b/admin/commands/common/set_golog_level.go index 812bf13a174..2c0a7d6cd9b 100644 --- a/admin/commands/common/set_golog_level.go +++ b/admin/commands/common/set_golog_level.go @@ -16,7 +16,7 @@ var _ commands.AdminCommand = (*SetGologLevelCommand)(nil) type SetGologLevelCommand struct{} -func (s *SetGologLevelCommand) Handler(ctx context.Context, req *admin.CommandRequest) (any, error) { +func (s *SetGologLevelCommand) Handler(ctx context.Context, req *admin.CommandRequest) (interface{}, error) { level := req.ValidatorData.(golog.LogLevel) golog.SetAllLoggers(level) diff --git a/admin/commands/common/set_log_level.go b/admin/commands/common/set_log_level.go index 3c30f7a2617..a7812db8375 100644 --- a/admin/commands/common/set_log_level.go +++ b/admin/commands/common/set_log_level.go @@ -14,7 +14,7 @@ var _ commands.AdminCommand = (*SetLogLevelCommand)(nil) type SetLogLevelCommand struct{} -func (s *SetLogLevelCommand) Handler(_ context.Context, req *admin.CommandRequest) (any, error) { +func (s *SetLogLevelCommand) Handler(_ context.Context, req *admin.CommandRequest) (interface{}, error) { level := req.ValidatorData.(zerolog.Level) zerolog.SetGlobalLevel(level) diff --git a/admin/commands/execution/checkpoint_trigger.go b/admin/commands/execution/checkpoint_trigger.go index f69d9b3e689..0a396ec23e4 100644 --- a/admin/commands/execution/checkpoint_trigger.go +++ b/admin/commands/execution/checkpoint_trigger.go @@ -35,7 +35,7 @@ func NewTriggerCheckpointCommand(trigger *atomic.Bool, ledgerServiceAddr, ledger } } -func (s *TriggerCheckpointCommand) Handler(_ context.Context, _ *admin.CommandRequest) (any, error) { +func (s *TriggerCheckpointCommand) Handler(_ context.Context, _ *admin.CommandRequest) (interface{}, error) { if s.trigger.CompareAndSwap(false, true) { log.Info().Msgf("admintool: trigger checkpoint as soon as finishing writing the current segment file. you can find log about 'compactor' to check the checkpointing progress") } else { diff --git a/admin/commands/execution/stop_at_height.go b/admin/commands/execution/stop_at_height.go index c3e55857159..fd88a8c4f10 100644 --- a/admin/commands/execution/stop_at_height.go +++ b/admin/commands/execution/stop_at_height.go @@ -33,7 +33,7 @@ type StopAtHeightReq struct { // Handler method sets the stop height parameters. // Errors only if setting of stop height parameters fails. // Returns "ok" if successful. -func (s *StopAtHeightCommand) Handler(_ context.Context, req *admin.CommandRequest) (any, error) { +func (s *StopAtHeightCommand) Handler(_ context.Context, req *admin.CommandRequest) (interface{}, error) { sah := req.ValidatorData.(StopAtHeightReq) oldParams := s.stopControl.GetStopParameters() @@ -66,7 +66,7 @@ func (s *StopAtHeightCommand) Handler(_ context.Context, req *admin.CommandReque // * `admin.InvalidAdminReqError` if any required field is missing or in a wrong format func (s *StopAtHeightCommand) Validator(req *admin.CommandRequest) error { - input, ok := req.Data.(map[string]any) + input, ok := req.Data.(map[string]interface{}) if !ok { return admin.NewInvalidAdminReqFormatError("expected map[string]any") } diff --git a/admin/commands/execution/stop_at_height_test.go b/admin/commands/execution/stop_at_height_test.go index cbfe8f8c076..f78858d97c7 100644 --- a/admin/commands/execution/stop_at_height_test.go +++ b/admin/commands/execution/stop_at_height_test.go @@ -20,7 +20,7 @@ func TestCommandParsing(t *testing.T) { t.Run("happy path", func(t *testing.T) { req := &admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "height": float64(21), // raw json parses to float64 "crash": true, }, @@ -40,7 +40,7 @@ func TestCommandParsing(t *testing.T) { t.Run("empty", func(t *testing.T) { req := &admin.CommandRequest{ - Data: map[string]any{}, + Data: map[string]interface{}{}, } err := cmd.Validator(req) @@ -51,7 +51,7 @@ func TestCommandParsing(t *testing.T) { t.Run("wrong height type", func(t *testing.T) { req := &admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "height": "abc", }, } @@ -64,7 +64,7 @@ func TestCommandParsing(t *testing.T) { t.Run("wrong height type", func(t *testing.T) { req := &admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "height": "abc", }, } @@ -77,7 +77,7 @@ func TestCommandParsing(t *testing.T) { t.Run("negative", func(t *testing.T) { req := &admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "height": -12, }, } diff --git a/admin/commands/state_synchronization/execute_script.go b/admin/commands/state_synchronization/execute_script.go index 5592482e93b..237bb3907a7 100644 --- a/admin/commands/state_synchronization/execute_script.go +++ b/admin/commands/state_synchronization/execute_script.go @@ -22,7 +22,7 @@ type ExecuteScriptCommand struct { scriptExecutor execution.ScriptExecutor } -func (e *ExecuteScriptCommand) Handler(ctx context.Context, req *admin.CommandRequest) (any, error) { +func (e *ExecuteScriptCommand) Handler(ctx context.Context, req *admin.CommandRequest) (interface{}, error) { d := req.ValidatorData.(*scriptData) result, err := e.scriptExecutor.ExecuteAtBlockHeight(context.Background(), d.script, d.arguments, d.height) @@ -36,7 +36,7 @@ func (e *ExecuteScriptCommand) Handler(ctx context.Context, req *admin.CommandRe // Validator validates the request. // Returns admin.InvalidAdminReqError for invalid/malformed requests. func (e *ExecuteScriptCommand) Validator(req *admin.CommandRequest) error { - input, ok := req.Data.(map[string]any) + input, ok := req.Data.(map[string]interface{}) if !ok { return admin.NewInvalidAdminReqFormatError("expected map[string]any") } diff --git a/admin/commands/state_synchronization/read_execution_data.go b/admin/commands/state_synchronization/read_execution_data.go index bba9ad5ad92..5b3e4a98f75 100644 --- a/admin/commands/state_synchronization/read_execution_data.go +++ b/admin/commands/state_synchronization/read_execution_data.go @@ -21,7 +21,7 @@ type ReadExecutionDataCommand struct { executionDataStore execution_data.ExecutionDataStore } -func (r *ReadExecutionDataCommand) Handler(ctx context.Context, req *admin.CommandRequest) (any, error) { +func (r *ReadExecutionDataCommand) Handler(ctx context.Context, req *admin.CommandRequest) (interface{}, error) { data := req.ValidatorData.(*requestData) ed, err := r.executionDataStore.Get(ctx, data.rootID) @@ -36,7 +36,7 @@ func (r *ReadExecutionDataCommand) Handler(ctx context.Context, req *admin.Comma // Validator validates the request. // Returns admin.InvalidAdminReqError for invalid/malformed requests. func (r *ReadExecutionDataCommand) Validator(req *admin.CommandRequest) error { - input, ok := req.Data.(map[string]any) + input, ok := req.Data.(map[string]interface{}) if !ok { return admin.NewInvalidAdminReqFormatError("expected map[string]any") } diff --git a/admin/commands/storage/backfill_tx_error_messages.go b/admin/commands/storage/backfill_tx_error_messages.go index 1c8e3f717dd..48ea8ff6de8 100644 --- a/admin/commands/storage/backfill_tx_error_messages.go +++ b/admin/commands/storage/backfill_tx_error_messages.go @@ -53,7 +53,7 @@ func NewBackfillTxErrorMessagesCommand( // - admin.InvalidAdminReqError - if start-height is greater than end-height or // if the input format is invalid, if an invalid execution node ID is provided. func (b *BackfillTxErrorMessagesCommand) Validator(request *admin.CommandRequest) error { - input, ok := request.Data.(map[string]any) + input, ok := request.Data.(map[string]interface{}) if !ok { return admin.NewInvalidAdminReqFormatError("expected map[string]any") } @@ -146,7 +146,7 @@ func (b *BackfillTxErrorMessagesCommand) Validator(request *admin.CommandRequest // from data.executionNodeIds if available, otherwise defaults to valid execution nodes. // // No errors are expected during normal operation. -func (b *BackfillTxErrorMessagesCommand) Handler(ctx context.Context, request *admin.CommandRequest) (any, error) { +func (b *BackfillTxErrorMessagesCommand) Handler(ctx context.Context, request *admin.CommandRequest) (interface{}, error) { if b.txErrorMessagesCore == nil { return nil, fmt.Errorf("failed to backfill, could not get transaction error messages storage") } @@ -187,7 +187,7 @@ func (b *BackfillTxErrorMessagesCommand) Handler(ctx context.Context, request *a // // Expected errors during normal operation: // - admin.InvalidAdminReqParameterError - if execution-node-ids is empty or has an invalid format. -func (b *BackfillTxErrorMessagesCommand) parseExecutionNodeIds(executionNodeIdsIn any, allIdentities flow.IdentityList) (flow.IdentitySkeletonList, error) { +func (b *BackfillTxErrorMessagesCommand) parseExecutionNodeIds(executionNodeIdsIn interface{}, allIdentities flow.IdentityList) (flow.IdentitySkeletonList, error) { var ids flow.IdentityList switch executionNodeIds := executionNodeIdsIn.(type) { case []any: diff --git a/admin/commands/storage/backfill_tx_error_messages_test.go b/admin/commands/storage/backfill_tx_error_messages_test.go index 75e341b0084..ce7a11211b2 100644 --- a/admin/commands/storage/backfill_tx_error_messages_test.go +++ b/admin/commands/storage/backfill_tx_error_messages_test.go @@ -180,7 +180,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestValidateInvalidFormat() { // invalid start-height suite.Run("invalid start-height field", func() { err := suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "start-height": "123", }, }) @@ -194,7 +194,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestValidateInvalidFormat() { suite.Run("start-height is greater than latest sealed block", func() { startHeight := 100 err := suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "start-height": float64(startHeight), }, }) @@ -209,7 +209,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestValidateInvalidFormat() { startHeight := 1 err := suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "start-height": float64(startHeight), }, }) @@ -223,7 +223,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestValidateInvalidFormat() { // invalid end-height suite.Run("invalid end-height field", func() { err := suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "end-height": "123", }, }) @@ -237,7 +237,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestValidateInvalidFormat() { suite.Run("invalid end-height is greater than latest sealed block", func() { endHeight := 100 err := suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "start-height": float64(1), // raw json parses to float64 "end-height": float64(endHeight), // raw json parses to float64 "execution-node-ids": []any{suite.allENIDs[0].NodeID.String()}, @@ -255,7 +255,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestValidateInvalidFormat() { startHeight := 3 endHeight := 1 err := suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "start-height": float64(startHeight), // raw json parses to float64 "end-height": float64(endHeight), // raw json parses to float64 }, @@ -269,7 +269,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestValidateInvalidFormat() { suite.Run("invalid execution-node-ids field", func() { // invalid type err := suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "execution-node-ids": []int{1, 2, 3}, }, }) @@ -279,7 +279,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestValidateInvalidFormat() { // invalid type err = suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "execution-node-ids": "123", }, }) @@ -290,7 +290,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestValidateInvalidFormat() { // invalid execution node id invalidENID := unittest.IdentifierFixture() err = suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "start-height": float64(1), // raw json parses to float64 "end-height": float64(4), // raw json parses to float64 "execution-node-ids": []any{invalidENID.String()}, @@ -313,7 +313,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestValidateValidFormat() { // execution-node-ids is not provided, any valid execution node will be used. suite.Run("happy case, all default parameters", func() { err := suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{}, + Data: map[string]interface{}{}, }) suite.NoError(err) }) @@ -321,7 +321,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestValidateValidFormat() { // all parameters are provided suite.Run("happy case, all parameters are provided", func() { err := suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "start-height": float64(1), // raw json parses to float64 "end-height": float64(3), // raw json parses to float64 "execution-node-ids": []any{suite.allENIDs[0].NodeID.String()}, @@ -339,7 +339,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestHandleBackfillTxErrorMessages() { // default parameters req := &admin.CommandRequest{ - Data: map[string]any{}, + Data: map[string]interface{}{}, } suite.Require().NoError(suite.command.Validator(req)) @@ -389,7 +389,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestHandleBackfillTxErrorMessages() { executorID := suite.allENIDs[1].NodeID req = &admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "start-height": float64(startHeight), // raw json parses to float64 "end-height": float64(endHeight), // raw json parses to float64 "execution-node-ids": []any{executorID.String()}, @@ -433,7 +433,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestHandleBackfillTxErrorMessagesErro defer cancel() suite.Run("error when txErrorMessagesCore is nil", func() { - req := &admin.CommandRequest{Data: map[string]any{}} + req := &admin.CommandRequest{Data: map[string]interface{}{}} command := NewBackfillTxErrorMessagesCommand( suite.log, suite.state, @@ -448,7 +448,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestHandleBackfillTxErrorMessagesErro suite.Run("error when failing to retrieve block header", func() { req := &admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "start-height": float64(1), // raw json parses to float64 }, } @@ -471,7 +471,7 @@ func (suite *BackfillTxErrorMessagesSuite) TestHandleBackfillTxErrorMessagesErro func (suite *BackfillTxErrorMessagesSuite) generateResultsForBlock() []flow.LightTransactionResult { results := make([]flow.LightTransactionResult, 0) - for i := range 5 { + for i := 0; i < 5; i++ { results = append(results, flow.LightTransactionResult{ TransactionID: unittest.IdentifierFixture(), Failed: i%2 == 0, // create a mix of failed and non-failed transactions diff --git a/admin/commands/storage/helper.go b/admin/commands/storage/helper.go index 0c84737dfab..e8166cb731a 100644 --- a/admin/commands/storage/helper.go +++ b/admin/commands/storage/helper.go @@ -26,12 +26,12 @@ const ( type blocksRequest struct { requestType blocksRequestType - value any + value interface{} } // parseN verifies that the input is an integral float64 value >=1. // All generic errors indicate a benign validation failure, and should be wrapped by the caller. -func parseN(m any) (uint64, error) { +func parseN(m interface{}) (uint64, error) { n, ok := m.(float64) if !ok { return 0, fmt.Errorf("invalid value for \"n\": %v", n) @@ -47,7 +47,7 @@ func parseN(m any) (uint64, error) { // parseBlocksRequest parses the block field of an admin request. // All generic errors indicate a benign validation failure, and should be wrapped by the caller. -func parseBlocksRequest(block any) (*blocksRequest, error) { +func parseBlocksRequest(block interface{}) (*blocksRequest, error) { errInvalidBlockValue := fmt.Errorf("invalid value for \"block\": expected %q, %q, block ID, or block height, but got: %v", FINAL, SEALED, block) req := &blocksRequest{} @@ -93,7 +93,7 @@ func getBlockHeader(state protocol.State, req *blocksRequest) (*flow.Header, err } func parseHeightRangeRequestData(req *admin.CommandRequest) (*heightRangeReqData, error) { - input, ok := req.Data.(map[string]any) + input, ok := req.Data.(map[string]interface{}) if !ok { return nil, admin.NewInvalidAdminReqFormatError("missing 'data' field") } @@ -119,7 +119,7 @@ func parseHeightRangeRequestData(req *admin.CommandRequest) (*heightRangeReqData } func parseString(req *admin.CommandRequest, field string) (string, error) { - input, ok := req.Data.(map[string]any) + input, ok := req.Data.(map[string]interface{}) if !ok { return "", admin.NewInvalidAdminReqFormatError("missing 'data' field") } @@ -131,7 +131,7 @@ func parseString(req *admin.CommandRequest, field string) (string, error) { } // Returns admin.InvalidAdminReqError for invalid inputs -func findUint64(input map[string]any, field string) (uint64, error) { +func findUint64(input map[string]interface{}, field string) (uint64, error) { data, ok := input[field] if !ok { return 0, admin.NewInvalidAdminReqErrorf("missing required field '%s'", field) @@ -144,7 +144,7 @@ func findUint64(input map[string]any, field string) (uint64, error) { return uint64(val), nil } -func findString(input map[string]any, field string) (string, error) { +func findString(input map[string]interface{}, field string) (string, error) { data, ok := input[field] if !ok { return "", admin.NewInvalidAdminReqErrorf("missing required field '%s'", field) diff --git a/admin/commands/storage/pebble_checkpoint.go b/admin/commands/storage/pebble_checkpoint.go index 74362b2e63b..64a2274610b 100644 --- a/admin/commands/storage/pebble_checkpoint.go +++ b/admin/commands/storage/pebble_checkpoint.go @@ -31,7 +31,7 @@ func NewPebbleDBCheckpointCommand(checkpointDir string, dbname string, pebbleDB } } -func (c *PebbleDBCheckpointCommand) Handler(ctx context.Context, req *admin.CommandRequest) (any, error) { +func (c *PebbleDBCheckpointCommand) Handler(ctx context.Context, req *admin.CommandRequest) (interface{}, error) { log.Info().Msgf("admintool: creating %v database checkpoint", c.dbname) targetDir := nextTmpFolder(c.checkpointDir) diff --git a/admin/commands/storage/read_blocks.go b/admin/commands/storage/read_blocks.go index f07ea727b9f..b05c06721a8 100644 --- a/admin/commands/storage/read_blocks.go +++ b/admin/commands/storage/read_blocks.go @@ -25,7 +25,7 @@ type ReadBlocksCommand struct { blocks storage.Blocks } -func (r *ReadBlocksCommand) Handler(ctx context.Context, req *admin.CommandRequest) (any, error) { +func (r *ReadBlocksCommand) Handler(ctx context.Context, req *admin.CommandRequest) (interface{}, error) { data := req.ValidatorData.(*readBlocksRequest) var result []*flow.Block var blockID flow.Identifier @@ -56,7 +56,7 @@ func (r *ReadBlocksCommand) Handler(ctx context.Context, req *admin.CommandReque // Validator validates the request. // Returns admin.InvalidAdminReqError for invalid/malformed requests. func (r *ReadBlocksCommand) Validator(req *admin.CommandRequest) error { - input, ok := req.Data.(map[string]any) + input, ok := req.Data.(map[string]interface{}) if !ok { return admin.NewInvalidAdminReqFormatError("expected map[string]any") } diff --git a/admin/commands/storage/read_blocks_test.go b/admin/commands/storage/read_blocks_test.go index 4de010358d3..e48a69b91d8 100644 --- a/admin/commands/storage/read_blocks_test.go +++ b/admin/commands/storage/read_blocks_test.go @@ -125,7 +125,7 @@ func (suite *ReadBlocksSuite) TestValidateInvalidFormat() { Data: "foo", })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "blah": 123, }, })) @@ -133,22 +133,22 @@ func (suite *ReadBlocksSuite) TestValidateInvalidFormat() { func (suite *ReadBlocksSuite) TestValidateInvalidBlock() { assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": true, }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": "", }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": "uhznms", }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": "deadbeef", }, })) @@ -156,12 +156,12 @@ func (suite *ReadBlocksSuite) TestValidateInvalidBlock() { func (suite *ReadBlocksSuite) TestValidateInvalidBlockHeight() { assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": float64(-1), }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": float64(1.1), }, })) @@ -169,26 +169,26 @@ func (suite *ReadBlocksSuite) TestValidateInvalidBlockHeight() { func (suite *ReadBlocksSuite) TestValidateInvalidN() { assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": 1, "n": "foo", }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": 1, "n": float64(1.1), }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "block": 1, "n": float64(0), }, })) } -func (suite *ReadBlocksSuite) getBlocks(reqData map[string]any) []*flow.Block { +func (suite *ReadBlocksSuite) getBlocks(reqData map[string]interface{}) []*flow.Block { ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -208,7 +208,7 @@ func (suite *ReadBlocksSuite) getBlocks(reqData map[string]any) []*flow.Block { } func (suite *ReadBlocksSuite) TestHandleFinal() { - blocks := suite.getBlocks(map[string]any{ + blocks := suite.getBlocks(map[string]interface{}{ "block": "final", }) require.Len(suite.T(), blocks, 1) @@ -216,7 +216,7 @@ func (suite *ReadBlocksSuite) TestHandleFinal() { } func (suite *ReadBlocksSuite) TestHandleSealed() { - blocks := suite.getBlocks(map[string]any{ + blocks := suite.getBlocks(map[string]interface{}{ "block": "sealed", }) require.Len(suite.T(), blocks, 1) @@ -225,7 +225,7 @@ func (suite *ReadBlocksSuite) TestHandleSealed() { func (suite *ReadBlocksSuite) TestHandleHeight() { for i, block := range suite.allBlocks { - responseBlocks := suite.getBlocks(map[string]any{ + responseBlocks := suite.getBlocks(map[string]interface{}{ "block": float64(i), }) require.Len(suite.T(), responseBlocks, 1) @@ -235,7 +235,7 @@ func (suite *ReadBlocksSuite) TestHandleHeight() { func (suite *ReadBlocksSuite) TestHandleID() { for _, block := range suite.allBlocks { - responseBlocks := suite.getBlocks(map[string]any{ + responseBlocks := suite.getBlocks(map[string]interface{}{ "block": block.ID().String(), }) require.Len(suite.T(), responseBlocks, 1) @@ -244,7 +244,7 @@ func (suite *ReadBlocksSuite) TestHandleID() { } func (suite *ReadBlocksSuite) TestHandleNExceedsRootBlock() { - responseBlocks := suite.getBlocks(map[string]any{ + responseBlocks := suite.getBlocks(map[string]interface{}{ "block": "final", "n": float64(len(suite.allBlocks) + 1), }) diff --git a/admin/commands/storage/read_protocol_snapshot.go b/admin/commands/storage/read_protocol_snapshot.go index bd3fe8c99db..738e6409936 100644 --- a/admin/commands/storage/read_protocol_snapshot.go +++ b/admin/commands/storage/read_protocol_snapshot.go @@ -47,7 +47,7 @@ func NewProtocolSnapshotCommand( } } -func (s *ProtocolSnapshotCommand) Handler(_ context.Context, req *admin.CommandRequest) (any, error) { +func (s *ProtocolSnapshotCommand) Handler(_ context.Context, req *admin.CommandRequest) (interface{}, error) { validated, ok := req.ValidatorData.(*protocolSnapshotData) if !ok { return nil, fmt.Errorf("fail to parse validator data") @@ -102,7 +102,7 @@ func (s *ProtocolSnapshotCommand) Validator(req *admin.CommandRequest) error { blocksToSkip: uint(0), } - input, ok := req.Data.(map[string]any) + input, ok := req.Data.(map[string]interface{}) if ok { data, ok := input["blocks-to-skip"] diff --git a/admin/commands/storage/read_range_blocks.go b/admin/commands/storage/read_range_blocks.go index 3a65e76135b..cc4d00d6354 100644 --- a/admin/commands/storage/read_range_blocks.go +++ b/admin/commands/storage/read_range_blocks.go @@ -27,7 +27,7 @@ func NewReadRangeBlocksCommand(blocks storage.Blocks) commands.AdminCommand { } } -func (c *ReadRangeBlocksCommand) Handler(ctx context.Context, req *admin.CommandRequest) (any, error) { +func (c *ReadRangeBlocksCommand) Handler(ctx context.Context, req *admin.CommandRequest) (interface{}, error) { reqData, err := parseHeightRangeRequestData(req) if err != nil { return nil, err diff --git a/admin/commands/storage/read_range_cluster_blocks.go b/admin/commands/storage/read_range_cluster_blocks.go index 894cc1caea8..b0e41b86fe8 100644 --- a/admin/commands/storage/read_range_cluster_blocks.go +++ b/admin/commands/storage/read_range_cluster_blocks.go @@ -34,7 +34,7 @@ func NewReadRangeClusterBlocksCommand(db storage.DB, headers *store.Headers, pay } } -func (c *ReadRangeClusterBlocksCommand) Handler(ctx context.Context, req *admin.CommandRequest) (any, error) { +func (c *ReadRangeClusterBlocksCommand) Handler(ctx context.Context, req *admin.CommandRequest) (interface{}, error) { chainID, err := parseString(req, "chain-id") if err != nil { return nil, err diff --git a/admin/commands/storage/read_results.go b/admin/commands/storage/read_results.go index 6afd2dbfc38..8eadd86d985 100644 --- a/admin/commands/storage/read_results.go +++ b/admin/commands/storage/read_results.go @@ -22,7 +22,7 @@ const ( type readResultsRequest struct { requestType readResultsRequestType - value any + value interface{} numResultsToQuery uint64 } @@ -31,7 +31,7 @@ type ReadResultsCommand struct { results storage.ExecutionResults } -func (r *ReadResultsCommand) Handler(ctx context.Context, req *admin.CommandRequest) (any, error) { +func (r *ReadResultsCommand) Handler(ctx context.Context, req *admin.CommandRequest) (interface{}, error) { data := req.ValidatorData.(*readResultsRequest) var results []*flow.ExecutionResult var resultID flow.Identifier @@ -67,7 +67,7 @@ func (r *ReadResultsCommand) Handler(ctx context.Context, req *admin.CommandRequ // Validator validates the request. // Returns admin.InvalidAdminReqError for invalid/malformed requests. func (r *ReadResultsCommand) Validator(req *admin.CommandRequest) error { - input, ok := req.Data.(map[string]any) + input, ok := req.Data.(map[string]interface{}) if !ok { return admin.NewInvalidAdminReqFormatError("expected map[string]any") } diff --git a/admin/commands/storage/read_results_test.go b/admin/commands/storage/read_results_test.go index 2acde0112d6..e78d4a6b5b2 100644 --- a/admin/commands/storage/read_results_test.go +++ b/admin/commands/storage/read_results_test.go @@ -158,33 +158,33 @@ func (suite *ReadResultsSuite) SetupTest() { func (suite *ReadResultsSuite) TestValidateInvalidResultID() { assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "result": true, }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "result": "", }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "result": "uhznms", }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "result": "deadbeef", }, })) assert.Error(suite.T(), suite.command.Validator(&admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "result": 1, }, })) } -func (suite *ReadResultsSuite) getResults(reqData map[string]any) []*flow.ExecutionResult { +func (suite *ReadResultsSuite) getResults(reqData map[string]interface{}) []*flow.ExecutionResult { ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -204,7 +204,7 @@ func (suite *ReadResultsSuite) getResults(reqData map[string]any) []*flow.Execut } func (suite *ReadResultsSuite) TestHandleFinalBlock() { - results := suite.getResults(map[string]any{ + results := suite.getResults(map[string]interface{}{ "block": "final", }) require.Len(suite.T(), results, 1) @@ -212,7 +212,7 @@ func (suite *ReadResultsSuite) TestHandleFinalBlock() { } func (suite *ReadResultsSuite) TestHandleSealedBlock() { - results := suite.getResults(map[string]any{ + results := suite.getResults(map[string]interface{}{ "block": "sealed", }) require.Len(suite.T(), results, 1) @@ -221,7 +221,7 @@ func (suite *ReadResultsSuite) TestHandleSealedBlock() { func (suite *ReadResultsSuite) TestHandleBlockHeight() { for i, result := range suite.allResults { - results := suite.getResults(map[string]any{ + results := suite.getResults(map[string]interface{}{ "block": float64(i), }) require.Len(suite.T(), results, 1) @@ -231,7 +231,7 @@ func (suite *ReadResultsSuite) TestHandleBlockHeight() { func (suite *ReadResultsSuite) TestHandleBlockID() { for i, result := range suite.allResults { - results := suite.getResults(map[string]any{ + results := suite.getResults(map[string]interface{}{ "block": suite.allBlocks[i].ID().String(), }) require.Len(suite.T(), results, 1) @@ -241,7 +241,7 @@ func (suite *ReadResultsSuite) TestHandleBlockID() { func (suite *ReadResultsSuite) TestHandleID() { for _, result := range suite.allResults { - results := suite.getResults(map[string]any{ + results := suite.getResults(map[string]interface{}{ "result": result.ID().String(), }) require.Len(suite.T(), results, 1) @@ -251,7 +251,7 @@ func (suite *ReadResultsSuite) TestHandleID() { func (suite *ReadResultsSuite) TestHandleNExceedsRootBlock() { // request by block - results := suite.getResults(map[string]any{ + results := suite.getResults(map[string]interface{}{ "block": "final", "n": float64(len(suite.allResults) + 1), }) @@ -259,7 +259,7 @@ func (suite *ReadResultsSuite) TestHandleNExceedsRootBlock() { require.ElementsMatch(suite.T(), results, suite.allResults) // request by result ID - results = suite.getResults(map[string]any{ + results = suite.getResults(map[string]interface{}{ "result": suite.finalResult.ID().String(), "n": float64(len(suite.allResults) + 1), }) diff --git a/admin/commands/storage/read_seals.go b/admin/commands/storage/read_seals.go index 6f9101652e9..f2b3b386049 100644 --- a/admin/commands/storage/read_seals.go +++ b/admin/commands/storage/read_seals.go @@ -22,7 +22,7 @@ const ( type readSealsRequest struct { requestType readSealsRequestType - value any + value interface{} numBlocksToQuery uint64 } @@ -45,7 +45,7 @@ type ReadSealsCommand struct { index storage.Index } -func (r *ReadSealsCommand) Handler(ctx context.Context, req *admin.CommandRequest) (any, error) { +func (r *ReadSealsCommand) Handler(ctx context.Context, req *admin.CommandRequest) (interface{}, error) { data := req.ValidatorData.(*readSealsRequest) if data.requestType == readSealsRequestByID { @@ -124,7 +124,7 @@ func (r *ReadSealsCommand) Handler(ctx context.Context, req *admin.CommandReques // Validator validates the request. // Returns admin.InvalidAdminReqError for invalid/malformed requests. func (r *ReadSealsCommand) Validator(req *admin.CommandRequest) error { - input, ok := req.Data.(map[string]any) + input, ok := req.Data.(map[string]interface{}) if !ok { return admin.NewInvalidAdminReqFormatError("expected map[string]any") } diff --git a/admin/commands/storage/read_seals_test.go b/admin/commands/storage/read_seals_test.go index 27694997437..5642c2a3e0f 100644 --- a/admin/commands/storage/read_seals_test.go +++ b/admin/commands/storage/read_seals_test.go @@ -1,6 +1,7 @@ package storage import ( + "context" "fmt" "testing" @@ -41,10 +42,11 @@ func TestReadSealsByID(t *testing.T) { command := NewReadSealsCommand(state, seals, index) - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() req := &admin.CommandRequest{ - Data: map[string]any{ + Data: map[string]interface{}{ "seal": seal.ID().String(), }, } diff --git a/admin/commands/storage/read_transactions.go b/admin/commands/storage/read_transactions.go index d570ed857c0..386c429d509 100644 --- a/admin/commands/storage/read_transactions.go +++ b/admin/commands/storage/read_transactions.go @@ -37,7 +37,7 @@ func NewGetTransactionsCommand(state protocol.State, payloads storage.Payloads, } } -func (c *GetTransactionsCommand) Handler(ctx context.Context, req *admin.CommandRequest) (any, error) { +func (c *GetTransactionsCommand) Handler(ctx context.Context, req *admin.CommandRequest) (interface{}, error) { data := req.ValidatorData.(*heightRangeReqData) limit := uint64(10001) diff --git a/admin/commands/storage/read_transactions_test.go b/admin/commands/storage/read_transactions_test.go index 7ca5648fa75..2a3917c48e9 100644 --- a/admin/commands/storage/read_transactions_test.go +++ b/admin/commands/storage/read_transactions_test.go @@ -13,7 +13,7 @@ import ( func TestReadTransactionsRangeTooWide(t *testing.T) { c := GetTransactionsCommand{} - data := map[string]any{ + data := map[string]interface{}{ "start-height": float64(1), "end-height": float64(10002), } @@ -32,7 +32,7 @@ func TestReadTransactionsRangeTooWide(t *testing.T) { func TestReadTransactionsRangeInvalid(t *testing.T) { c := GetTransactionsCommand{} - data := map[string]any{ + data := map[string]interface{}{ "start-height": float64(1001), "end-height": float64(1000), } @@ -46,7 +46,7 @@ func TestReadTransactionsRangeInvalid(t *testing.T) { func TestReadTransactionsMissingStart(t *testing.T) { c := GetTransactionsCommand{} - data := map[string]any{ + data := map[string]interface{}{ "start-height": float64(1001), } err := c.Validator(&admin.CommandRequest{ @@ -59,7 +59,7 @@ func TestReadTransactionsMissingStart(t *testing.T) { func TestReadTransactionsMissingEnd(t *testing.T) { c := GetTransactionsCommand{} - data := map[string]any{ + data := map[string]interface{}{ "end-height": float64(1001), } err := c.Validator(&admin.CommandRequest{ diff --git a/admin/commands/uploader/toggle_uploader.go b/admin/commands/uploader/toggle_uploader.go index 8ed97cc25d2..9cf5bf404b0 100644 --- a/admin/commands/uploader/toggle_uploader.go +++ b/admin/commands/uploader/toggle_uploader.go @@ -14,7 +14,7 @@ type ToggleUploaderCommand struct { uploadManager *uploader.Manager } -func (t *ToggleUploaderCommand) Handler(ctx context.Context, req *admin.CommandRequest) (any, error) { +func (t *ToggleUploaderCommand) Handler(ctx context.Context, req *admin.CommandRequest) (interface{}, error) { enabled := req.ValidatorData.(bool) t.uploadManager.SetEnabled(enabled) return "ok", nil diff --git a/cmd/Dockerfile b/cmd/Dockerfile index 0f3243844be..b0e5398fb36 100644 --- a/cmd/Dockerfile +++ b/cmd/Dockerfile @@ -3,7 +3,7 @@ #################################### ## (1) Setup the build environment -FROM golang:1.26-bookworm AS build-setup +FROM golang:1.25-bookworm AS build-setup RUN apt-get update RUN apt-get -y install zip apt-utils gcc-aarch64-linux-gnu @@ -85,7 +85,7 @@ RUN --mount=type=ssh \ RUN chmod a+x /app/app ## (4) Add the statically linked debug binary to a distroless image configured for debugging -FROM golang:1.26-bookworm as debug +FROM golang:1.25-bookworm as debug RUN go install github.com/go-delve/delve/cmd/dlv@latest diff --git a/cmd/access/node_builder/access_node_builder.go b/cmd/access/node_builder/access_node_builder.go index f62e966c9df..5c3a42fafaa 100644 --- a/cmd/access/node_builder/access_node_builder.go +++ b/cmd/access/node_builder/access_node_builder.go @@ -1938,8 +1938,8 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) { return nil }). Module("historical access node clients", func(node *cmd.NodeConfig) error { - addrs := strings.SplitSeq(builder.rpcConf.HistoricalAccessAddrs, ",") - for addr := range addrs { + addrs := strings.Split(builder.rpcConf.HistoricalAccessAddrs, ",") + for _, addr := range addrs { if strings.TrimSpace(addr) == "" { continue } diff --git a/cmd/bootstrap/cmd/keygen.go b/cmd/bootstrap/cmd/keygen.go index 8bcd17f9e78..ddb6435a9d5 100644 --- a/cmd/bootstrap/cmd/keygen.go +++ b/cmd/bootstrap/cmd/keygen.go @@ -48,7 +48,7 @@ var keygenCmd = &cobra.Command{ log.Info().Msg("") // write key files - writeJSONFile := func(relativePath string, val any) error { + writeJSONFile := func(relativePath string, val interface{}) error { return common.WriteJSON(relativePath, flagOutdir, val) } writeFile := func(relativePath string, data []byte) error { diff --git a/cmd/bootstrap/cmd/util.go b/cmd/bootstrap/cmd/util.go index db47b856715..ac0b7358491 100644 --- a/cmd/bootstrap/cmd/util.go +++ b/cmd/bootstrap/cmd/util.go @@ -9,7 +9,7 @@ import ( func GenerateRandomSeeds(n int, seedLen int) [][]byte { seeds := make([][]byte, 0, n) - for range n { + for i := 0; i < n; i++ { seeds = append(seeds, GenerateRandomSeed(seedLen)) } return seeds diff --git a/cmd/bootstrap/utils/key_generation.go b/cmd/bootstrap/utils/key_generation.go index 405a38d1178..658656b9222 100644 --- a/cmd/bootstrap/utils/key_generation.go +++ b/cmd/bootstrap/utils/key_generation.go @@ -77,7 +77,7 @@ func GeneratePublicNetworkingKey(seed []byte) (key crypto.PrivateKey, err error) hkdf := hkdf.New(func() gohash.Hash { return sha256.New() }, seed, nil, []byte("public network")) round_seed := make([]byte, len(seed)) max_iterations := 20 // 1/(2^20) failure chance - for range max_iterations { + for i := 0; i < max_iterations; i++ { if _, err = io.ReadFull(hkdf, round_seed); err != nil { // the hkdf Reader should not fail panic(err) @@ -128,7 +128,7 @@ func GenerateStakingKey(seed []byte) (crypto.PrivateKey, error) { func GenerateStakingKeys(n int, seeds [][]byte) ([]crypto.PrivateKey, error) { keys := make([]crypto.PrivateKey, 0, n) - for i := range n { + for i := 0; i < n; i++ { key, err := GenerateStakingKey(seeds[i]) if err != nil { return nil, err @@ -159,7 +159,7 @@ func GenerateKeys(algo crypto.SigningAlgorithm, n int, seeds [][]byte) ([]crypto // accepts the path for the file (relative to the bootstrapping root directory) // and the value to write. The function must marshal the value as JSON and write // the result to the given path. -type WriteJSONFileFunc func(relativePath string, value any) error +type WriteJSONFileFunc func(relativePath string, value interface{}) error // WriteFileFunc is the same as WriteJSONFileFunc, but it writes the bytes directly // rather than marshalling a structure to json. diff --git a/cmd/bootstrap/utils/key_generation_test.go b/cmd/bootstrap/utils/key_generation_test.go index 24e534f755c..a261c07238d 100644 --- a/cmd/bootstrap/utils/key_generation_test.go +++ b/cmd/bootstrap/utils/key_generation_test.go @@ -78,7 +78,7 @@ func TestWriteMachineAccountFiles(t *testing.T) { nodeIDLookup[addr.HexWithPrefix()] = node.NodeID } - write := func(path string, value any) error { + write := func(path string, value interface{}) error { actual, ok := value.(bootstrap.NodeMachineAccountInfo) require.True(t, ok) @@ -114,7 +114,7 @@ func TestWriteStakingNetworkingKeyFiles(t *testing.T) { } // check that the correct path and value are passed to the write function - write := func(path string, value any) error { + write := func(path string, value interface{}) error { actual, ok := value.(bootstrap.NodeInfoPriv) require.True(t, ok) diff --git a/cmd/execution_config.go b/cmd/execution_config.go index b094aa10d32..00ddf2d1bc6 100644 --- a/cmd/execution_config.go +++ b/cmd/execution_config.go @@ -181,8 +181,8 @@ func (exeConf *ExecutionConfig) ValidateFlags() error { } } if exeConf.executionDataAllowedPeers != "" { - ids := strings.SplitSeq(exeConf.executionDataAllowedPeers, ",") - for id := range ids { + ids := strings.Split(exeConf.executionDataAllowedPeers, ",") + for _, id := range ids { if _, err := flow.HexStringToIdentifier(id); err != nil { return fmt.Errorf("invalid node ID in execution-data-allowed-requesters %s: %w", id, err) } diff --git a/cmd/ledger/main.go b/cmd/ledger/main.go index c5fb0b5855a..0dd48ca6b98 100644 --- a/cmd/ledger/main.go +++ b/cmd/ledger/main.go @@ -156,8 +156,8 @@ func main() { // Create Unix socket listeners if socket path(s) are provided if *ledgerServiceSocket != "" { // Support multiple socket paths separated by comma - socketPathsList := strings.SplitSeq(*ledgerServiceSocket, ",") - for socketPath := range socketPathsList { + socketPathsList := strings.Split(*ledgerServiceSocket, ",") + for _, socketPath := range socketPathsList { socketPath = strings.TrimSpace(socketPath) if socketPath == "" { continue diff --git a/cmd/scaffold_test.go b/cmd/scaffold_test.go index 09be7290e1e..b63eb68f22a 100644 --- a/cmd/scaffold_test.go +++ b/cmd/scaffold_test.go @@ -595,7 +595,7 @@ func testErrorHandler(logger *testLog, expected error) component.OnError { // * Start order should be 3, 1, 2 // run test 10 times to ensure order is consistent func TestDependableComponentWaitForDependencies(t *testing.T) { - for range 10 { + for i := 0; i < 10; i++ { testDependableComponentWaitForDependencies(t) } } diff --git a/cmd/testUtil.go b/cmd/testUtil.go index 0258ce2cd21..dca1cef021c 100644 --- a/cmd/testUtil.go +++ b/cmd/testUtil.go @@ -13,7 +13,7 @@ type testLog struct { } // handle concurrent logging -func (l *testLog) Logf(msg string, args ...any) { +func (l *testLog) Logf(msg string, args ...interface{}) { l.Log(fmt.Sprintf(msg, args...)) } diff --git a/cmd/util/cmd/atree_inlined_status/cmd.go b/cmd/util/cmd/atree_inlined_status/cmd.go index 42d970fa069..f55dc0be107 100644 --- a/cmd/util/cmd/atree_inlined_status/cmd.go +++ b/cmd/util/cmd/atree_inlined_status/cmd.go @@ -260,7 +260,10 @@ func checkAtreeInlinedStatus(payloads []*ledger.Payload, nWorkers int) ( break } - endIndex := min(payloadStartIndex+numOfPayloadPerJob, len(payloads)) + endIndex := payloadStartIndex + numOfPayloadPerJob + if endIndex > len(payloads) { + endIndex = len(payloads) + } jobs <- job{payloads: payloads[payloadStartIndex:endIndex]} diff --git a/cmd/util/cmd/check-storage/evm_account_storage_health_test.go b/cmd/util/cmd/check-storage/evm_account_storage_health_test.go index a72b55888ce..c705cfa4edc 100644 --- a/cmd/util/cmd/check-storage/evm_account_storage_health_test.go +++ b/cmd/util/cmd/check-storage/evm_account_storage_health_test.go @@ -131,7 +131,7 @@ func createCadenceStorage(t *testing.T, ledger atree.Ledger, address common.Addr storageDomain := storage.GetDomainStorageMap(inter, address, domain, true) // Create large domain map so there are more than one atree registers under the hood. - for i := range 100 { + for i := 0; i < 100; i++ { domainStr := domain.Identifier() key := interpreter.StringStorageMapKey(domainStr + "_key_" + strconv.Itoa(i)) value := interpreter.NewUnmeteredStringValue(domainStr + "_value_" + strconv.Itoa(i)) diff --git a/cmd/util/cmd/common/clusters.go b/cmd/util/cmd/common/clusters.go index 76bda8dd434..c38b0c3c880 100644 --- a/cmd/util/cmd/common/clusters.go +++ b/cmd/util/cmd/common/clusters.go @@ -94,7 +94,7 @@ func ConstructClusterAssignment(log zerolog.Logger, partnerNodes, internalNodes // check the 2/3 constraint: for every cluster `i`, constraint[i] must be strictly positive // for a QC to be created without external votes canConstructAllClusterQCs := true - for i := range numCollectionClusters { + for i := 0; i < numCollectionClusters; i++ { if constraint[i] <= 0 { canConstructAllClusterQCs = false } diff --git a/cmd/util/cmd/common/print.go b/cmd/util/cmd/common/print.go index d2e301dfede..a01baf5d181 100644 --- a/cmd/util/cmd/common/print.go +++ b/cmd/util/cmd/common/print.go @@ -16,7 +16,7 @@ func PrettyPrintEntity(entity flow.Entity) { } // PrettyPrint an interface -func PrettyPrint(entity any) { +func PrettyPrint(entity interface{}) { bytes, err := json.MarshalIndent(entity, "", " ") if err != nil { log.Fatal().Err(err).Msg("could not marshal interface into json") diff --git a/cmd/util/cmd/common/utils.go b/cmd/util/cmd/common/utils.go index 3a02a34af5d..f5b9570071e 100644 --- a/cmd/util/cmd/common/utils.go +++ b/cmd/util/cmd/common/utils.go @@ -52,7 +52,7 @@ func PathExists(path string) (bool, error) { return false, err } -func ReadJSON(path string, target any) error { +func ReadJSON(path string, target interface{}) error { dat, err := io.ReadFile(path) if err != nil { return fmt.Errorf("cannot read json: %w", err) @@ -64,7 +64,7 @@ func ReadJSON(path string, target any) error { return nil } -func WriteJSON(path string, out string, data any) error { +func WriteJSON(path string, out string, data interface{}) error { bz, err := json.MarshalIndent(data, "", " ") if err != nil { return fmt.Errorf("cannot marshal json: %w", err) diff --git a/cmd/util/cmd/epochs/cmd/recover_test.go b/cmd/util/cmd/epochs/cmd/recover_test.go index 43764e7fb5a..8cc552a81e3 100644 --- a/cmd/util/cmd/epochs/cmd/recover_test.go +++ b/cmd/util/cmd/epochs/cmd/recover_test.go @@ -68,7 +68,7 @@ func TestRecoverEpochHappyPath(t *testing.T) { generateRecoverEpochTxArgs(snapshotFn)(generateRecoverEpochTxArgsCmd, nil) // read output from stdout - var outputTxArgs []any + var outputTxArgs []interface{} err = json.NewDecoder(stdout).Decode(&outputTxArgs) require.NoError(t, err) diff --git a/cmd/util/cmd/epochs/cmd/reset_test.go b/cmd/util/cmd/epochs/cmd/reset_test.go index 588c8f05337..30e7d0178f2 100644 --- a/cmd/util/cmd/epochs/cmd/reset_test.go +++ b/cmd/util/cmd/epochs/cmd/reset_test.go @@ -41,7 +41,7 @@ func TestReset_LocalSnapshot(t *testing.T) { resetRun(resetCmd, nil) // read output from stdout - var outputTxArgs []any + var outputTxArgs []interface{} err = json.NewDecoder(stdout).Decode(&outputTxArgs) require.NoError(t, err) @@ -87,7 +87,7 @@ func TestReset_BucketSnapshot(t *testing.T) { resetRun(resetCmd, nil) // read output from stdout - var outputTxArgs []any + var outputTxArgs []interface{} err := json.NewDecoder(stdout).Decode(&outputTxArgs) require.NoError(t, err) @@ -109,7 +109,7 @@ func TestReset_BucketSnapshot(t *testing.T) { resetRun(resetCmd, nil) // read output from stdout - var outputTxArgs []any + var outputTxArgs []interface{} err := json.NewDecoder(stdout).Decode(&outputTxArgs) require.NoError(t, err) @@ -143,7 +143,7 @@ func writeRootSnapshot(bootDir string, snapshot *inmem.Snapshot) error { // TODO: unify methods from all commands // TODO: move this to common module -func writeJSON(path string, data any) error { +func writeJSON(path string, data interface{}) error { bz, err := json.MarshalIndent(data, "", " ") if err != nil { return err diff --git a/cmd/util/cmd/execution-state-extract/execution_state_extract_test.go b/cmd/util/cmd/execution-state-extract/execution_state_extract_test.go index d653c01ee3b..eeb7412ee19 100644 --- a/cmd/util/cmd/execution-state-extract/execution_state_extract_test.go +++ b/cmd/util/cmd/execution-state-extract/execution_state_extract_test.go @@ -126,7 +126,7 @@ func TestExtractExecutionState(t *testing.T) { commitsByBlocks := make(map[flow.Identifier]ledger.State) blocksInOrder := make([]flow.Identifier, size) - for i := range size { + for i := 0; i < size; i++ { keys, values := getSampleKeyValues(i) update, err := ledger.NewUpdate(stateCommitment, keys, values) @@ -223,7 +223,7 @@ func TestExtractPayloadsFromExecutionState(t *testing.T) { // Save generated data after updates keysValues := make(map[string]keyPair) - for i := range size { + for i := 0; i < size; i++ { keys, values := getSampleKeyValues(i) update, err := ledger.NewUpdate(stateCommitment, keys, values) @@ -303,7 +303,7 @@ func TestExtractPayloadsFromExecutionState(t *testing.T) { // Save generated data after updates keysValues := make(map[string]keyPair) - for i := range size { + for i := 0; i < size; i++ { keys, values := getSampleKeyValues(i) update, err := ledger.NewUpdate(stateCommitment, keys, values) @@ -414,7 +414,7 @@ func TestExtractStateFromPayloads(t *testing.T) { keysValues := make(map[string]keyPair) var payloads []*ledger.Payload - for i := range size { + for i := 0; i < size; i++ { keys, values := getSampleKeyValues(i) for j, key := range keys { @@ -485,7 +485,7 @@ func TestExtractStateFromPayloads(t *testing.T) { keysValues := make(map[string]keyPair) var payloads []*ledger.Payload - for i := range size { + for i := 0; i < size; i++ { keys, values := getSampleKeyValues(i) for j, key := range keys { @@ -552,7 +552,7 @@ func TestExtractStateFromPayloads(t *testing.T) { keysValues := make(map[string]keyPair) var payloads []*ledger.Payload - for i := range size { + for i := 0; i < size; i++ { keys, values := getSampleKeyValues(i) for j, key := range keys { @@ -629,7 +629,7 @@ func getSampleKeyValues(i int) ([]ledger.Key, []ledger.Value) { default: keys := make([]ledger.Key, 0) values := make([]ledger.Value, 0) - for range 10 { + for j := 0; j < 10; j++ { // address := make([]byte, 32) address := make([]byte, 8) _, err := rand.Read(address) diff --git a/cmd/util/cmd/extract-payloads-by-address/extract_payloads_test.go b/cmd/util/cmd/extract-payloads-by-address/extract_payloads_test.go index 1d0b0573aaa..697d983d1f9 100644 --- a/cmd/util/cmd/extract-payloads-by-address/extract_payloads_test.go +++ b/cmd/util/cmd/extract-payloads-by-address/extract_payloads_test.go @@ -36,7 +36,7 @@ func TestExtractPayloads(t *testing.T) { keysValues := make(map[string]keyPair) var payloads []*ledger.Payload - for i := range size { + for i := 0; i < size; i++ { keys, values := getSampleKeyValues(i) for j, key := range keys { @@ -131,7 +131,7 @@ func TestExtractPayloads(t *testing.T) { keysValues := make(map[string]keyPair) var payloads []*ledger.Payload - for i := range size { + for i := 0; i < size; i++ { keys, values := getSampleKeyValues(i) for j, key := range keys { @@ -198,7 +198,7 @@ func getSampleKeyValues(i int) ([]ledger.Key, []ledger.Value) { default: keys := make([]ledger.Key, 0) values := make([]ledger.Value, 0) - for range 10 { + for j := 0; j < 10; j++ { // address := make([]byte, 32) address := make([]byte, 8) _, err := rand.Read(address) diff --git a/cmd/util/cmd/generate-authorization-fixes/cmd.go b/cmd/util/cmd/generate-authorization-fixes/cmd.go index e8da5a38849..038eaa6ea1d 100644 --- a/cmd/util/cmd/generate-authorization-fixes/cmd.go +++ b/cmd/util/cmd/generate-authorization-fixes/cmd.go @@ -99,7 +99,7 @@ func run(*cobra.Command, []string) { var addressFilter map[common.Address]struct{} if len(flagAddresses) > 0 { - for hexAddr := range strings.SplitSeq(flagAddresses, ",") { + for _, hexAddr := range strings.Split(flagAddresses, ",") { hexAddr = strings.TrimSpace(hexAddr) diff --git a/cmd/util/cmd/generate-authorization-fixes/cmd_test.go b/cmd/util/cmd/generate-authorization-fixes/cmd_test.go index b9a20e1b677..6d1bf83e1d6 100644 --- a/cmd/util/cmd/generate-authorization-fixes/cmd_test.go +++ b/cmd/util/cmd/generate-authorization-fixes/cmd_test.go @@ -64,7 +64,7 @@ type testReportWriter struct { entries []any } -func (t *testReportWriter) Write(entry any) { +func (t *testReportWriter) Write(entry interface{}) { t.entries = append(t.entries, entry) } @@ -142,7 +142,7 @@ func TestGenerateAuthorizationFixes(t *testing.T) { require.NoError(t, err) setupTx, err := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` import Test from %s transaction { @@ -181,7 +181,7 @@ func TestGenerateAuthorizationFixes(t *testing.T) { } `, address.HexWithPrefix(), - )). + ))). AddAuthorizer(address). Build() require.NoError(t, err) diff --git a/cmd/util/cmd/read-badger/cmd/stats.go b/cmd/util/cmd/read-badger/cmd/stats.go index ccd5c483896..1dc03058ebb 100644 --- a/cmd/util/cmd/read-badger/cmd/stats.go +++ b/cmd/util/cmd/read-badger/cmd/stats.go @@ -22,7 +22,10 @@ var statsCmd = &cobra.Command{ RunE: func(cmd *cobra.Command, args []string) error { return common.WithStorage(flagDatadir, func(sdb storage.DB) error { - numWorkers := min(runtime.NumCPU(), 256) + numWorkers := runtime.NumCPU() + if numWorkers > 256 { + numWorkers = 256 + } log.Info().Msgf("getting stats with %v workers", numWorkers) stats, err := operation.SummarizeKeysByFirstByteConcurrent(log.Logger, sdb.Reader(), numWorkers) diff --git a/cmd/util/ledger/migrations/account_based_migration.go b/cmd/util/ledger/migrations/account_based_migration.go index 005370f7f23..b6b4f15b369 100644 --- a/cmd/util/ledger/migrations/account_based_migration.go +++ b/cmd/util/ledger/migrations/account_based_migration.go @@ -156,7 +156,7 @@ func MigrateAccountsConcurrently( workersLeft := int64(nWorker) - for range nWorker { + for workerIndex := 0; workerIndex < nWorker; workerIndex++ { g.Go(func() error { defer func() { if syncAtomic.AddInt64(&workersLeft, -1) == 0 { diff --git a/cmd/util/ledger/migrations/cadence_value_diff_test.go b/cmd/util/ledger/migrations/cadence_value_diff_test.go index ab5e746feef..4f9f73b9d85 100644 --- a/cmd/util/ledger/migrations/cadence_value_diff_test.go +++ b/cmd/util/ledger/migrations/cadence_value_diff_test.go @@ -822,7 +822,7 @@ func createTestRegisters(t *testing.T, address common.Address, domain common.Sto // Add Cadence DictionaryValue const dictCount = 10 dictValues := make([]interpreter.Value, 0, dictCount*2) - for i := range dictCount { + for i := 0; i < dictCount; i++ { k := interpreter.NewUnmeteredUInt64Value(uint64(i)) v := interpreter.NewUnmeteredStringValue(fmt.Sprintf("value %d", i)) dictValues = append(dictValues, k, v) diff --git a/cmd/util/ledger/migrations/deploy_migration_test.go b/cmd/util/ledger/migrations/deploy_migration_test.go index cc8d91f5bbe..5465aaed672 100644 --- a/cmd/util/ledger/migrations/deploy_migration_test.go +++ b/cmd/util/ledger/migrations/deploy_migration_test.go @@ -72,7 +72,7 @@ func TestDeploy(t *testing.T) { chainID, Contract{ Name: "NewContract", - Code: fmt.Appendf(nil, + Code: []byte(fmt.Sprintf( ` import FungibleToken from %s @@ -86,7 +86,7 @@ func TestDeploy(t *testing.T) { } `, fungibleTokenAddress.HexWithPrefix(), - ), + )), }, targetAddress, map[flow.Address]struct{}{ @@ -127,7 +127,7 @@ func TestDeploy(t *testing.T) { require.NoError(t, err) txBody, err := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, + SetScript([]byte(fmt.Sprintf( ` import NewContract from %s @@ -138,7 +138,7 @@ func TestDeploy(t *testing.T) { } `, targetAddress.HexWithPrefix(), - )). + ))). SetPayer(serviceAccountAddress). Build() require.NoError(t, err) diff --git a/cmd/util/ledger/migrations/filter_unreferenced_slabs_migration_test.go b/cmd/util/ledger/migrations/filter_unreferenced_slabs_migration_test.go index ecfcb625545..d8747008b76 100644 --- a/cmd/util/ledger/migrations/filter_unreferenced_slabs_migration_test.go +++ b/cmd/util/ledger/migrations/filter_unreferenced_slabs_migration_test.go @@ -136,7 +136,7 @@ func TestFilterUnreferencedSlabs(t *testing.T) { // Ensure the array is large enough to be stored in a separate slab arrayCount := 100 arrayValues := make([]interpreter.Value, arrayCount) - for i := range arrayCount { + for i := 0; i < arrayCount; i++ { arrayValues[i] = interpreter.NewUnmeteredIntValueFromInt64(int64(i)) } diff --git a/cmd/util/ledger/reporters/account_reporter.go b/cmd/util/ledger/reporters/account_reporter.go index e2c87679136..c92eb1a52ce 100644 --- a/cmd/util/ledger/reporters/account_reporter.go +++ b/cmd/util/ledger/reporters/account_reporter.go @@ -173,7 +173,7 @@ func newAccountDataProcessor( bp.rwa = rwa bp.rwc = rwc bp.rwm = rwm - bp.balanceScript = fmt.Appendf(nil, ` + bp.balanceScript = []byte(fmt.Sprintf(` import FungibleToken from 0x%s import FlowToken from 0x%s access(all) fun main(account: Address): UFix64 { @@ -182,9 +182,9 @@ func newAccountDataProcessor( ?? panic("Could not borrow Balance reference to the Vault") return vaultRef.balance } - `, sc.FungibleToken.Address.Hex(), sc.FlowToken.Address.Hex()) + `, sc.FungibleToken.Address.Hex(), sc.FlowToken.Address.Hex())) - bp.fusdScript = fmt.Appendf(nil, ` + bp.fusdScript = []byte(fmt.Sprintf(` import FungibleToken from 0x%s import FUSD from 0x%s access(all) fun main(address: Address): UFix64 { @@ -193,7 +193,7 @@ func newAccountDataProcessor( ?? panic("Could not borrow Balance reference to the Vault") return vaultRef.balance } - `, sc.FungibleToken.Address.Hex(), "3c5959b568896393") + `, sc.FungibleToken.Address.Hex(), "3c5959b568896393")) bp.momentsScript = []byte(` import TopShot from 0x0b2a3299cc857e29 diff --git a/cmd/util/ledger/reporters/fungible_token_tracker_test.go b/cmd/util/ledger/reporters/fungible_token_tracker_test.go index 9a51a1c857b..8183216dbff 100644 --- a/cmd/util/ledger/reporters/fungible_token_tracker_test.go +++ b/cmd/util/ledger/reporters/fungible_token_tracker_test.go @@ -94,13 +94,13 @@ func TestFungibleTokenTracker(t *testing.T) { } }`, sc.FungibleToken.Address.Hex()) - deployingTestContractScript := fmt.Appendf(nil, ` + deployingTestContractScript := []byte(fmt.Sprintf(` transaction { prepare(signer: auth(AddContract) &Account) { signer.contracts.add(name: "%s", code: "%s".decodeHex()) } } - `, "WrappedToken", hex.EncodeToString([]byte(testContract))) + `, "WrappedToken", hex.EncodeToString([]byte(testContract)))) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(deployingTestContractScript). @@ -117,7 +117,7 @@ func TestFungibleTokenTracker(t *testing.T) { err = view.Merge(snapshot) require.NoError(t, err) - wrapTokenScript := fmt.Appendf(nil, + wrapTokenScript := []byte(fmt.Sprintf( ` import FungibleToken from 0x%s import FlowToken from 0x%s @@ -136,7 +136,7 @@ func TestFungibleTokenTracker(t *testing.T) { sc.FungibleToken.Address.Hex(), sc.FlowToken.Address.Hex(), sc.FlowServiceAccount.Address.Hex(), - ) + )) txBody, err = flow.NewTransactionBodyBuilder(). SetScript(wrapTokenScript). diff --git a/cmd/util/ledger/reporters/reporter_output_test.go b/cmd/util/ledger/reporters/reporter_output_test.go index 8f8da952314..a443f770f13 100644 --- a/cmd/util/ledger/reporters/reporter_output_test.go +++ b/cmd/util/ledger/reporters/reporter_output_test.go @@ -59,10 +59,12 @@ func TestReportFileWriterJSONArray(t *testing.T) { rw := reporters.NewReportFileWriter(filename, log, reporters.ReportFormatJSONArray) wg := &sync.WaitGroup{} - for range 3 { - wg.Go(func() { + for i := 0; i < 3; i++ { + wg.Add(1) + go func() { rw.Write(testData{TestField: "something"}) - }) + wg.Done() + }() } wg.Wait() @@ -124,10 +126,12 @@ func TestReportFileWriterJSONL(t *testing.T) { rw := reporters.NewReportFileWriter(filename, log, reporters.ReportFormatJSONL) wg := &sync.WaitGroup{} - for range 3 { - wg.Go(func() { + for i := 0; i < 3; i++ { + wg.Add(1) + go func() { rw.Write(testData{TestField: "something"}) - }) + wg.Done() + }() } wg.Wait() @@ -186,10 +190,12 @@ func TestReportFileWriterCSV(t *testing.T) { rw := reporters.NewReportFileWriter(filename, log, reporters.ReportFormatCSV) wg := &sync.WaitGroup{} - for range 3 { - wg.Go(func() { + for i := 0; i < 3; i++ { + wg.Add(1) + go func() { rw.Write([]string{"something"}) - }) + wg.Done() + }() } wg.Wait() diff --git a/cmd/util/ledger/util/payload_file_test.go b/cmd/util/ledger/util/payload_file_test.go index 246db97f9f4..4040c8707e9 100644 --- a/cmd/util/ledger/util/payload_file_test.go +++ b/cmd/util/ledger/util/payload_file_test.go @@ -35,7 +35,7 @@ func TestPayloadFile(t *testing.T) { keysValues := make(map[string]keyPair) var payloads []*ledger.Payload - for i := range size { + for i := 0; i < size; i++ { keys, values := getSampleKeyValues(i) for j, key := range keys { @@ -88,7 +88,7 @@ func TestPayloadFile(t *testing.T) { keysValues := make(map[string]keyPair) var payloads []*ledger.Payload - for i := range size { + for i := 0; i < size; i++ { keys, values := getSampleKeyValues(i) for j, key := range keys { @@ -143,7 +143,7 @@ func TestPayloadFile(t *testing.T) { var payloads []*ledger.Payload var globalRegisterCount int - for i := range size { + for i := 0; i < size; i++ { keys, values := getSampleKeyValues(i) for j, key := range keys { @@ -249,7 +249,7 @@ func TestPayloadFile(t *testing.T) { var globalRegisterCount int - for i := range size { + for i := 0; i < size; i++ { keys, values := getSampleKeyValues(i) for j, key := range keys { @@ -312,7 +312,7 @@ func getSampleKeyValues(i int) ([]ledger.Key, []ledger.Value) { default: keys := make([]ledger.Key, 0) values := make([]ledger.Value, 0) - for range 10 { + for j := 0; j < 10; j++ { // address := make([]byte, 32) address := make([]byte, 8) _, err := rand.Read(address) diff --git a/cmd/util/ledger/util/payload_grouping.go b/cmd/util/ledger/util/payload_grouping.go index d16e0602e59..cd46cbd9f8f 100644 --- a/cmd/util/ledger/util/payload_grouping.go +++ b/cmd/util/ledger/util/payload_grouping.go @@ -153,7 +153,10 @@ func (s sortablePayloads) FindNextKeyIndexUntil(i int, upperBound int) int { step *= 2 } - high := min(low+step, upperBound) + high := low + step + if high > upperBound { + high = upperBound + } for low < high { mid := (low + high) / 2 diff --git a/cmd/util/ledger/util/payload_grouping_test.go b/cmd/util/ledger/util/payload_grouping_test.go index 41c38a01ab0..13cd80af816 100644 --- a/cmd/util/ledger/util/payload_grouping_test.go +++ b/cmd/util/ledger/util/payload_grouping_test.go @@ -32,7 +32,7 @@ func TestGroupPayloadsByAccountForDataRace(t *testing.T) { const accountSize = 4 var payloads []*ledger.Payload - for range accountSize { + for i := 0; i < accountSize; i++ { payloads = append(payloads, generateRandomPayloadsWithAddress(generateRandomAddress(), 100_000)...) } @@ -122,11 +122,14 @@ func generateRandomPayloads(n int) []*ledger.Payload { for i := 0; i < n; { - registersForAccount := min(minPayloadsPerAccount+int(rand2.ExpFloat64()*(meanPayloadsPerAccount-minPayloadsPerAccount)), n-i) + registersForAccount := minPayloadsPerAccount + int(rand2.ExpFloat64()*(meanPayloadsPerAccount-minPayloadsPerAccount)) + if registersForAccount > n-i { + registersForAccount = n - i + } i += registersForAccount accountKey := generateRandomAccountKey() - for range registersForAccount { + for j := 0; j < registersForAccount; j++ { payloads = append(payloads, ledger.NewPayload( accountKey, @@ -146,14 +149,17 @@ func generateRandomPayloadsWithAddress(address string, n int) []*ledger.Payload for i := 0; i < n; { - registersForAccount := min(minPayloadsPerAccount+int(rand2.ExpFloat64()*(meanPayloadsPerAccount-minPayloadsPerAccount)), n-i) + registersForAccount := minPayloadsPerAccount + int(rand2.ExpFloat64()*(meanPayloadsPerAccount-minPayloadsPerAccount)) + if registersForAccount > n-i { + registersForAccount = n - i + } i += registersForAccount accountKey := convert.RegisterIDToLedgerKey(flow.RegisterID{ Owner: address, Key: generateRandomString(10), }) - for range registersForAccount { + for j := 0; j < registersForAccount; j++ { payloads = append(payloads, ledger.NewPayload( accountKey, diff --git a/config/config_test.go b/config/config_test.go index 697a66e482e..c52d7dac9bd 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -158,16 +158,16 @@ func testFlagSet(c *FlowConfig) *pflag.FlagSet { // - prefix: the prefix to prepend to the keys. // Returns: // - the list of keys extracted from the YAML data. -func getAllYAMLKeys(data any, prefix string) []string { +func getAllYAMLKeys(data interface{}, prefix string) []string { var keys []string switch v := data.(type) { - case map[any]any: + case map[interface{}]interface{}: for key, value := range v { fullKey := prefix + "-" + key.(string) keys = append(keys, getAllYAMLKeys(value, fullKey)...) } - case []any: + case []interface{}: for i, value := range v { fullKey := prefix + "-" + strings.ToLower(strings.ReplaceAll(reflect.TypeOf(value).Name(), "_", "-")) keys = append(keys, getAllYAMLKeys(value, fullKey+string(rune('a'+i)))...) @@ -184,14 +184,14 @@ func allResourceManagerFlagNames(t *testing.T) []string { yamlFile, err := os.ReadFile("default-config.yml") require.NoError(t, err, "failed to read YAML file") - var config map[string]any + var config map[string]interface{} err = yaml.Unmarshal(yamlFile, &config) require.NoError(t, err, "failed to unmarshal YAML file") - networkConfig, exists := config["network-config"].(map[any]any) + networkConfig, exists := config["network-config"].(map[interface{}]interface{}) require.True(t, exists, "the key 'network-config' does not exist in the YAML file") - resourceManagerConfig, exists := networkConfig["libp2p-resource-manager"].(map[any]any) + resourceManagerConfig, exists := networkConfig["libp2p-resource-manager"].(map[interface{}]interface{}) require.True(t, exists, "the key 'libp2p-resource-manager' does not exist in the YAML file") return getAllYAMLKeys(resourceManagerConfig, "libp2p-resource-manager") diff --git a/consensus/follower_test.go b/consensus/follower_test.go index 870644c57be..104a593331e 100644 --- a/consensus/follower_test.go +++ b/consensus/follower_test.go @@ -306,12 +306,12 @@ func (s *HotStuffFollowerSuite) TestOutOfOrderBlocks() { } // blockWithID returns a testify `argumentMatcher` that only accepts blocks with the given ID -func blockWithID(expectedBlockID flow.Identifier) any { +func blockWithID(expectedBlockID flow.Identifier) interface{} { return mock.MatchedBy(func(block *model.Block) bool { return expectedBlockID == block.BlockID }) } // blockID returns a testify `argumentMatcher` that only accepts the given ID -func blockID(expectedBlockID flow.Identifier) any { +func blockID(expectedBlockID flow.Identifier) interface{} { return mock.MatchedBy(func(blockID flow.Identifier) bool { return expectedBlockID == blockID }) } diff --git a/consensus/hotstuff/committees/consensus_committee_test.go b/consensus/hotstuff/committees/consensus_committee_test.go index 3df06139131..1856388abcf 100644 --- a/consensus/hotstuff/committees/consensus_committee_test.go +++ b/consensus/hotstuff/committees/consensus_committee_test.go @@ -282,7 +282,7 @@ func (suite *ConsensusSuite) TestProtocolEvents_EpochExtendedMultiple() { suite.AssertKnownViews(expectedKnownViews...) // Add several extensions in series - for range 10 { + for i := 0; i < 10; i++ { finalView := curEpoch.FinalView() extension := flow.EpochExtension{ FirstView: finalView + 1, @@ -717,7 +717,7 @@ func TestRemoveOldEpochs(t *testing.T) { } // check we have the correct epochs stored - for i := range uint64(3) { + for i := uint64(0); i < 3; i++ { counter := currentEpochCounter - i if counter < firstEpochCounter { break diff --git a/consensus/hotstuff/committees/leader/leader_selection.go b/consensus/hotstuff/committees/leader/leader_selection.go index ff1ca185a2d..e820d1f617a 100644 --- a/consensus/hotstuff/committees/leader/leader_selection.go +++ b/consensus/hotstuff/committees/leader/leader_selection.go @@ -155,7 +155,7 @@ func weightedRandomSelection( } leaders := make([]uint16, 0, count) - for range count { + for i := 0; i < count; i++ { // pick a random number from 0 (inclusive) to cumsum (exclusive). Or [0, cumsum) randomness := rng.UintN(cumsum) diff --git a/consensus/hotstuff/committees/leader/leader_selection_test.go b/consensus/hotstuff/committees/leader/leader_selection_test.go index 38d43bce65c..c391ea756a6 100644 --- a/consensus/hotstuff/committees/leader/leader_selection_test.go +++ b/consensus/hotstuff/committees/leader/leader_selection_test.go @@ -27,7 +27,7 @@ func TestSingleConsensusNode(t *testing.T) { rng := getPRG(t, someSeed) selection, err := ComputeLeaderSelection(0, rng, 10, flow.IdentitySkeletonList{&identity.IdentitySkeleton}) require.NoError(t, err) - for i := range uint64(10) { + for i := uint64(0); i < 10; i++ { leaderID, err := selection.LeaderForView(i) require.NoError(t, err) require.Equal(t, identity.NodeID, leaderID) @@ -42,14 +42,14 @@ func TestBsearchVSsortSearch(t *testing.T) { var sum2 int sums := make([]uint64, 0) sums2 := make([]int, 0) - for i := range weights { + for i := 0; i < len(weights); i++ { sum += weights[i] sum2 += weights2[i] sums = append(sums, sum) sums2 = append(sums2, sum2) } sel := make([]int, 0, 10) - for i := range 10 { + for i := 0; i < 10; i++ { index := binarySearchStrictlyBigger(uint64(i), sums) sel = append(sel, index) } @@ -68,12 +68,12 @@ func TestBsearch(t *testing.T) { weights := []uint64{1, 2, 3, 4} var sum uint64 sums := make([]uint64, 0) - for i := range weights { + for i := 0; i < len(weights); i++ { sum += weights[i] sums = append(sums, sum) } sel := make([]int, 0, 10) - for i := range 10 { + for i := 0; i < 10; i++ { index := binarySearchStrictlyBigger(uint64(i), sums) sel = append(sel, index) } @@ -86,14 +86,14 @@ func TestBsearchWithNormalSearch(t *testing.T) { count := 100 sums := make([]uint64, 0, count) sum := 0 - for i := range count { + for i := 0; i < count; i++ { sum += i sums = append(sums, uint64(sum)) } var value uint64 total := sums[len(sums)-1] - for value = range total { + for value = 0; value < total; value++ { expected, err := bruteSearch(value, sums) require.NoError(t, err) @@ -140,7 +140,7 @@ func TestDeterministic(t *testing.T) { leaders2, err := ComputeLeaderSelection(0, rng, N_VIEWS, identities) require.NoError(t, err) - for i := range N_VIEWS { + for i := 0; i < N_VIEWS; i++ { l1, err := leaders1.LeaderForView(uint64(i)) require.NoError(t, err) @@ -243,7 +243,7 @@ func TestDifferentSeedWillProduceDifferentSelection(t *testing.T) { require.NoError(t, err) diff := 0 - for view := range N_VIEWS { + for view := 0; view < N_VIEWS; view++ { l1, err := leaders1.LeaderForView(uint64(view)) require.NoError(t, err) @@ -276,7 +276,7 @@ func TestLeaderSelectionAreWeighted(t *testing.T) { require.NoError(t, err) selected := make(map[flow.Identifier]uint64) - for view := range N_VIEWS { + for view := 0; view < N_VIEWS; view++ { nodeID, err := leaders.LeaderForView(uint64(view)) require.NoError(t, err) @@ -308,7 +308,7 @@ func BenchmarkLeaderSelection(b *testing.B) { const N_NODES = 20 identities := make(flow.IdentityList, 0, N_NODES) - for i := range N_NODES { + for i := 0; i < N_NODES; i++ { identities = append(identities, unittest.IdentityFixture(unittest.WithInitialWeight(uint64(i)))) } skeletonIdentities := identities.ToSkeleton() @@ -353,7 +353,7 @@ func TestZeroWeightNodeWillNotBeSelected(t *testing.T) { selectionFromWeightful, err := ComputeLeaderSelection(0, rng_copy, N_VIEWS, weightful) require.NoError(t, err) - for i := range N_VIEWS { + for i := 0; i < N_VIEWS; i++ { nodeIDFromAll, err := selectionFromAll.LeaderForView(uint64(i)) require.NoError(t, err) @@ -389,7 +389,7 @@ func TestZeroWeightNodeWillNotBeSelected(t *testing.T) { selectionFromWeightful, err := ComputeLeaderSelection(0, rng_copy, count, votingConsensusNodes) require.NoError(t, err) - for i := range count { + for i := 0; i < count; i++ { nodeIDFromAll, err := selectionFromAll.LeaderForView(uint64(i)) require.NoError(t, err) @@ -413,7 +413,7 @@ func TestZeroWeightNodeWillNotBeSelected(t *testing.T) { selections, err := ComputeLeaderSelection(0, toolRng, 1000, identities) require.NoError(t, err) - for i := range 1000 { + for i := 0; i < 1000; i++ { nodeID, err := selections.LeaderForView(uint64(i)) require.NoError(t, err) require.Equal(t, onlyNodeWithWeight.NodeID, nodeID) diff --git a/consensus/hotstuff/cruisectl/block_time_controller.go b/consensus/hotstuff/cruisectl/block_time_controller.go index cdd37e5d51a..df28a562f7b 100644 --- a/consensus/hotstuff/cruisectl/block_time_controller.go +++ b/consensus/hotstuff/cruisectl/block_time_controller.go @@ -234,17 +234,17 @@ func (ctl *BlockTimeController) getProposalTiming() ProposalTiming { func (ctl *BlockTimeController) TargetPublicationTime(proposalView uint64, timeViewEntered time.Time, parentBlockId flow.Identifier) time.Time { targetPublicationTime := ctl.getProposalTiming().TargetPublicationTime(proposalView, timeViewEntered, parentBlockId) - publicationDelay := max( - // targetPublicationTime should already account for the controller's upper limit of authority (longest view time - // the controller is allowed to select). However, targetPublicationTime is allowed to be in the past, if the - // controller want to signal that the proposal should be published asap. We could hypothetically update a past - // targetPublicationTime to 'now' at every level in the code. However, this time stamp would move into the past - // immediately, and we would have to update the targetPublicationTime over and over. Instead, we just allow values - // in the past, thereby making repeated corrections unnecessary. In this model, the code _interpreting_ the value - // needs to apply the convention a negative publicationDelay essentially means "no delay". - time.Until(targetPublicationTime), - // Controller can only delay publication of proposal. Hence, the delay is lower-bounded by zero. - 0) + publicationDelay := time.Until(targetPublicationTime) + // targetPublicationTime should already account for the controller's upper limit of authority (longest view time + // the controller is allowed to select). However, targetPublicationTime is allowed to be in the past, if the + // controller want to signal that the proposal should be published asap. We could hypothetically update a past + // targetPublicationTime to 'now' at every level in the code. However, this time stamp would move into the past + // immediately, and we would have to update the targetPublicationTime over and over. Instead, we just allow values + // in the past, thereby making repeated corrections unnecessary. In this model, the code _interpreting_ the value + // needs to apply the convention a negative publicationDelay essentially means "no delay". + if publicationDelay < 0 { + publicationDelay = 0 // Controller can only delay publication of proposal. Hence, the delay is lower-bounded by zero. + } ctl.metrics.ProposalPublicationDelay(publicationDelay) return targetPublicationTime diff --git a/consensus/hotstuff/cruisectl/block_time_controller_test.go b/consensus/hotstuff/cruisectl/block_time_controller_test.go index 4b7e36e8983..590f38de7a8 100644 --- a/consensus/hotstuff/cruisectl/block_time_controller_test.go +++ b/consensus/hotstuff/cruisectl/block_time_controller_test.go @@ -750,7 +750,7 @@ func captureControllerStateDigest(ctl *BlockTimeController) *controllerStateDige // inProximityOf returns a testify `argumentMatcher` that only accepts durations d, // such that |d - t| ≤ ε, for specified constants targetValue t and acceptedDeviation ε. -func inProximityOf(targetValue, acceptedDeviation time.Duration) any { +func inProximityOf(targetValue, acceptedDeviation time.Duration) interface{} { return mock.MatchedBy(func(duration time.Duration) bool { e := targetValue.Seconds() - duration.Seconds() return math.Abs(e) <= acceptedDeviation.Abs().Seconds() diff --git a/consensus/hotstuff/cruisectl/proposal_timing.go b/consensus/hotstuff/cruisectl/proposal_timing.go index 24e70a99c68..8f6082ad252 100644 --- a/consensus/hotstuff/cruisectl/proposal_timing.go +++ b/consensus/hotstuff/cruisectl/proposal_timing.go @@ -138,3 +138,17 @@ func (pt *fallbackTiming) ObservationView() uint64 { return pt.observationVie func (pt *fallbackTiming) ObservationTime() time.Time { return pt.observationTime } /* *************************************** auxiliary functions *************************************** */ + +func min(d1, d2 time.Duration) time.Duration { + if d1 < d2 { + return d1 + } + return d2 +} + +func max(d1, d2 time.Duration) time.Duration { + if d1 > d2 { + return d1 + } + return d2 +} diff --git a/consensus/hotstuff/eventhandler/event_handler_test.go b/consensus/hotstuff/eventhandler/event_handler_test.go index ec140097339..b469a47142b 100644 --- a/consensus/hotstuff/eventhandler/event_handler_test.go +++ b/consensus/hotstuff/eventhandler/event_handler_test.go @@ -777,7 +777,7 @@ func (es *EventHandlerSuite) TestOnTimeout_ReplicaEjected() { // Test100Timeout tests that receiving 100 TCs for increasing views advances rounds func (es *EventHandlerSuite) Test100Timeout() { - for i := range 100 { + for i := 0; i < 100; i++ { tc := helper.MakeTC(helper.WithTCView(es.initView + uint64(i))) err := es.eventhandler.OnReceiveTc(tc) es.endView++ @@ -794,7 +794,7 @@ func (es *EventHandlerSuite) TestLeaderBuild100Blocks() { es.committee.leaders[es.initView] = struct{}{} totalView := 100 - for i := range totalView { + for i := 0; i < totalView; i++ { // I'm the leader for 100 views // I'm the next leader es.committee.leaders[es.initView+uint64(i+1)] = struct{}{} @@ -842,7 +842,7 @@ func (es *EventHandlerSuite) TestFollowerFollows100Blocks() { // add parent proposal otherwise we can't propose parentProposal := createProposal(es.initView, es.initView-1) es.forks.proposals[parentProposal.Block.BlockID] = parentProposal.Block - for i := range 100 { + for i := 0; i < 100; i++ { // create each proposal as if they are created by some leader proposal := createProposal(es.initView+uint64(i)+1, es.initView+uint64(i)) // as a follower, I receive these proposals @@ -856,7 +856,7 @@ func (es *EventHandlerSuite) TestFollowerFollows100Blocks() { // TestFollowerReceives100Forks tests scenario where follower receives 100 forks built on top of the same block func (es *EventHandlerSuite) TestFollowerReceives100Forks() { - for i := range 100 { + for i := 0; i < 100; i++ { // create each proposal as if they are created by some leader proposal := createProposal(es.initView+uint64(i)+1, es.initView-1) proposal.LastViewTC = helper.MakeTC(helper.WithTCView(es.initView+uint64(i)), diff --git a/consensus/hotstuff/integration/connect_test.go b/consensus/hotstuff/integration/connect_test.go index a66279cde86..cb5f1f33b2d 100644 --- a/consensus/hotstuff/integration/connect_test.go +++ b/consensus/hotstuff/integration/connect_test.go @@ -20,6 +20,7 @@ func Connect(t *testing.T, instances []*Instance) { // then, for each instance, initialize a wired up communicator for _, sender := range instances { + sender := sender // avoid capturing loop variable in closure *sender.notifier = *NewMockedCommunicatorConsumer() sender.notifier.On("OnOwnProposal", mock.Anything, mock.Anything).Run( diff --git a/consensus/hotstuff/integration/instance_test.go b/consensus/hotstuff/integration/instance_test.go index b7f55408737..3c6c9153f1c 100644 --- a/consensus/hotstuff/integration/instance_test.go +++ b/consensus/hotstuff/integration/instance_test.go @@ -56,7 +56,7 @@ type Instance struct { stop Condition // instance data - queue chan any + queue chan interface{} updatingBlocks sync.RWMutex headers map[flow.Identifier]*flow.Header pendings map[flow.Identifier]*model.SignedProposal // indexed by parent ID @@ -153,7 +153,7 @@ func NewInstance(t *testing.T, options ...Option) *Instance { // instance data pendings: make(map[flow.Identifier]*model.SignedProposal), headers: make(map[flow.Identifier]*flow.Header), - queue: make(chan any, 1024), + queue: make(chan interface{}, 1024), // instance mocks committee: &mocks.DynamicCommittee{}, diff --git a/consensus/hotstuff/integration/integration_test.go b/consensus/hotstuff/integration/integration_test.go index 110c27e980e..d29ec533942 100644 --- a/consensus/hotstuff/integration/integration_test.go +++ b/consensus/hotstuff/integration/integration_test.go @@ -58,7 +58,7 @@ func TestThreeInstances(t *testing.T) { // since we don't block any messages we should have enough data to advance in happy path // for that reason we will block all TO related communication. instances := make([]*Instance, 0, num) - for n := range num { + for n := 0; n < num; n++ { in := NewInstance(t, WithRoot(root), WithParticipants(participants), @@ -119,7 +119,7 @@ func TestSevenInstances(t *testing.T) { require.NoError(t, err) // set up five instances that work fully - for n := range numPass { + for n := 0; n < numPass; n++ { in := NewInstance(t, WithRoot(root), WithParticipants(participants), diff --git a/consensus/hotstuff/integration/liveness_test.go b/consensus/hotstuff/integration/liveness_test.go index 5387d5f34c9..3d7c14c55f4 100644 --- a/consensus/hotstuff/integration/liveness_test.go +++ b/consensus/hotstuff/integration/liveness_test.go @@ -40,7 +40,7 @@ func Test2TimeoutOutof7Instances(t *testing.T) { require.NoError(t, err) // set up five instances that work fully - for n := range healthyReplicas { + for n := 0; n < healthyReplicas; n++ { in := NewInstance(t, WithRoot(root), WithParticipants(participants), @@ -107,7 +107,7 @@ func Test2TimeoutOutof4Instances(t *testing.T) { require.NoError(t, err) // set up two instances that work fully - for n := range healthyReplicas { + for n := 0; n < healthyReplicas; n++ { in := NewInstance(t, WithRoot(root), WithParticipants(participants), @@ -176,7 +176,7 @@ func Test1TimeoutOutof5Instances(t *testing.T) { require.NoError(t, err) // set up instances that work fully - for n := range healthyReplicas { + for n := 0; n < healthyReplicas; n++ { in := NewInstance(t, WithRoot(root), WithParticipants(participants), @@ -273,7 +273,7 @@ func TestBlockDelayIsHigherThanTimeout(t *testing.T) { require.NoError(t, err) // set up 2 instances that fully work (incl. sending TimeoutObjects) - for n := range healthyReplicas { + for n := 0; n < healthyReplicas; n++ { in := NewInstance(t, WithRoot(root), WithParticipants(participants), @@ -358,7 +358,7 @@ func TestAsyncClusterStartup(t *testing.T) { // set up instances that work fully var lock sync.Mutex timeoutObjectGenerated := make(map[flow.Identifier]struct{}, 0) - for n := range replicas { + for n := 0; n < replicas; n++ { in := NewInstance(t, WithRoot(root), WithParticipants(participants), diff --git a/consensus/hotstuff/pacemaker/pacemaker_test.go b/consensus/hotstuff/pacemaker/pacemaker_test.go index a02c7c684fd..7db14618460 100644 --- a/consensus/hotstuff/pacemaker/pacemaker_test.go +++ b/consensus/hotstuff/pacemaker/pacemaker_test.go @@ -28,7 +28,7 @@ const ( happyPathMaxRoundFailures uint64 = 6 // number of failed rounds before first timeout increase ) -func expectedTimerInfo(view uint64) any { +func expectedTimerInfo(view uint64) interface{} { return mock.MatchedBy( func(timerInfo model.TimerInfo) bool { return timerInfo.View == view @@ -318,7 +318,7 @@ func (s *ActivePaceMakerTestSuite) Test_Initialization() { // This is useful as a fallback, because it allows replicas other than the designated // leader to also collect votes and generate a QC. tcs := make([]*flow.TimeoutCertificate, 110) - for i := range 80 { + for i := 0; i < 80; i++ { tcView := s.initialView + uint64(rand.Intn(100)) qcView := 1 + uint64(rand.Intn(int(tcView))) tcs[i] = helper.MakeTC(helper.WithTCView(tcView), helper.WithTCNewestQC(QC(qcView))) @@ -330,7 +330,7 @@ func (s *ActivePaceMakerTestSuite) Test_Initialization() { // randomly create 80 QCs (same logic as above) qcs := make([]*flow.QuorumCertificate, 110) - for i := range 80 { + for i := 0; i < 80; i++ { qcs[i] = QC(s.initialView + uint64(rand.Intn(100))) highestView = max(highestView, qcs[i].View) } diff --git a/consensus/hotstuff/signature/packer_test.go b/consensus/hotstuff/signature/packer_test.go index d084004bcc8..5ff63f77749 100644 --- a/consensus/hotstuff/signature/packer_test.go +++ b/consensus/hotstuff/signature/packer_test.go @@ -121,7 +121,7 @@ func TestPackUnpackManyNodes(t *testing.T) { view := rand.Uint64() blockSigData := makeBlockSigData(committee) stakingSigners := make([]flow.Identifier, 0) - for i := range 60 { + for i := 0; i < 60; i++ { stakingSigners = append(stakingSigners, committee[i].NodeID) } randomBeaconSigners := make([]flow.Identifier, 0) diff --git a/consensus/hotstuff/signature/weighted_signature_aggregator_test.go b/consensus/hotstuff/signature/weighted_signature_aggregator_test.go index 66c20404890..03942153fe5 100644 --- a/consensus/hotstuff/signature/weighted_signature_aggregator_test.go +++ b/consensus/hotstuff/signature/weighted_signature_aggregator_test.go @@ -45,7 +45,7 @@ func createAggregationData(t *testing.T, signersNumber int) ( sigs := make([]crypto.Signature, 0, signersNumber) pks := make([]crypto.PublicKey, 0, signersNumber) seed := make([]byte, crypto.KeyGenSeedMinLen) - for range signersNumber { + for i := 0; i < signersNumber; i++ { // id ids = append(ids, unittest.IdentityFixture()) // keys @@ -149,7 +149,7 @@ func TestWeightedSignatureAggregator(t *testing.T) { assert.True(t, ok) // check signers identifiers = make([]flow.Identifier, 0, signersNum) - for i := range signersNum { + for i := 0; i < signersNum; i++ { identifiers = append(identifiers, ids[i].NodeID) } assert.ElementsMatch(t, signers, identifiers) diff --git a/consensus/hotstuff/timeoutaggregator/timeout_aggregator.go b/consensus/hotstuff/timeoutaggregator/timeout_aggregator.go index d83417bc078..e5294e9b4ee 100644 --- a/consensus/hotstuff/timeoutaggregator/timeout_aggregator.go +++ b/consensus/hotstuff/timeoutaggregator/timeout_aggregator.go @@ -72,7 +72,7 @@ func NewTimeoutAggregator(log zerolog.Logger, } componentBuilder := component.NewComponentManagerBuilder() - for range defaultTimeoutAggregatorWorkers { // manager for worker routines that process inbound events + for i := 0; i < defaultTimeoutAggregatorWorkers; i++ { // manager for worker routines that process inbound events componentBuilder.AddWorker(func(ctx irrecoverable.SignalerContext, ready component.ReadyFunc) { ready() aggregator.queuedTimeoutsProcessingLoop(ctx) diff --git a/consensus/hotstuff/timeoutaggregator/timeout_aggregator_test.go b/consensus/hotstuff/timeoutaggregator/timeout_aggregator_test.go index 0c3d0719840..ac570cf77a2 100644 --- a/consensus/hotstuff/timeoutaggregator/timeout_aggregator_test.go +++ b/consensus/hotstuff/timeoutaggregator/timeout_aggregator_test.go @@ -79,7 +79,7 @@ func (s *TimeoutAggregatorTestSuite) TestAddTimeout_HappyPath() { var start sync.WaitGroup start.Add(timeoutsCount) - for range timeoutsCount { + for i := 0; i < timeoutsCount; i++ { go func() { timeout := helper.TimeoutObjectFixture(helper.WithTimeoutObjectView(s.lowestRetainedView)) diff --git a/consensus/hotstuff/timeoutaggregator/timeout_collectors_test.go b/consensus/hotstuff/timeoutaggregator/timeout_collectors_test.go index f7239e7c335..ef19cfce01d 100644 --- a/consensus/hotstuff/timeoutaggregator/timeout_collectors_test.go +++ b/consensus/hotstuff/timeoutaggregator/timeout_collectors_test.go @@ -123,14 +123,16 @@ func (s *TimeoutCollectorsTestSuite) TestGetOrCreateCollectors_ConcurrentAccess( view := s.lowestView + 10 s.prepareMockedCollector(view) var wg sync.WaitGroup - for range 10 { - wg.Go(func() { + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { + defer wg.Done() _, created, err := s.collectors.GetOrCreateCollector(view) require.NoError(s.T(), err) if created { createdTimes.Add(1) } - }) + }() } unittest.AssertReturnsBefore(s.T(), wg.Wait, time.Second) @@ -141,7 +143,7 @@ func (s *TimeoutCollectorsTestSuite) TestGetOrCreateCollectors_ConcurrentAccess( func (s *TimeoutCollectorsTestSuite) TestPruneUpToView() { numberOfCollectors := uint64(10) prunedViews := make([]uint64, 0) - for i := range numberOfCollectors { + for i := uint64(0); i < numberOfCollectors; i++ { view := s.lowestView + i s.prepareMockedCollector(view) _, _, err := s.collectors.GetOrCreateCollector(view) @@ -152,7 +154,7 @@ func (s *TimeoutCollectorsTestSuite) TestPruneUpToView() { pruningHeight := s.lowestView + numberOfCollectors expectedCollectors := make([]hotstuff.TimeoutCollector, 0) - for i := range numberOfCollectors { + for i := uint64(0); i < numberOfCollectors; i++ { view := pruningHeight + i s.prepareMockedCollector(view) collector, _, err := s.collectors.GetOrCreateCollector(view) diff --git a/consensus/hotstuff/timeoutcollector/aggregation_test.go b/consensus/hotstuff/timeoutcollector/aggregation_test.go index 9ad9e580584..93eb0774d0a 100644 --- a/consensus/hotstuff/timeoutcollector/aggregation_test.go +++ b/consensus/hotstuff/timeoutcollector/aggregation_test.go @@ -39,7 +39,7 @@ func createAggregationData(t *testing.T, signersNumber int) ( ids := make(flow.IdentitySkeletonList, 0, signersNumber) pks := make([]crypto.PublicKey, 0, signersNumber) view := 10 + uint64(rand.Uint32()) - for range signersNumber { + for i := 0; i < signersNumber; i++ { sk := unittest.PrivateKeyFixture(crypto.BLSBLS12381) identity := unittest.IdentityFixture(unittest.WithStakingPubKey(sk.PublicKey())) // id diff --git a/consensus/hotstuff/timeoutcollector/timeout_collector_test.go b/consensus/hotstuff/timeoutcollector/timeout_collector_test.go index 77794ef9450..f30b953c1cf 100644 --- a/consensus/hotstuff/timeoutcollector/timeout_collector_test.go +++ b/consensus/hotstuff/timeoutcollector/timeout_collector_test.go @@ -53,14 +53,16 @@ func (s *TimeoutCollectorTestSuite) TestView() { // all operations should be successful, no errors expected func (s *TimeoutCollectorTestSuite) TestAddTimeout_HappyPath() { var wg sync.WaitGroup - for range 20 { - wg.Go(func() { + for i := 0; i < 20; i++ { + wg.Add(1) + go func() { + defer wg.Done() timeout := helper.TimeoutObjectFixture(helper.WithTimeoutObjectView(s.view)) s.notifier.On("OnTimeoutProcessed", timeout).Once() s.processor.On("Process", timeout).Return(nil).Once() err := s.collector.AddTimeout(timeout) require.NoError(s.T(), err) - }) + }() } unittest.AssertReturnsBefore(s.T(), wg.Wait, time.Second) @@ -155,7 +157,7 @@ func (s *TimeoutCollectorTestSuite) TestAddTimeout_TONotifications() { s.notifier.On("OnNewTcDiscovered", lastViewTC).Once() timeouts := make([]*model.TimeoutObject, 0, qcCount) - for i := range qcCount { + for i := 0; i < qcCount; i++ { qc := helper.MakeQC(helper.WithQCView(uint64(i))) timeout := helper.TimeoutObjectFixture(func(timeout *model.TimeoutObject) { timeout.View = s.view diff --git a/consensus/hotstuff/tracker/tracker_test.go b/consensus/hotstuff/tracker/tracker_test.go index 757a700644c..04e5a735097 100644 --- a/consensus/hotstuff/tracker/tracker_test.go +++ b/consensus/hotstuff/tracker/tracker_test.go @@ -30,13 +30,13 @@ func TestNewestQCTracker_Track(t *testing.T) { // setup initial value tracker.Track(helper.MakeQC(helper.WithQCView(0))) - for range times { + for i := 0; i < times; i++ { startView := tracker.NewestQC().View var readyWg, startWg, doneWg sync.WaitGroup startWg.Add(1) readyWg.Add(samples) doneWg.Add(samples) - for s := range samples { + for s := 0; s < samples; s++ { qc := helper.MakeQC(helper.WithQCView(startView + uint64(s+1))) go func(newestQC *flow.QuorumCertificate) { defer doneWg.Done() @@ -77,13 +77,13 @@ func TestNewestTCTracker_Track(t *testing.T) { // setup initial value tracker.Track(helper.MakeTC(helper.WithTCView(0))) - for range times { + for i := 0; i < times; i++ { startView := tracker.NewestTC().View var readyWg, startWg, doneWg sync.WaitGroup startWg.Add(1) readyWg.Add(samples) doneWg.Add(samples) - for s := range samples { + for s := 0; s < samples; s++ { tc := helper.MakeTC(helper.WithTCView(startView + uint64(s+1))) go func(newestTC *flow.TimeoutCertificate) { defer doneWg.Done() @@ -124,13 +124,13 @@ func TestNewestBlockTracker_Track(t *testing.T) { // setup initial value tracker.Track(helper.MakeBlock(helper.WithBlockView(0))) - for range times { + for i := 0; i < times; i++ { startView := tracker.NewestBlock().View var readyWg, startWg, doneWg sync.WaitGroup startWg.Add(1) readyWg.Add(samples) doneWg.Add(samples) - for s := range samples { + for s := 0; s < samples; s++ { block := helper.MakeBlock(helper.WithBlockView(startView + uint64(s+1))) go func(newestBlock *model.Block) { defer doneWg.Done() diff --git a/consensus/hotstuff/verification/common.go b/consensus/hotstuff/verification/common.go index 06c9e50dab7..04c355f4390 100644 --- a/consensus/hotstuff/verification/common.go +++ b/consensus/hotstuff/verification/common.go @@ -105,7 +105,7 @@ func verifyTCSignatureManyMessages( messages := make([][]byte, 0, len(pks)) hashers := make([]hash.Hasher, 0, len(pks)) - for i := range pks { + for i := 0; i < len(pks); i++ { messages = append(messages, MakeTimeoutMessage(view, highQCViews[i])) hashers = append(hashers, hasher) } diff --git a/consensus/hotstuff/voteaggregator/vote_aggregator.go b/consensus/hotstuff/voteaggregator/vote_aggregator.go index 115ae5d81df..32ea0ef2a65 100644 --- a/consensus/hotstuff/voteaggregator/vote_aggregator.go +++ b/consensus/hotstuff/voteaggregator/vote_aggregator.go @@ -93,7 +93,7 @@ func NewVoteAggregator( componentBuilder := component.NewComponentManagerBuilder() var wg sync.WaitGroup wg.Add(defaultVoteAggregatorWorkers) - for range defaultVoteAggregatorWorkers { // manager for worker routines that process inbound messages + for i := 0; i < defaultVoteAggregatorWorkers; i++ { // manager for worker routines that process inbound messages componentBuilder.AddWorker(func(ctx irrecoverable.SignalerContext, ready component.ReadyFunc) { defer wg.Done() ready() diff --git a/consensus/hotstuff/voteaggregator/vote_collectors_test.go b/consensus/hotstuff/voteaggregator/vote_collectors_test.go index 305f9b004f0..f1851c03538 100644 --- a/consensus/hotstuff/voteaggregator/vote_collectors_test.go +++ b/consensus/hotstuff/voteaggregator/vote_collectors_test.go @@ -103,14 +103,16 @@ func (s *VoteCollectorsTestSuite) TestGetOrCreateCollectors_ConcurrentAccess() { view := s.lowestLevel + 10 s.prepareMockedCollector(view) var wg sync.WaitGroup - for range 10 { - wg.Go(func() { + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { _, created, err := s.collectors.GetOrCreateCollector(view) require.NoError(s.T(), err) if created { createdTimes.Add(1) } - }) + wg.Done() + }() } wg.Wait() @@ -121,7 +123,7 @@ func (s *VoteCollectorsTestSuite) TestGetOrCreateCollectors_ConcurrentAccess() { func (s *VoteCollectorsTestSuite) TestPruneUpToView() { numberOfCollectors := uint64(10) prunedViews := make([]uint64, 0) - for i := range numberOfCollectors { + for i := uint64(0); i < numberOfCollectors; i++ { view := s.lowestLevel + i s.prepareMockedCollector(view) _, _, err := s.collectors.GetOrCreateCollector(view) @@ -132,7 +134,7 @@ func (s *VoteCollectorsTestSuite) TestPruneUpToView() { pruningHeight := s.lowestLevel + numberOfCollectors expectedCollectors := make([]hotstuff.VoteCollector, 0) - for i := range numberOfCollectors { + for i := uint64(0); i < numberOfCollectors; i++ { view := pruningHeight + i s.prepareMockedCollector(view) collector, _, err := s.collectors.GetOrCreateCollector(view) diff --git a/consensus/hotstuff/votecollector/combined_vote_processor_v2_test.go b/consensus/hotstuff/votecollector/combined_vote_processor_v2_test.go index 7c5a3cd653e..8a4d67b375e 100644 --- a/consensus/hotstuff/votecollector/combined_vote_processor_v2_test.go +++ b/consensus/hotstuff/votecollector/combined_vote_processor_v2_test.go @@ -411,14 +411,16 @@ func (s *CombinedVoteProcessorV2TestSuite) TestProcess_ConcurrentCreatingQC() { vote := unittest.VoteForBlockFixture(s.proposal.Block, VoteWithStakingSig()) startupWg.Add(1) // prepare goroutines, so they are ready to submit a vote at roughly same time - for range 5 { - shutdownWg.Go(func() { + for i := 0; i < 5; i++ { + shutdownWg.Add(1) + go func() { + defer shutdownWg.Done() startupWg.Wait() err := s.processor.Process(vote) if err != nil { require.True(s.T(), model.IsDuplicatedSignerError(err)) } - }) + }() } startupWg.Done() diff --git a/consensus/hotstuff/votecollector/combined_vote_processor_v3_test.go b/consensus/hotstuff/votecollector/combined_vote_processor_v3_test.go index 5f93d48dc75..aca9120ded1 100644 --- a/consensus/hotstuff/votecollector/combined_vote_processor_v3_test.go +++ b/consensus/hotstuff/votecollector/combined_vote_processor_v3_test.go @@ -415,14 +415,16 @@ func (s *CombinedVoteProcessorV3TestSuite) TestProcess_ConcurrentCreatingQC() { vote := unittest.VoteForBlockFixture(s.proposal.Block, unittest.VoteWithStakingSig()) startupWg.Add(1) // prepare goroutines, so they are ready to submit a vote at roughly same time - for range 5 { - shutdownWg.Go(func() { + for i := 0; i < 5; i++ { + shutdownWg.Add(1) + go func() { + defer shutdownWg.Done() startupWg.Wait() err := s.processor.Process(vote) if err != nil { require.True(s.T(), model.IsDuplicatedSignerError(err)) } - }) + }() } startupWg.Done() diff --git a/consensus/hotstuff/votecollector/staking_vote_processor_test.go b/consensus/hotstuff/votecollector/staking_vote_processor_test.go index ddd62bdddcb..1b096419c4d 100644 --- a/consensus/hotstuff/votecollector/staking_vote_processor_test.go +++ b/consensus/hotstuff/votecollector/staking_vote_processor_test.go @@ -225,12 +225,14 @@ func (s *StakingVoteProcessorTestSuite) TestProcess_ConcurrentCreatingQC() { vote := unittest.VoteForBlockFixture(s.proposal.Block) startupWg.Add(1) // prepare goroutines, so they are ready to submit a vote at roughly same time - for range 5 { - shutdownWg.Go(func() { + for i := 0; i < 5; i++ { + shutdownWg.Add(1) + go func() { + defer shutdownWg.Done() startupWg.Wait() err := s.processor.Process(vote) require.NoError(s.T(), err) - }) + }() } startupWg.Done() diff --git a/consensus/hotstuff/votecollector/statemachine_test.go b/consensus/hotstuff/votecollector/statemachine_test.go index ed7c02572a6..ce0933acd73 100644 --- a/consensus/hotstuff/votecollector/statemachine_test.go +++ b/consensus/hotstuff/votecollector/statemachine_test.go @@ -214,7 +214,7 @@ func (s *StateMachineTestSuite) TestProcessBlock_ProcessingOfCachedVotes() { proposal := makeSignedProposalWithView(s.view) block := proposal.Block processor := s.prepareMockedProcessor(proposal) - for range votes { + for i := 0; i < votes; i++ { vote := unittest.VoteForBlockFixture(block) // once when caching vote, and once when processing cached vote s.notifier.On("OnVoteProcessed", vote).Twice() @@ -447,7 +447,7 @@ func (s *StateMachineTestSuite) RegisterVoteConsumer() { block := proposal.Block processor := s.prepareMockedProcessor(proposal) expectedVotes := make([]*model.Vote, 0) - for range votes { + for i := 0; i < votes; i++ { vote := unittest.VoteForBlockFixture(block) // eventually it has to be process by processor processor.On("Process", vote).Return(nil).Once() @@ -462,7 +462,7 @@ func (s *StateMachineTestSuite) RegisterVoteConsumer() { s.collector.RegisterVoteConsumer(consumer) - for range votes { + for i := 0; i < votes; i++ { vote := unittest.VoteForBlockFixture(block) // eventually it has to be process by processor processor.On("Process", vote).Return(nil).Once() diff --git a/consensus/hotstuff/votecollector/vote_cache_test.go b/consensus/hotstuff/votecollector/vote_cache_test.go index 4d895bbc718..2e83e775676 100644 --- a/consensus/hotstuff/votecollector/vote_cache_test.go +++ b/consensus/hotstuff/votecollector/vote_cache_test.go @@ -114,7 +114,7 @@ func TestVotesCache_RegisterVoteConsumer(t *testing.T) { require.Equal(t, expectedVotes, consumedVotes) // produce second batch after registering vote consumer - for range votesBatchSize { + for i := 0; i < votesBatchSize; i++ { vote := unittest.VoteFixture(unittest.WithVoteView(view)) expectedVotes = append(expectedVotes, vote) require.NoError(t, cache.AddVote(vote)) diff --git a/consensus/integration/blockordelay_test.go b/consensus/integration/blockordelay_test.go index f180d213b0f..fceebc4c1ca 100644 --- a/consensus/integration/blockordelay_test.go +++ b/consensus/integration/blockordelay_test.go @@ -23,7 +23,7 @@ func blockNodesFirstMessages(n uint64, denyList ...*Node) BlockOrDelayFunc { blackList[node.id.NodeID] = n } lock := new(sync.Mutex) - return func(channel channels.Channel, event any, sender, receiver *Node) (bool, time.Duration) { + return func(channel channels.Channel, event interface{}, sender, receiver *Node) (bool, time.Duration) { // filter only consensus messages switch event.(type) { case *messages.Proposal: @@ -48,7 +48,7 @@ func blockNodesFirstMessages(n uint64, denyList ...*Node) BlockOrDelayFunc { func blockReceiverMessagesRandomly(dropProbability float32) BlockOrDelayFunc { lock := new(sync.Mutex) prng := rand.New(rand.NewSource(time.Now().UnixNano())) - return func(channel channels.Channel, event any, sender, receiver *Node) (bool, time.Duration) { + return func(channel channels.Channel, event interface{}, sender, receiver *Node) (bool, time.Duration) { lock.Lock() block := prng.Float32() < dropProbability lock.Unlock() @@ -74,12 +74,12 @@ func delayReceiverMessagesByRange(low time.Duration, high time.Duration) BlockOr // shortcut for low = high: always return low if delayRangeNs == 0 { - return func(channel channels.Channel, event any, sender, receiver *Node) (bool, time.Duration) { + return func(channel channels.Channel, event interface{}, sender, receiver *Node) (bool, time.Duration) { return false, low } } // general version - return func(channel channels.Channel, event any, sender, receiver *Node) (bool, time.Duration) { + return func(channel channels.Channel, event interface{}, sender, receiver *Node) (bool, time.Duration) { lock.Lock() d := prng.Int63n(delayRangeNs) lock.Unlock() diff --git a/consensus/integration/integration_test.go b/consensus/integration/integration_test.go index 0b31feb3604..ddc1c8cb6fc 100644 --- a/consensus/integration/integration_test.go +++ b/consensus/integration/integration_test.go @@ -143,11 +143,11 @@ func chainViews(t *testing.T, node *Node) []uint64 { // entirely (return value `true`) or should be delivered (return value `false`). The second // return value specifies the delay by which the message should be delivered. // Implementations must be CONCURRENCY SAFE. -type BlockOrDelayFunc func(channel channels.Channel, event any, sender, receiver *Node) (bool, time.Duration) +type BlockOrDelayFunc func(channel channels.Channel, event interface{}, sender, receiver *Node) (bool, time.Duration) // blockNothing specifies that _all_ messages should be delivered without delay. // I.e. this function returns always `false` (no blocking), `0` (no delay). -func blockNothing(_ channels.Channel, _ any, _, _ *Node) (bool, time.Duration) { +func blockNothing(_ channels.Channel, _ interface{}, _, _ *Node) (bool, time.Duration) { return false, 0 } @@ -160,7 +160,7 @@ func blockNodes(denyList ...*Node) BlockOrDelayFunc { denyMap[n.id.NodeID] = n } // no concurrency protection needed as blackList is only read but not modified - return func(channel channels.Channel, event any, sender, receiver *Node) (bool, time.Duration) { + return func(channel channels.Channel, event interface{}, sender, receiver *Node) (bool, time.Duration) { if _, ok := denyMap[sender.id.NodeID]; ok { return true, 0 // block the message } diff --git a/consensus/integration/network_test.go b/consensus/integration/network_test.go index b6c22ce06c1..79cb20ad2ee 100644 --- a/consensus/integration/network_test.go +++ b/consensus/integration/network_test.go @@ -115,7 +115,7 @@ func (n *Network) unregister(channel channels.Channel) error { // submit is called when the attached Engine to the channel is sending an event to an // Engine attached to the same channel on another node or nodes. // This implementation uses unicast under the hood. -func (n *Network) submit(event any, channel channels.Channel, targetIDs ...flow.Identifier) error { +func (n *Network) submit(event interface{}, channel channels.Channel, targetIDs ...flow.Identifier) error { var sendErrors *multierror.Error for _, targetID := range targetIDs { if err := n.unicast(event, channel, targetID); err != nil { @@ -127,7 +127,7 @@ func (n *Network) submit(event any, channel channels.Channel, targetIDs ...flow. // unicast is called when the attached Engine to the channel is sending an event to a single target // Engine attached to the same channel on another node. -func (n *Network) unicast(event any, channel channels.Channel, targetID flow.Identifier) error { +func (n *Network) unicast(event interface{}, channel channels.Channel, targetID flow.Identifier) error { net, found := n.hub.networks[targetID] if !found { return fmt.Errorf("could not find target network on hub: %x", targetID) @@ -155,7 +155,7 @@ func (n *Network) unicast(event any, channel channels.Channel, targetID flow.Ide } // use a goroutine to wait and send - go func(delay time.Duration, senderID flow.Identifier, receiver *Conduit, event any) { + go func(delay time.Duration, senderID flow.Identifier, receiver *Conduit, event interface{}) { // sleep in order to simulate the network delay time.Sleep(delay) msg, ok := event.(messages.UntrustedMessage) @@ -173,14 +173,14 @@ func (n *Network) unicast(event any, channel channels.Channel, targetID flow.Ide // publish is called when the attached Engine is sending an event to a group of Engines attached to the // same channel on other nodes based on selector. // In this test helper implementation, publish uses submit method under the hood. -func (n *Network) publish(event any, channel channels.Channel, targetIDs ...flow.Identifier) error { +func (n *Network) publish(event interface{}, channel channels.Channel, targetIDs ...flow.Identifier) error { return n.submit(event, channel, targetIDs...) } // multicast is called when an Engine attached to the channel is sending an event to a number of randomly chosen // Engines attached to the same channel on other nodes. The targeted nodes are selected based on the selector. // In this test helper implementation, multicast uses submit method under the hood. -func (n *Network) multicast(event any, channel channels.Channel, num uint, targetIDs ...flow.Identifier) error { +func (n *Network) multicast(event interface{}, channel channels.Channel, num uint, targetIDs ...flow.Identifier) error { var err error targetIDs, err = flow.Sample(num, targetIDs...) if err != nil { @@ -206,28 +206,28 @@ func (c *Conduit) ReportMisbehavior(_ network.MisbehaviorReport) { var _ network.Conduit = (*Conduit)(nil) -func (c *Conduit) Submit(event any, targetIDs ...flow.Identifier) error { +func (c *Conduit) Submit(event interface{}, targetIDs ...flow.Identifier) error { if c.ctx.Err() != nil { return fmt.Errorf("conduit closed") } return c.net.submit(event, c.channel, targetIDs...) } -func (c *Conduit) Publish(event any, targetIDs ...flow.Identifier) error { +func (c *Conduit) Publish(event interface{}, targetIDs ...flow.Identifier) error { if c.ctx.Err() != nil { return fmt.Errorf("conduit closed") } return c.net.publish(event, c.channel, targetIDs...) } -func (c *Conduit) Unicast(event any, targetID flow.Identifier) error { +func (c *Conduit) Unicast(event interface{}, targetID flow.Identifier) error { if c.ctx.Err() != nil { return fmt.Errorf("conduit closed") } return c.net.unicast(event, c.channel, targetID) } -func (c *Conduit) Multicast(event any, num uint, targetIDs ...flow.Identifier) error { +func (c *Conduit) Multicast(event interface{}, num uint, targetIDs ...flow.Identifier) error { if c.ctx.Err() != nil { return fmt.Errorf("conduit closed") } diff --git a/consensus/integration/slow_test.go b/consensus/integration/slow_test.go index 3814e8a93af..3ac5226755c 100644 --- a/consensus/integration/slow_test.go +++ b/consensus/integration/slow_test.go @@ -71,7 +71,7 @@ func TestOneNodeBehind(t *testing.T) { rootSnapshot := createRootSnapshot(t, participantsData) nodes, hub, runFor := createNodes(t, NewConsensusParticipants(participantsData), rootSnapshot, stopper) - hub.WithFilter(func(channelID channels.Channel, event any, sender, receiver *Node) (bool, time.Duration) { + hub.WithFilter(func(channelID channels.Channel, event interface{}, sender, receiver *Node) (bool, time.Duration) { if receiver == nodes[0] { return false, hotstuffTimeout + time.Millisecond } @@ -103,7 +103,7 @@ func TestTimeoutRebroadcast(t *testing.T) { // nodeID -> view -> numTimeoutMessages lock := new(sync.Mutex) blockedTimeoutObjectsTracker := make(map[flow.Identifier]map[uint64]uint64) - hub.WithFilter(func(channelID channels.Channel, event any, sender, receiver *Node) (bool, time.Duration) { + hub.WithFilter(func(channelID channels.Channel, event interface{}, sender, receiver *Node) (bool, time.Duration) { switch m := event.(type) { case *messages.Proposal: return m.Block.View == 5, 0 // drop proposals only for view 5 diff --git a/crypto/go.mod b/crypto/go.mod index 89d9d7b7876..d1ab85ff01a 100644 --- a/crypto/go.mod +++ b/crypto/go.mod @@ -1,4 +1,4 @@ // Deprecated: The latest supported version is v0.25.0. The module then migrated to github.com/onflow/crypto. Use the new module github.com/onflow/crypto instead. module github.com/onflow/flow-go/crypto -go 1.26 +go 1.25 diff --git a/engine/access/access_test.go b/engine/access/access_test.go index 769e5b609b3..ce22a417a29 100644 --- a/engine/access/access_test.go +++ b/engine/access/access_test.go @@ -1433,7 +1433,7 @@ func (suite *Suite) TestExecuteScript() { return &expectedResp } - assertResult := func(err error, expected any, actual any) { + assertResult := func(err error, expected interface{}, actual interface{}) { suite.Require().NoError(err) suite.Require().Equal(expected, actual) suite.execClient.AssertExpectations(suite.T()) diff --git a/engine/access/index/event_index_test.go b/engine/access/index/event_index_test.go index 9bb2e249458..94b521d6046 100644 --- a/engine/access/index/event_index_test.go +++ b/engine/access/index/event_index_test.go @@ -46,7 +46,7 @@ func TestGetEvents(t *testing.T) { func generateTxEvents(txID flow.Identifier, txIndex uint32, count int) flow.EventsList { events := make(flow.EventsList, count) - for i := range count { + for i := 0; i < count; i++ { events[i] = flow.Event{ Type: unittest.EventTypeFixture(flow.Localnet), TransactionID: txID, diff --git a/engine/access/ingestion/engine.go b/engine/access/ingestion/engine.go index 839d08d6180..8bc8e802aca 100644 --- a/engine/access/ingestion/engine.go +++ b/engine/access/ingestion/engine.go @@ -309,7 +309,7 @@ func (e *Engine) processTransactionResultErrorMessagesByReceipts(ctx irrecoverab // process processes the given ingestion engine event. Events that are given // to this function originate within the expulsion engine on the node with the // given origin ID. -func (e *Engine) process(originID flow.Identifier, event any) error { +func (e *Engine) process(originID flow.Identifier, event interface{}) error { select { case <-e.ComponentManager.ShutdownSignal(): return component.ErrComponentShutdown @@ -328,7 +328,7 @@ func (e *Engine) process(originID flow.Identifier, event any) error { // Process processes the given event from the node with the given origin ID in // a blocking manner. It returns the potential processing error when done. -func (e *Engine) Process(_ channels.Channel, originID flow.Identifier, event any) error { +func (e *Engine) Process(_ channels.Channel, originID flow.Identifier, event interface{}) error { return e.process(originID, event) } diff --git a/engine/access/ingestion/engine_test.go b/engine/access/ingestion/engine_test.go index e0cb11a7f4d..59adbcaa937 100644 --- a/engine/access/ingestion/engine_test.go +++ b/engine/access/ingestion/engine_test.go @@ -366,7 +366,7 @@ func (s *Suite) TestOnFinalizedBlockSeveralBlocksAhead() { blocks := make([]*flow.Block, newBlocksCount) // generate the test blocks, cgs and collections - for i := range newBlocksCount { + for i := 0; i < newBlocksCount; i++ { block := s.generateBlock(clusterCommittee, snap) block.Height = startHeight + uint64(i) s.blockMap[block.Height] = block diff --git a/engine/access/ingestion/tx_error_messages/tx_error_messages_core_test.go b/engine/access/ingestion/tx_error_messages/tx_error_messages_core_test.go index 2e77c4dcc4f..62c11353cbf 100644 --- a/engine/access/ingestion/tx_error_messages/tx_error_messages_core_test.go +++ b/engine/access/ingestion/tx_error_messages/tx_error_messages_core_test.go @@ -335,7 +335,7 @@ func createExpectedTxErrorMessages(resultsByBlockID []flow.LightTransactionResul func mockTransactionResultsByBlock(count int) []flow.LightTransactionResult { // Create mock transaction results with a mix of failed and non-failed transactions. resultsByBlockID := make([]flow.LightTransactionResult, 0) - for i := range count { + for i := 0; i < count; i++ { resultsByBlockID = append(resultsByBlockID, flow.LightTransactionResult{ TransactionID: unittest.IdentifierFixture(), Failed: i%2 == 0, // create a mix of failed and non-failed transactions diff --git a/engine/access/ingestion/tx_error_messages/tx_error_messages_engine_test.go b/engine/access/ingestion/tx_error_messages/tx_error_messages_engine_test.go index 7908a47209a..b01988b4846 100644 --- a/engine/access/ingestion/tx_error_messages/tx_error_messages_engine_test.go +++ b/engine/access/ingestion/tx_error_messages/tx_error_messages_engine_test.go @@ -120,7 +120,7 @@ func (s *TxErrorMessagesEngineSuite) SetupTest() { s.rootBlock = unittest.Block.Genesis(flow.Emulator) parent := s.rootBlock.ToHeader() - for range blockCount { + for i := 0; i < blockCount; i++ { block := unittest.BlockWithParentFixture(parent) // update for next iteration parent = block.ToHeader() diff --git a/engine/access/ingestion2/engine.go b/engine/access/ingestion2/engine.go index 5b9db6d85bc..3b81b776156 100644 --- a/engine/access/ingestion2/engine.go +++ b/engine/access/ingestion2/engine.go @@ -102,7 +102,7 @@ func New( // a blocking manner. It returns the potential processing error when done. // // No errors are expected during normal operations. -func (e *Engine) Process(chanName channels.Channel, originID flow.Identifier, event any) error { +func (e *Engine) Process(chanName channels.Channel, originID flow.Identifier, event interface{}) error { select { case <-e.ComponentManager.ShutdownSignal(): return component.ErrComponentShutdown diff --git a/engine/access/ingestion2/engine_test.go b/engine/access/ingestion2/engine_test.go index 2315d13cc41..78c0541f220 100644 --- a/engine/access/ingestion2/engine_test.go +++ b/engine/access/ingestion2/engine_test.go @@ -145,7 +145,7 @@ func (s *Suite) SetupTest() { s.rootBlock = unittest.Block.Genesis(flow.Emulator) parent := s.rootBlock.ToHeader() - for range blockCount { + for i := 0; i < blockCount; i++ { block := unittest.BlockWithParentFixture(parent) // update for next iteration parent = block.ToHeader() @@ -379,7 +379,7 @@ func (s *Suite) TestOnFinalizedBlockSeveralBlocksAhead() { blocks := make([]*flow.Block, newBlocksCount) // generate the test blocks, cgs and collections - for i := range newBlocksCount { + for i := 0; i < newBlocksCount; i++ { block := s.generateBlock(clusterCommittee, snap) block.Height = startHeight + uint64(i) s.blockMap[block.Height] = block diff --git a/engine/access/integration_unsecure_grpc_server_test.go b/engine/access/integration_unsecure_grpc_server_test.go index 7161eb6a473..847d0b50655 100644 --- a/engine/access/integration_unsecure_grpc_server_test.go +++ b/engine/access/integration_unsecure_grpc_server_test.go @@ -154,7 +154,7 @@ func (suite *SameGRPCPortTestSuite) SetupTest() { parent := rootBlock.ToHeader() suite.blockMap[rootBlock.Height] = rootBlock - for range blockCount { + for i := 0; i < blockCount; i++ { block := unittest.BlockWithParentFixture(parent) suite.blockMap[block.Height] = block } diff --git a/engine/access/ping/engine.go b/engine/access/ping/engine.go index 389ea71672d..f6489484a33 100644 --- a/engine/access/ping/engine.go +++ b/engine/access/ping/engine.go @@ -117,6 +117,7 @@ func (e *Engine) pingAllNodes(ctx context.Context) { peers := e.idProvider.Identities(filter.Not(filter.HasNodeID[flow.Identity](e.me.NodeID()))) for i, peer := range peers { + peer := peer delay := makeJitter(i) g.Go(func() error { diff --git a/engine/access/rest/common/models/model_block_events.go b/engine/access/rest/common/models/model_block_events.go index ef8c933d3a3..7646856aca4 100644 --- a/engine/access/rest/common/models/model_block_events.go +++ b/engine/access/rest/common/models/model_block_events.go @@ -15,7 +15,7 @@ import ( type BlockEvents struct { BlockId string `json:"block_id,omitempty"` BlockHeight string `json:"block_height,omitempty"` - BlockTimestamp time.Time `json:"block_timestamp"` + BlockTimestamp time.Time `json:"block_timestamp,omitempty"` Events []Event `json:"events,omitempty"` Links *Links `json:"_links,omitempty"` } diff --git a/engine/access/rest/common/parser/transaction_test.go b/engine/access/rest/common/parser/transaction_test.go index 45cdbed36b1..fe13c8bb902 100644 --- a/engine/access/rest/common/parser/transaction_test.go +++ b/engine/access/rest/common/parser/transaction_test.go @@ -14,7 +14,7 @@ import ( "github.com/onflow/flow-go/utils/unittest" ) -func buildTransaction() map[string]any { +func buildTransaction() map[string]interface{} { tx := unittest.TransactionFixture() tx.Arguments = [][]uint8{} tx.PayloadSignatures = []flow.TransactionSignature{} @@ -23,19 +23,19 @@ func buildTransaction() map[string]any { auth[i] = a.String() } - return map[string]any{ + return map[string]interface{}{ "script": util.ToBase64(tx.Script), "arguments": tx.Arguments, "reference_block_id": tx.ReferenceBlockID.String(), "gas_limit": fmt.Sprintf("%d", tx.GasLimit), "payer": tx.Payer.String(), - "proposal_key": map[string]any{ + "proposal_key": map[string]interface{}{ "address": tx.ProposalKey.Address.String(), "key_index": fmt.Sprintf("%d", tx.ProposalKey.KeyIndex), "sequence_number": fmt.Sprintf("%d", tx.ProposalKey.SequenceNumber), }, "authorizers": auth, - "envelope_signatures": []map[string]any{{ + "envelope_signatures": []map[string]interface{}{{ "address": tx.EnvelopeSignatures[0].Address.String(), "key_index": fmt.Sprintf("%d", tx.EnvelopeSignatures[0].KeyIndex), "signature": util.ToBase64(tx.EnvelopeSignatures[0].Signature), @@ -43,7 +43,7 @@ func buildTransaction() map[string]any { } } -func transactionToReader(tx map[string]any) io.Reader { +func transactionToReader(tx map[string]interface{}) io.Reader { res, _ := json.Marshal(tx) return bytes.NewReader(res) } @@ -88,7 +88,7 @@ func TestTransaction_InvalidParse(t *testing.T) { for _, test := range keyTests { tx := buildTransaction() - tx["proposal_key"].(map[string]any)[test.inputField] = test.inputValue + tx["proposal_key"].(map[string]interface{})[test.inputField] = test.inputValue input := transactionToReader(tx) var transaction Transaction @@ -109,7 +109,7 @@ func TestTransaction_InvalidParse(t *testing.T) { for _, test := range sigTests { tx := buildTransaction() - tx["envelope_signatures"].([]map[string]any)[0][test.inputField] = test.inputValue + tx["envelope_signatures"].([]map[string]interface{})[0][test.inputField] = test.inputValue input := transactionToReader(tx) var transaction Transaction diff --git a/engine/access/rest/experimental/get_account_transactions.go b/engine/access/rest/experimental/get_account_transactions.go index d72f4317a61..48cc9e1f05d 100644 --- a/engine/access/rest/experimental/get_account_transactions.go +++ b/engine/access/rest/experimental/get_account_transactions.go @@ -39,7 +39,7 @@ type AccountTransactionFilter struct { } // GetAccountTransactions returns a paginated list of transactions for the given account address. -func GetAccountTransactions(r *common.Request, backend extended.API, link commonmodels.LinkGenerator) (any, error) { +func GetAccountTransactions(r *common.Request, backend extended.API, link commonmodels.LinkGenerator) (interface{}, error) { address, err := parser.ParseAddress(r.GetVar("address"), r.Chain) if err != nil { return nil, common.NewBadRequestError(err) @@ -67,8 +67,8 @@ func GetAccountTransactions(r *common.Request, backend extended.API, link common var filter extended.AccountTransactionFilter if raw := r.GetQueryParam("roles"); raw != "" { - roles := strings.SplitSeq(raw, ",") - for role := range roles { + roles := strings.Split(raw, ",") + for _, role := range roles { parsed, err := accessmodel.ParseTransactionRole(strings.TrimSpace(role)) if err != nil { return nil, common.NewBadRequestError(fmt.Errorf("invalid role: %w", err)) diff --git a/engine/access/rest/experimental/handler.go b/engine/access/rest/experimental/handler.go index 2c5a28d13d0..d8781be8219 100644 --- a/engine/access/rest/experimental/handler.go +++ b/engine/access/rest/experimental/handler.go @@ -13,7 +13,7 @@ import ( // ApiHandlerFunc is the handler function signature for experimental API endpoints. // It uses extended.API as the backend instead of access.API. -type ApiHandlerFunc func(r *common.Request, backend extended.API, link models.LinkGenerator) (any, error) +type ApiHandlerFunc func(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) // Handler wraps an ApiHandlerFunc with common HTTP handling (error handling, JSON responses). type Handler struct { diff --git a/engine/access/rest/experimental/routes/account_ft_transfers.go b/engine/access/rest/experimental/routes/account_ft_transfers.go index 920cb2d2345..454f44730fa 100644 --- a/engine/access/rest/experimental/routes/account_ft_transfers.go +++ b/engine/access/rest/experimental/routes/account_ft_transfers.go @@ -12,7 +12,7 @@ import ( ) // GetAccountFungibleTokenTransfers returns a paginated list of fungible token transfers for the given account address. -func GetAccountFungibleTokenTransfers(r *common.Request, backend extended.API, link models.LinkGenerator) (any, error) { +func GetAccountFungibleTokenTransfers(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { req, err := request.NewGetAccountFTTransfers(r) if err != nil { return nil, common.NewBadRequestError(err) diff --git a/engine/access/rest/experimental/routes/account_nft_transfers.go b/engine/access/rest/experimental/routes/account_nft_transfers.go index 85e2b1f47fe..adfc0572351 100644 --- a/engine/access/rest/experimental/routes/account_nft_transfers.go +++ b/engine/access/rest/experimental/routes/account_nft_transfers.go @@ -12,7 +12,7 @@ import ( ) // GetAccountNonFungibleTokenTransfers returns a paginated list of non-fungible token transfers for the given account address. -func GetAccountNonFungibleTokenTransfers(r *common.Request, backend extended.API, link models.LinkGenerator) (any, error) { +func GetAccountNonFungibleTokenTransfers(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { req, err := request.NewGetAccountNFTTransfers(r) if err != nil { return nil, common.NewBadRequestError(err) diff --git a/engine/access/rest/experimental/routes/account_transactions.go b/engine/access/rest/experimental/routes/account_transactions.go index 47ba723d78d..02a35f718f2 100644 --- a/engine/access/rest/experimental/routes/account_transactions.go +++ b/engine/access/rest/experimental/routes/account_transactions.go @@ -12,7 +12,7 @@ import ( ) // GetAccountTransactions returns a paginated list of transactions for the given account address. -func GetAccountTransactions(r *common.Request, backend extended.API, link models.LinkGenerator) (any, error) { +func GetAccountTransactions(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { req, err := request.NewGetAccountTransactions(r) if err != nil { return nil, common.NewBadRequestError(err) diff --git a/engine/access/rest/experimental/routes/contracts.go b/engine/access/rest/experimental/routes/contracts.go index a9ab987e740..28f41500683 100644 --- a/engine/access/rest/experimental/routes/contracts.go +++ b/engine/access/rest/experimental/routes/contracts.go @@ -13,7 +13,7 @@ import ( ) // GetContracts handles GET /experimental/v1/contracts. -func GetContracts(r *common.Request, backend extended.API, link models.LinkGenerator) (any, error) { +func GetContracts(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { req, err := request.NewGetContracts(r) if err != nil { return nil, common.NewBadRequestError(err) @@ -35,7 +35,7 @@ func GetContracts(r *common.Request, backend extended.API, link models.LinkGener } // GetContract handles GET /experimental/v1/contracts/{identifier}. -func GetContract(r *common.Request, backend extended.API, link models.LinkGenerator) (any, error) { +func GetContract(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { req, err := request.NewGetContract(r) if err != nil { return nil, common.NewBadRequestError(err) @@ -61,7 +61,7 @@ func GetContract(r *common.Request, backend extended.API, link models.LinkGenera } // GetContractDeployments handles GET /experimental/v1/contracts/{identifier}/deployments. -func GetContractDeployments(r *common.Request, backend extended.API, link models.LinkGenerator) (any, error) { +func GetContractDeployments(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { req, err := request.NewGetContractDeployments(r) if err != nil { return nil, common.NewBadRequestError(err) @@ -84,7 +84,7 @@ func GetContractDeployments(r *common.Request, backend extended.API, link models } // GetContractsByAddress handles GET /experimental/v1/accounts/{address}/contracts. -func GetContractsByAddress(r *common.Request, backend extended.API, link models.LinkGenerator) (any, error) { +func GetContractsByAddress(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { req, err := request.NewGetContractsByAddress(r) if err != nil { return nil, common.NewBadRequestError(err) diff --git a/engine/access/rest/experimental/routes/scheduled_transactions.go b/engine/access/rest/experimental/routes/scheduled_transactions.go index b05ef3bf610..ca06e60779e 100644 --- a/engine/access/rest/experimental/routes/scheduled_transactions.go +++ b/engine/access/rest/experimental/routes/scheduled_transactions.go @@ -13,7 +13,7 @@ import ( ) // GetScheduledTransactions handles GET /scheduled. -func GetScheduledTransactions(r *common.Request, backend extended.API, link models.LinkGenerator) (any, error) { +func GetScheduledTransactions(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { req, err := request.NewGetScheduledTransactions(r) if err != nil { return nil, common.NewBadRequestError(err) @@ -35,7 +35,7 @@ func GetScheduledTransactions(r *common.Request, backend extended.API, link mode } // GetScheduledTransaction handles GET /scheduled/transaction/{id}. -func GetScheduledTransaction(r *common.Request, backend extended.API, link models.LinkGenerator) (any, error) { +func GetScheduledTransaction(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { req, err := request.NewGetScheduledTransaction(r) if err != nil { return nil, common.NewBadRequestError(err) @@ -60,7 +60,7 @@ func GetScheduledTransaction(r *common.Request, backend extended.API, link model } // GetScheduledTransactionsByAddress handles GET /accounts/{address}/scheduled. -func GetScheduledTransactionsByAddress(r *common.Request, backend extended.API, link models.LinkGenerator) (any, error) { +func GetScheduledTransactionsByAddress(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { req, err := request.NewGetScheduledTransactionsByAddress(r) if err != nil { return nil, common.NewBadRequestError(err) diff --git a/engine/access/rest/http/routes/blocks_test.go b/engine/access/rest/http/routes/blocks_test.go index 45413fee617..7adb937c836 100644 --- a/engine/access/rest/http/routes/blocks_test.go +++ b/engine/access/rest/http/routes/blocks_test.go @@ -238,7 +238,7 @@ func generateMocks(backend *mock.API, count int) ([]string, []string, []*flow.Bl blocks := make([]*flow.Block, count) executionResults := make([]*flow.ExecutionResult, count) - for i := range count { + for i := 0; i < count; i++ { block := unittest.BlockFixture( unittest.Block.WithHeight(uint64(i + 1)), // avoiding edge case of height = 0 (genesis block) ) diff --git a/engine/access/rest/http/routes/collections_test.go b/engine/access/rest/http/routes/collections_test.go index a666f6bc084..aa9decf12a1 100644 --- a/engine/access/rest/http/routes/collections_test.go +++ b/engine/access/rest/http/routes/collections_test.go @@ -92,12 +92,12 @@ func TestGetCollections(t *testing.T) { // really hacky but we can't build whole response since it's really complex // so we just make sure the transactions are included and have defined values // anyhow we already test transaction responses in transaction tests - var res map[string]any + var res map[string]interface{} err := json.Unmarshal(rr.Body.Bytes(), &res) assert.NoError(t, err) - resTx := res["transactions"].([]any) + resTx := res["transactions"].([]interface{}) for i, r := range resTx { - c := r.(map[string]any) + c := r.(map[string]interface{}) assert.Equal(t, transactions[i].ID().String(), c["id"]) assert.NotNil(t, c["envelope_signatures"]) } diff --git a/engine/access/rest/http/routes/events_test.go b/engine/access/rest/http/routes/events_test.go index 535b5cefa02..dcaa1e01268 100644 --- a/engine/access/rest/http/routes/events_test.go +++ b/engine/access/rest/http/routes/events_test.go @@ -162,7 +162,7 @@ func generateEventsMocks(backend *mock.API, n int) []flow.BlockEvents { ids := make([]flow.Identifier, n) var lastHeader *flow.Header - for i := range n { + for i := 0; i < n; i++ { header := unittest.BlockHeaderFixture(unittest.WithHeaderHeight(uint64(i))) ids[i] = header.ID() diff --git a/engine/access/rest/http/routes/scripts_test.go b/engine/access/rest/http/routes/scripts_test.go index 017d8e09f1f..9f1c7da813d 100644 --- a/engine/access/rest/http/routes/scripts_test.go +++ b/engine/access/rest/http/routes/scripts_test.go @@ -19,7 +19,7 @@ import ( "github.com/onflow/flow-go/model/flow" ) -func scriptReq(id string, height string, body any) *http.Request { +func scriptReq(id string, height string, body interface{}) *http.Request { u, _ := url.ParseRequestURI("/v1/scripts") q := u.Query() @@ -41,7 +41,7 @@ func scriptReq(id string, height string, body any) *http.Request { func TestScripts(t *testing.T) { validCode := []byte(`access(all) fun main(foo: String): String { return foo }`) validArgs := []byte(`{ "type": "String", "value": "hello world" }`) - validBody := map[string]any{ + validBody := map[string]interface{}{ "script": util.ToBase64(validCode), "arguments": []string{util.ToBase64(validArgs)}, } @@ -114,7 +114,7 @@ func TestScripts(t *testing.T) { tests := []struct { id string height string - body map[string]any + body map[string]interface{} out string status int }{ diff --git a/engine/access/rest/http/routes/transactions_test.go b/engine/access/rest/http/routes/transactions_test.go index 71599906d71..ad2a7655c8b 100644 --- a/engine/access/rest/http/routes/transactions_test.go +++ b/engine/access/rest/http/routes/transactions_test.go @@ -115,7 +115,7 @@ func newGetTransactionResultsRequest(blockIdQuery string, height string) *http.R return req } -func newCreateTransactionRequest(body any) *http.Request { +func newCreateTransactionRequest(body interface{}) *http.Request { jsonBody, _ := json.Marshal(body) req, _ := http.NewRequest("POST", "/v1/transactions", bytes.NewBuffer(jsonBody)) return req diff --git a/engine/access/rest/websockets/connection.go b/engine/access/rest/websockets/connection.go index 346308a9027..5170e917e9f 100644 --- a/engine/access/rest/websockets/connection.go +++ b/engine/access/rest/websockets/connection.go @@ -7,8 +7,8 @@ import ( ) type WebsocketConnection interface { - ReadJSON(v any) error - WriteJSON(v any) error + ReadJSON(v interface{}) error + WriteJSON(v interface{}) error WriteControl(messageType int, deadline time.Time) error Close() error SetReadDeadline(deadline time.Time) error @@ -28,11 +28,11 @@ func NewWebsocketConnection(conn *websocket.Conn) *WebsocketConnectionImpl { var _ WebsocketConnection = (*WebsocketConnectionImpl)(nil) -func (c *WebsocketConnectionImpl) ReadJSON(v any) error { +func (c *WebsocketConnectionImpl) ReadJSON(v interface{}) error { return c.conn.ReadJSON(v) } -func (c *WebsocketConnectionImpl) WriteJSON(v any) error { +func (c *WebsocketConnectionImpl) WriteJSON(v interface{}) error { return c.conn.WriteJSON(v) } diff --git a/engine/access/rest/websockets/controller.go b/engine/access/rest/websockets/controller.go index 8fbae55fa3f..02401f77056 100644 --- a/engine/access/rest/websockets/controller.go +++ b/engine/access/rest/websockets/controller.go @@ -131,7 +131,7 @@ type Controller struct { // // This design ensures that the channel is only closed when it is safe to do so, avoiding // issues such as sending on a closed channel while maintaining proper cleanup. - multiplexedStream chan any + multiplexedStream chan interface{} dataProviders *concurrentmap.Map[SubscriptionID, dp.DataProvider] dataProviderFactory dp.DataProviderFactory @@ -162,7 +162,7 @@ func NewWebSocketController( logger: logger.With().Str("component", "websocket-controller").Logger(), config: config, conn: conn, - multiplexedStream: make(chan any), + multiplexedStream: make(chan interface{}), dataProviders: concurrentmap.New[SubscriptionID, dp.DataProvider](), dataProviderFactory: dataProviderFactory, dataProvidersGroup: &sync.WaitGroup{}, @@ -591,7 +591,7 @@ func (c *Controller) writeErrorResponse(ctx context.Context, err error, msg mode c.writeResponse(ctx, msg) } -func (c *Controller) writeResponse(ctx context.Context, response any) { +func (c *Controller) writeResponse(ctx context.Context, response interface{}) { select { case <-ctx.Done(): return diff --git a/engine/access/rest/websockets/controller_test.go b/engine/access/rest/websockets/controller_test.go index 4e1961a8792..14e90613613 100644 --- a/engine/access/rest/websockets/controller_test.go +++ b/engine/access/rest/websockets/controller_test.go @@ -100,7 +100,7 @@ func (s *WsControllerSuite) TestSubscribeRequest() { conn. On("WriteJSON", mock.Anything). - Return(func(msg any) error { + Return(func(msg interface{}) error { defer close(done) response, ok := msg.(models.SubscribeMessageResponse) @@ -149,7 +149,7 @@ func (s *WsControllerSuite) TestSubscribeRequest() { done := make(chan struct{}) conn. On("WriteJSON", mock.Anything). - Return(func(msg any) error { + Return(func(msg interface{}) error { defer close(done) response, ok := msg.(models.BaseMessageResponse) @@ -186,7 +186,7 @@ func (s *WsControllerSuite) TestSubscribeRequest() { conn. On("WriteJSON", mock.Anything). - Return(func(msg any) error { + Return(func(msg interface{}) error { defer close(done) response, ok := msg.(models.BaseMessageResponse) @@ -233,7 +233,7 @@ func (s *WsControllerSuite) TestSubscribeRequest() { conn. On("WriteJSON", mock.Anything). - Return(func(msg any) error { + Return(func(msg interface{}) error { defer close(done) response, ok := msg.(models.BaseMessageResponse) @@ -276,7 +276,7 @@ func (s *WsControllerSuite) TestGlobalStreamLimiter() { conn. On("WriteJSON", mock.Anything). - Return(func(msg any) error { + Return(func(msg interface{}) error { defer close(done) response, ok := msg.(models.BaseMessageResponse) @@ -322,7 +322,7 @@ func (s *WsControllerSuite) TestGlobalStreamLimiter() { conn. On("WriteJSON", mock.Anything). - Return(func(msg any) error { + Return(func(msg interface{}) error { defer close(done) response, ok := msg.(models.BaseMessageResponse) @@ -447,7 +447,7 @@ func (s *WsControllerSuite) TestUnsubscribeRequest() { conn. On("WriteJSON", mock.Anything). - Return(func(msg any) error { + Return(func(msg interface{}) error { defer close(done) response, ok := msg.(models.UnsubscribeMessageResponse) @@ -516,7 +516,7 @@ func (s *WsControllerSuite) TestUnsubscribeRequest() { conn. On("WriteJSON", mock.Anything). - Return(func(msg any) error { + Return(func(msg interface{}) error { defer close(done) response, ok := msg.(models.BaseMessageResponse) @@ -587,7 +587,7 @@ func (s *WsControllerSuite) TestUnsubscribeRequest() { conn. On("WriteJSON", mock.Anything). - Return(func(msg any) error { + Return(func(msg interface{}) error { defer close(done) response, ok := msg.(models.BaseMessageResponse) @@ -669,7 +669,7 @@ func (s *WsControllerSuite) TestListSubscriptions() { conn. On("WriteJSON", mock.Anything). - Return(func(msg any) error { + Return(func(msg interface{}) error { defer close(done) response, ok := msg.(models.ListSubscriptionsMessageResponse) @@ -731,7 +731,7 @@ func (s *WsControllerSuite) TestSubscribeBlocks() { var actualBlock flow.Block conn. On("WriteJSON", mock.Anything). - Return(func(msg any) error { + Return(func(msg interface{}) error { defer close(done) block, ok := msg.(flow.Block) @@ -790,7 +790,7 @@ func (s *WsControllerSuite) TestSubscribeBlocks() { // If we got to this point, the controller executed all its logic properly conn. On("WriteJSON", mock.Anything). - Return(func(msg any) error { + Return(func(msg interface{}) error { block, ok := msg.(flow.Block) require.True(t, ok) @@ -846,8 +846,8 @@ func (s *WsControllerSuite) TestRateLimiter() { // Step 3: Simulate sending messages to the controller's `multiplexedStream`. go func() { - for i := range totalMessages { - controller.multiplexedStream <- map[string]any{ + for i := 0; i < totalMessages; i++ { + controller.multiplexedStream <- map[string]interface{}{ "message": i, } } @@ -861,8 +861,8 @@ func (s *WsControllerSuite) TestRateLimiter() { timestamps = append(timestamps, time.Now()) // Extract the actual written message - actualMessage := args.Get(0).(map[string]any) - expectedMessage := map[string]any{"message": msgCounter} + actualMessage := args.Get(0).(map[string]interface{}) + expectedMessage := map[string]interface{}{"message": msgCounter} msgCounter++ assert.Equal(t, expectedMessage, actualMessage, "Received message does not match the expected message") @@ -928,7 +928,7 @@ func (s *WsControllerSuite) TestControllerShutdown() { conn. On("ReadJSON", mock.Anything). - Return(func(any) error { + Return(func(interface{}) error { <-done return &websocket.CloseError{Code: websocket.CloseNormalClosure} }). @@ -953,7 +953,7 @@ func (s *WsControllerSuite) TestControllerShutdown() { conn. On("ReadJSON", mock.Anything). - Return(func(_ any) error { + Return(func(_ interface{}) error { return &websocket.CloseError{Code: websocket.CloseNormalClosure} }). Once() @@ -992,7 +992,7 @@ func (s *WsControllerSuite) TestControllerShutdown() { conn. On("WriteJSON", mock.Anything). - Return(func(msg any) error { + Return(func(msg interface{}) error { close(done) return assert.AnError }) @@ -1045,7 +1045,7 @@ func (s *WsControllerSuite) TestControllerShutdown() { conn. On("ReadJSON", mock.Anything). - Return(func(any) error { + Return(func(interface{}) error { // make sure the reader routine sleeps for more time than InactivityTimeout + inactivity ticker period. // meanwhile, the writer routine must shut down the controller. <-time.After(wsConfig.InactivityTimeout + controller.inactivityTickerPeriod()*2) @@ -1087,7 +1087,7 @@ func (s *WsControllerSuite) TestKeepaliveRoutine() { }). Times(expectedCalls + 1) - conn.On("ReadJSON", mock.Anything).Return(func(_ any) error { + conn.On("ReadJSON", mock.Anything).Return(func(_ interface{}) error { <-done return &websocket.CloseError{Code: websocket.CloseNormalClosure} }) @@ -1113,7 +1113,8 @@ func (s *WsControllerSuite) TestKeepaliveRoutine() { require.NoError(t, err) controller.keepaliveConfig = keepaliveConfig - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() err = controller.keepalive(ctx) s.Require().Error(err) @@ -1132,7 +1133,8 @@ func (s *WsControllerSuite) TestKeepaliveRoutine() { require.NoError(t, err) controller.keepaliveConfig = keepaliveConfig - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() err = controller.keepalive(ctx) s.Require().Error(err) @@ -1212,7 +1214,7 @@ func (s *WsControllerSuite) expectCloseConnection(conn *connmock.WebsocketConnec // This call is optional because it is not needed in cases where readMessages exits promptly when the context is canceled. conn. On("ReadJSON", mock.Anything). - Return(func(msg any) error { + Return(func(msg interface{}) error { <-done return &websocket.CloseError{Code: websocket.CloseNormalClosure} }). diff --git a/engine/access/rest/websockets/data_providers/account_statuses_provider.go b/engine/access/rest/websockets/data_providers/account_statuses_provider.go index 2f2b081c18d..9ad67d9ad52 100644 --- a/engine/access/rest/websockets/data_providers/account_statuses_provider.go +++ b/engine/access/rest/websockets/data_providers/account_statuses_provider.go @@ -43,7 +43,7 @@ func NewAccountStatusesDataProvider( subscriptionID string, topic string, rawArguments wsmodels.Arguments, - send chan<- any, + send chan<- interface{}, chain flow.Chain, eventFilterConfig state_stream.EventFilterConfig, defaultHeartbeatInterval uint64, diff --git a/engine/access/rest/websockets/data_providers/account_statuses_provider_test.go b/engine/access/rest/websockets/data_providers/account_statuses_provider_test.go index 415e04d060b..aef1c3e14e1 100644 --- a/engine/access/rest/websockets/data_providers/account_statuses_provider_test.go +++ b/engine/access/rest/websockets/data_providers/account_statuses_provider_test.go @@ -82,8 +82,8 @@ func (s *AccountStatusesProviderSuite) TestAccountStatusesDataProvider_HappyPath AccountStatusesTopic, s.factory, s.subscribeAccountStatusesDataProviderTestCases(backendResponses), - func(dataChan chan any) { - for i := range backendResponses { + func(dataChan chan interface{}) { + for i := 0; i < len(backendResponses); i++ { dataChan <- backendResponses[i] } }, @@ -92,7 +92,7 @@ func (s *AccountStatusesProviderSuite) TestAccountStatusesDataProvider_HappyPath } func (s *AccountStatusesProviderSuite) TestAccountStatusesDataProvider_StateStreamNotConfigured() { - send := make(chan any) + send := make(chan interface{}) topic := AccountStatusesTopic provider, err := NewAccountStatusesDataProvider( @@ -171,7 +171,7 @@ func (s *AccountStatusesProviderSuite) subscribeAccountStatusesDataProviderTestC } // requireAccountStatuses ensures that the received account statuses information matches the expected data. -func (s *AccountStatusesProviderSuite) requireAccountStatuses(actual any, expected any) { +func (s *AccountStatusesProviderSuite) requireAccountStatuses(actual interface{}, expected interface{}) { expectedResponse, expectedResponsePayload := extractPayload[*models.AccountStatusesResponse](s.T(), expected) actualResponse, actualResponsePayload := extractPayload[*models.AccountStatusesResponse](s.T(), actual) @@ -190,8 +190,8 @@ func (s *AccountStatusesProviderSuite) requireAccountStatuses(actual any, expect } // expectedAccountStatusesResponses creates the expected responses for the provided events and backend responses. -func (s *AccountStatusesProviderSuite) expectedAccountStatusesResponses(backendResponses []*backend.AccountStatusesResponse) []any { - expectedResponses := make([]any, len(backendResponses)) +func (s *AccountStatusesProviderSuite) expectedAccountStatusesResponses(backendResponses []*backend.AccountStatusesResponse) []interface{} { + expectedResponses := make([]interface{}, len(backendResponses)) for i, resp := range backendResponses { // avoid updating the original response @@ -226,7 +226,7 @@ func (s *AccountStatusesProviderSuite) expectedAccountStatusesResponses(backendR // when invalid arguments are provided. It verifies that appropriate errors are returned // for missing or conflicting arguments. func (s *AccountStatusesProviderSuite) TestAccountStatusesDataProvider_InvalidArguments() { - send := make(chan any) + send := make(chan interface{}) topic := AccountStatusesTopic for _, test := range invalidAccountStatusesArgumentsTestCases() { @@ -252,22 +252,22 @@ func (s *AccountStatusesProviderSuite) TestAccountStatusesDataProvider_InvalidAr // TestMessageIndexAccountStatusesProviderResponse_HappyPath tests that MessageIndex values in response are strictly increasing. func (s *AccountStatusesProviderSuite) TestMessageIndexAccountStatusesProviderResponse_HappyPath() { - send := make(chan any, 10) + send := make(chan interface{}, 10) topic := AccountStatusesTopic accountStatusesCount := 4 // Create a channel to simulate the subscription's account statuses channel - accountStatusesChan := make(chan any) + accountStatusesChan := make(chan interface{}) // Create a mock subscription and mock the channel sub := submock.NewSubscription(s.T()) - sub.On("Channel").Return((<-chan any)(accountStatusesChan)) + sub.On("Channel").Return((<-chan interface{})(accountStatusesChan)) sub.On("Err").Return(nil).Once() s.api.On("SubscribeAccountStatusesFromStartBlockID", mock.Anything, mock.Anything, mock.Anything).Return(sub) arguments := - map[string]any{ + map[string]interface{}{ "start_block_id": s.rootBlock.ID().String(), "event_types": []string{string(flow.EventAccountCreated)}, "account_addresses": []string{unittest.AddressFixture().String()}, @@ -304,14 +304,14 @@ func (s *AccountStatusesProviderSuite) TestMessageIndexAccountStatusesProviderRe go func() { defer close(accountStatusesChan) // Close the channel when done - for range accountStatusesCount { + for i := 0; i < accountStatusesCount; i++ { accountStatusesChan <- &backend.AccountStatusesResponse{} } }() // Collect responses var responses []*models.AccountStatusesResponse - for range accountStatusesCount { + for i := 0; i < accountStatusesCount; i++ { res := <-send _, accStatusesResponsePayload := extractPayload[*models.AccountStatusesResponse](s.T(), res) @@ -364,7 +364,7 @@ func invalidAccountStatusesArgumentsTestCases() []testErrType { }, { name: "invalid 'start_block_id' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "start_block_id": "invalid_block_id", "event_types": []string{state_stream.CoreEventAccountCreated}, "account_addresses": []string{unittest.AddressFixture().String()}, @@ -373,7 +373,7 @@ func invalidAccountStatusesArgumentsTestCases() []testErrType { }, { name: "invalid 'start_block_height' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "start_block_height": "-1", "event_types": []string{state_stream.CoreEventAccountCreated}, "account_addresses": []string{unittest.AddressFixture().String()}, @@ -382,7 +382,7 @@ func invalidAccountStatusesArgumentsTestCases() []testErrType { }, { name: "invalid 'heartbeat_interval' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "start_block_id": unittest.BlockFixture().ID().String(), "event_types": []string{state_stream.CoreEventAccountCreated}, "account_addresses": []string{unittest.AddressFixture().String()}, @@ -392,7 +392,7 @@ func invalidAccountStatusesArgumentsTestCases() []testErrType { }, { name: "unexpected argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "start_block_id": unittest.BlockFixture().ID().String(), "event_types": []string{state_stream.CoreEventAccountCreated}, "account_addresses": []string{unittest.AddressFixture().String()}, diff --git a/engine/access/rest/websockets/data_providers/args_validation.go b/engine/access/rest/websockets/data_providers/args_validation.go index 7c316c5406c..831801cdff4 100644 --- a/engine/access/rest/websockets/data_providers/args_validation.go +++ b/engine/access/rest/websockets/data_providers/args_validation.go @@ -8,7 +8,7 @@ import ( "github.com/onflow/flow-go/engine/access/rest/websockets/models" ) -func ensureAllowedFields(fields map[string]any, allowedFields map[string]struct{}) error { +func ensureAllowedFields(fields map[string]interface{}, allowedFields map[string]struct{}) error { // Ensure only allowed fields are present for key := range fields { if _, exists := allowedFields[key]; !exists { diff --git a/engine/access/rest/websockets/data_providers/base_provider.go b/engine/access/rest/websockets/data_providers/base_provider.go index 108bb1196e0..6d6e55bb49d 100644 --- a/engine/access/rest/websockets/data_providers/base_provider.go +++ b/engine/access/rest/websockets/data_providers/base_provider.go @@ -20,7 +20,7 @@ type baseDataProvider struct { subscriptionID string topic string rawArguments wsmodels.Arguments - send chan<- any + send chan<- interface{} cancelSubscriptionContext context.CancelFunc } @@ -32,7 +32,7 @@ func newBaseDataProvider( subscriptionID string, topic string, rawArguments wsmodels.Arguments, - send chan<- any, + send chan<- interface{}, ) *baseDataProvider { ctx, cancel := context.WithCancel(ctx) return &baseDataProvider{ diff --git a/engine/access/rest/websockets/data_providers/block_digests_provider.go b/engine/access/rest/websockets/data_providers/block_digests_provider.go index 81bfc10bcf7..123ad6ac452 100644 --- a/engine/access/rest/websockets/data_providers/block_digests_provider.go +++ b/engine/access/rest/websockets/data_providers/block_digests_provider.go @@ -31,7 +31,7 @@ func NewBlockDigestsDataProvider( subscriptionID string, topic string, rawArguments wsmodels.Arguments, - send chan<- any, + send chan<- interface{}, ) (*BlockDigestsDataProvider, error) { args, err := parseBlocksArguments(rawArguments) if err != nil { diff --git a/engine/access/rest/websockets/data_providers/block_digests_provider_test.go b/engine/access/rest/websockets/data_providers/block_digests_provider_test.go index a149538b455..7f75d7244f9 100644 --- a/engine/access/rest/websockets/data_providers/block_digests_provider_test.go +++ b/engine/access/rest/websockets/data_providers/block_digests_provider_test.go @@ -39,7 +39,7 @@ func (s *BlockDigestsProviderSuite) TestBlockDigestsDataProvider_HappyPath() { BlockDigestsTopic, s.factory, s.validBlockDigestsArgumentsTestCases(), - func(dataChan chan any) { + func(dataChan chan interface{}) { for _, block := range s.blocks { dataChan <- flow.NewBlockDigest(block.ID(), block.Height, time.UnixMilli(int64(block.Timestamp)).UTC()) } @@ -51,7 +51,7 @@ func (s *BlockDigestsProviderSuite) TestBlockDigestsDataProvider_HappyPath() { // validBlockDigestsArgumentsTestCases defines test happy cases for block digests data providers. // Each test case specifies input arguments, and setup functions for the mock API used in the test. func (s *BlockDigestsProviderSuite) validBlockDigestsArgumentsTestCases() []testType { - expectedResponses := make([]any, len(s.blocks)) + expectedResponses := make([]interface{}, len(s.blocks)) for i, b := range s.blocks { blockDigest := flow.NewBlockDigest(b.ID(), b.Height, time.UnixMilli(int64(b.Timestamp)).UTC()) blockDigestPayload := models.NewBlockDigest(blockDigest) @@ -112,7 +112,7 @@ func (s *BlockDigestsProviderSuite) validBlockDigestsArgumentsTestCases() []test } // requireBlockDigest ensures that the received block header information matches the expected data. -func (s *BlocksProviderSuite) requireBlockDigest(actual any, expected any) { +func (s *BlocksProviderSuite) requireBlockDigest(actual interface{}, expected interface{}) { expectedResponse, expectedResponsePayload := extractPayload[*models.BlockDigest](s.T(), expected) actualResponse, actualResponsePayload := extractPayload[*models.BlockDigest](s.T(), actual) @@ -124,7 +124,7 @@ func (s *BlocksProviderSuite) requireBlockDigest(actual any, expected any) { // when invalid arguments are provided. It verifies that appropriate errors are returned // for missing or conflicting arguments. func (s *BlockDigestsProviderSuite) TestBlockDigestsDataProvider_InvalidArguments() { - send := make(chan any) + send := make(chan interface{}) topic := BlockDigestsTopic diff --git a/engine/access/rest/websockets/data_providers/block_headers_provider.go b/engine/access/rest/websockets/data_providers/block_headers_provider.go index 07b920a1065..8e5eb4159fb 100644 --- a/engine/access/rest/websockets/data_providers/block_headers_provider.go +++ b/engine/access/rest/websockets/data_providers/block_headers_provider.go @@ -32,7 +32,7 @@ func NewBlockHeadersDataProvider( subscriptionID string, topic string, rawArguments wsmodels.Arguments, - send chan<- any, + send chan<- interface{}, ) (*BlockHeadersDataProvider, error) { args, err := parseBlocksArguments(rawArguments) if err != nil { diff --git a/engine/access/rest/websockets/data_providers/block_headers_provider_test.go b/engine/access/rest/websockets/data_providers/block_headers_provider_test.go index 9b32fc5ddda..b834ebaf609 100644 --- a/engine/access/rest/websockets/data_providers/block_headers_provider_test.go +++ b/engine/access/rest/websockets/data_providers/block_headers_provider_test.go @@ -39,7 +39,7 @@ func (s *BlockHeadersProviderSuite) TestBlockHeadersDataProvider_HappyPath() { BlockHeadersTopic, s.factory, s.validBlockHeadersArgumentsTestCases(), - func(dataChan chan any) { + func(dataChan chan interface{}) { for _, block := range s.blocks { dataChan <- block.ToHeader() } @@ -51,7 +51,7 @@ func (s *BlockHeadersProviderSuite) TestBlockHeadersDataProvider_HappyPath() { // validBlockHeadersArgumentsTestCases defines test happy cases for block headers data providers. // Each test case specifies input arguments, and setup functions for the mock API used in the test. func (s *BlockHeadersProviderSuite) validBlockHeadersArgumentsTestCases() []testType { - expectedResponses := make([]any, len(s.blocks)) + expectedResponses := make([]interface{}, len(s.blocks)) for i, b := range s.blocks { var header commonmodels.BlockHeader header.Build(b.ToHeader()) @@ -113,7 +113,7 @@ func (s *BlockHeadersProviderSuite) validBlockHeadersArgumentsTestCases() []test } // requireBlockHeaders ensures that the received block header information matches the expected data. -func (s *BlockHeadersProviderSuite) requireBlockHeader(actual any, expected any) { +func (s *BlockHeadersProviderSuite) requireBlockHeader(actual interface{}, expected interface{}) { expectedResponse, expectedResponsePayload := extractPayload[*commonmodels.BlockHeader](s.T(), expected) actualResponse, actualResponsePayload := extractPayload[*commonmodels.BlockHeader](s.T(), actual) @@ -125,7 +125,7 @@ func (s *BlockHeadersProviderSuite) requireBlockHeader(actual any, expected any) // when invalid arguments are provided. It verifies that appropriate errors are returned // for missing or conflicting arguments. func (s *BlockHeadersProviderSuite) TestBlockHeadersDataProvider_InvalidArguments() { - send := make(chan any) + send := make(chan interface{}) topic := BlockHeadersTopic for _, test := range s.invalidArgumentsTestCases() { diff --git a/engine/access/rest/websockets/data_providers/blocks_provider.go b/engine/access/rest/websockets/data_providers/blocks_provider.go index d797cc7c23a..9368f2e17df 100644 --- a/engine/access/rest/websockets/data_providers/blocks_provider.go +++ b/engine/access/rest/websockets/data_providers/blocks_provider.go @@ -43,7 +43,7 @@ func NewBlocksDataProvider( linkGenerator commonmodels.LinkGenerator, topic string, rawArguments wsmodels.Arguments, - send chan<- any, + send chan<- interface{}, ) (*BlocksDataProvider, error) { args, err := parseBlocksArguments(rawArguments) if err != nil { diff --git a/engine/access/rest/websockets/data_providers/blocks_provider_test.go b/engine/access/rest/websockets/data_providers/blocks_provider_test.go index 2c4c7c2147d..5b51613677c 100644 --- a/engine/access/rest/websockets/data_providers/blocks_provider_test.go +++ b/engine/access/rest/websockets/data_providers/blocks_provider_test.go @@ -56,7 +56,7 @@ func (s *BlocksProviderSuite) SetupTest() { s.rootBlock = unittest.Block.Genesis(flow.Emulator) parent := s.rootBlock.ToHeader() - for range blockCount { + for i := 0; i < blockCount; i++ { transaction := unittest.TransactionBodyFixture() col := unittest.CollectionFromTransactions(&transaction) guarantee := &flow.CollectionGuarantee{CollectionID: col.ID()} @@ -103,7 +103,7 @@ func (s *BlocksProviderSuite) TestBlocksDataProvider_HappyPath() { BlocksTopic, s.factory, s.validBlockArgumentsTestCases(), - func(dataChan chan any) { + func(dataChan chan interface{}) { for _, block := range s.blocks { dataChan <- block } @@ -182,7 +182,7 @@ func (s *BlocksProviderSuite) validBlockArgumentsTestCases() []testType { } // requireBlock ensures that the received block information matches the expected data. -func (s *BlocksProviderSuite) requireBlock(actual any, expected any) { +func (s *BlocksProviderSuite) requireBlock(actual interface{}, expected interface{}) { expectedResponse, expectedResponsePayload := extractPayload[*commonmodels.Block](s.T(), expected) actualResponse, actualResponsePayload := extractPayload[*commonmodels.Block](s.T(), actual) @@ -195,8 +195,8 @@ func (s *BlocksProviderSuite) expectedBlockResponses( blocks []*flow.Block, expand map[string]bool, status flow.BlockStatus, -) []any { - responses := make([]any, len(blocks)) +) []interface{} { + responses := make([]interface{}, len(blocks)) for i, b := range blocks { var block commonmodels.Block err := block.Build(b, nil, s.linkGenerator, status, expand) @@ -215,7 +215,7 @@ func (s *BlocksProviderSuite) expectedBlockResponses( // when invalid arguments are provided. It verifies that appropriate errors are returned // for missing or conflicting arguments. func (s *BlocksProviderSuite) TestBlocksDataProvider_InvalidArguments() { - send := make(chan any) + send := make(chan interface{}) for _, test := range s.invalidArgumentsTestCases() { s.Run(test.name, func() { @@ -257,7 +257,7 @@ func (s *BlocksProviderSuite) invalidArgumentsTestCases() []testErrType { }, { name: "unexpected argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "block_status": parser.Finalized, "start_block_id": unittest.BlockFixture().ID().String(), "unexpected_argument": "dummy", diff --git a/engine/access/rest/websockets/data_providers/events_provider.go b/engine/access/rest/websockets/data_providers/events_provider.go index 11f460e6364..7b2f933c285 100644 --- a/engine/access/rest/websockets/data_providers/events_provider.go +++ b/engine/access/rest/websockets/data_providers/events_provider.go @@ -45,7 +45,7 @@ func NewEventsDataProvider( subscriptionID string, topic string, rawArguments wsmodels.Arguments, - send chan<- any, + send chan<- interface{}, chain flow.Chain, eventFilterConfig state_stream.EventFilterConfig, defaultHeartbeatInterval uint64, diff --git a/engine/access/rest/websockets/data_providers/events_provider_test.go b/engine/access/rest/websockets/data_providers/events_provider_test.go index 9a0554dc77a..88ef6a67c13 100644 --- a/engine/access/rest/websockets/data_providers/events_provider_test.go +++ b/engine/access/rest/websockets/data_providers/events_provider_test.go @@ -77,8 +77,8 @@ func (s *EventsProviderSuite) TestEventsDataProvider_HappyPath() { EventsTopic, s.factory, s.subscribeEventsDataProviderTestCases(backendResponses), - func(dataChan chan any) { - for i := range backendResponses { + func(dataChan chan interface{}) { + for i := 0; i < len(backendResponses); i++ { dataChan <- backendResponses[i] } }, @@ -150,7 +150,7 @@ func (s *EventsProviderSuite) subscribeEventsDataProviderTestCases(backendRespon } // requireEvents ensures that the received event information matches the expected data. -func (s *EventsProviderSuite) requireEvents(actual any, expected any) { +func (s *EventsProviderSuite) requireEvents(actual interface{}, expected interface{}) { expectedResponse, expectedResponsePayload := extractPayload[*models.EventResponse](s.T(), expected) actualResponse, actualResponsePayload := extractPayload[*models.EventResponse](s.T(), actual) @@ -178,8 +178,8 @@ func (s *EventsProviderSuite) backendEventsResponses(events []flow.Event) []*bac // expectedEventsResponses creates the expected responses for the provided backend responses. func (s *EventsProviderSuite) expectedEventsResponses( backendResponses []*backend.EventsResponse, -) []any { - expectedResponses := make([]any, len(backendResponses)) +) []interface{} { + expectedResponses := make([]interface{}, len(backendResponses)) for i, resp := range backendResponses { // avoid updating the original response @@ -209,22 +209,22 @@ func (s *EventsProviderSuite) expectedEventsResponses( // TestMessageIndexEventProviderResponse_HappyPath tests that MessageIndex values in response are strictly increasing. func (s *EventsProviderSuite) TestMessageIndexEventProviderResponse_HappyPath() { - send := make(chan any, 10) + send := make(chan interface{}, 10) topic := EventsTopic eventsCount := 4 // Create a channel to simulate the subscription's event channel - eventChan := make(chan any) + eventChan := make(chan interface{}) // Create a mock subscription and mock the channel sub := submock.NewSubscription(s.T()) - sub.On("Channel").Return((<-chan any)(eventChan)) + sub.On("Channel").Return((<-chan interface{})(eventChan)) sub.On("Err").Return(nil).Once() s.api.On("SubscribeEventsFromStartBlockID", mock.Anything, mock.Anything, mock.Anything).Return(sub) arguments := - map[string]any{ + map[string]interface{}{ "start_block_id": s.rootBlock.ID().String(), "event_types": []string{state_stream.CoreEventAccountCreated}, "addresses": []string{unittest.AddressFixture().String()}, @@ -263,7 +263,7 @@ func (s *EventsProviderSuite) TestMessageIndexEventProviderResponse_HappyPath() go func() { defer close(eventChan) // Close the channel when done - for range eventsCount { + for i := 0; i < eventsCount; i++ { eventChan <- &backend.EventsResponse{ Height: s.rootBlock.Height, } @@ -272,7 +272,7 @@ func (s *EventsProviderSuite) TestMessageIndexEventProviderResponse_HappyPath() // Collect responses var responses []*models.EventResponse - for range eventsCount { + for i := 0; i < eventsCount; i++ { res := <-send _, eventResData := extractPayload[*models.EventResponse](s.T(), res) @@ -302,7 +302,7 @@ func (s *EventsProviderSuite) TestMessageIndexEventProviderResponse_HappyPath() // 2. Invalid 'start_block_id' argument. // 3. Invalid 'start_block_height' argument. func (s *EventsProviderSuite) TestEventsDataProvider_InvalidArguments() { - send := make(chan any) + send := make(chan interface{}) topic := EventsTopic for _, test := range invalidEventsArgumentsTestCases() { @@ -327,7 +327,7 @@ func (s *EventsProviderSuite) TestEventsDataProvider_InvalidArguments() { } func (s *EventsProviderSuite) TestEventsDataProvider_StateStreamNotConfigured() { - send := make(chan any) + send := make(chan interface{}) topic := EventsTopic provider, err := NewEventsDataProvider( @@ -365,7 +365,7 @@ func invalidEventsArgumentsTestCases() []testErrType { }, { name: "invalid 'start_block_id' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "start_block_id": "invalid_block_id", "event_types": []string{state_stream.CoreEventAccountCreated}, "addresses": []string{unittest.AddressFixture().String()}, @@ -375,7 +375,7 @@ func invalidEventsArgumentsTestCases() []testErrType { }, { name: "invalid 'start_block_height' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "start_block_height": "-1", "event_types": []string{state_stream.CoreEventAccountCreated}, "addresses": []string{unittest.AddressFixture().String()}, @@ -385,7 +385,7 @@ func invalidEventsArgumentsTestCases() []testErrType { }, { name: "invalid 'heartbeat_interval' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "start_block_id": unittest.BlockFixture().ID().String(), "event_types": []string{state_stream.CoreEventAccountCreated}, "addresses": []string{unittest.AddressFixture().String()}, @@ -396,7 +396,7 @@ func invalidEventsArgumentsTestCases() []testErrType { }, { name: "unexpected argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "start_block_id": unittest.BlockFixture().ID().String(), "event_types": []string{state_stream.CoreEventAccountCreated}, "addresses": []string{unittest.AddressFixture().String()}, diff --git a/engine/access/rest/websockets/data_providers/factory.go b/engine/access/rest/websockets/data_providers/factory.go index d654706ec55..e612549611a 100644 --- a/engine/access/rest/websockets/data_providers/factory.go +++ b/engine/access/rest/websockets/data_providers/factory.go @@ -33,7 +33,7 @@ type DataProviderFactory interface { // and configuration parameters. // // No errors are expected during normal operations. - NewDataProvider(ctx context.Context, subID string, topic string, args wsmodels.Arguments, stream chan<- any) (DataProvider, error) + NewDataProvider(ctx context.Context, subID string, topic string, args wsmodels.Arguments, stream chan<- interface{}) (DataProvider, error) } var _ DataProviderFactory = (*DataProviderFactoryImpl)(nil) @@ -91,7 +91,7 @@ func NewDataProviderFactory( // - ch: Channel to which the data provider sends data. // // No errors are expected during normal operations. -func (s *DataProviderFactoryImpl) NewDataProvider(ctx context.Context, subscriptionID string, topic string, arguments wsmodels.Arguments, ch chan<- any) (DataProvider, error) { +func (s *DataProviderFactoryImpl) NewDataProvider(ctx context.Context, subscriptionID string, topic string, arguments wsmodels.Arguments, ch chan<- interface{}) (DataProvider, error) { switch topic { case BlocksTopic: return NewBlocksDataProvider(ctx, s.logger, s.accessApi, subscriptionID, s.linkGenerator, topic, arguments, ch) diff --git a/engine/access/rest/websockets/data_providers/factory_test.go b/engine/access/rest/websockets/data_providers/factory_test.go index 2eabb7f2a3d..dd5ed485179 100644 --- a/engine/access/rest/websockets/data_providers/factory_test.go +++ b/engine/access/rest/websockets/data_providers/factory_test.go @@ -24,7 +24,7 @@ type DataProviderFactorySuite struct { suite.Suite ctx context.Context - ch chan any + ch chan interface{} accessApi *accessmock.API stateStreamApi *ssmock.API @@ -44,7 +44,7 @@ func (s *DataProviderFactorySuite) SetupTest() { s.accessApi = accessmock.NewAPI(s.T()) s.ctx = context.Background() - s.ch = make(chan any) + s.ch = make(chan interface{}) s.factory = NewDataProviderFactory( log, diff --git a/engine/access/rest/websockets/data_providers/mock/data_provider_factory.go b/engine/access/rest/websockets/data_providers/mock/data_provider_factory.go index 34ff85b5d49..8ad7275f4eb 100644 --- a/engine/access/rest/websockets/data_providers/mock/data_provider_factory.go +++ b/engine/access/rest/websockets/data_providers/mock/data_provider_factory.go @@ -40,7 +40,7 @@ func (_m *DataProviderFactory) EXPECT() *DataProviderFactory_Expecter { } // NewDataProvider provides a mock function for the type DataProviderFactory -func (_mock *DataProviderFactory) NewDataProvider(ctx context.Context, subID string, topic string, args models.Arguments, stream chan<- any) (data_providers.DataProvider, error) { +func (_mock *DataProviderFactory) NewDataProvider(ctx context.Context, subID string, topic string, args models.Arguments, stream chan<- interface{}) (data_providers.DataProvider, error) { ret := _mock.Called(ctx, subID, topic, args, stream) if len(ret) == 0 { @@ -49,17 +49,17 @@ func (_mock *DataProviderFactory) NewDataProvider(ctx context.Context, subID str var r0 data_providers.DataProvider var r1 error - if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, models.Arguments, chan<- any) (data_providers.DataProvider, error)); ok { + if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, models.Arguments, chan<- interface{}) (data_providers.DataProvider, error)); ok { return returnFunc(ctx, subID, topic, args, stream) } - if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, models.Arguments, chan<- any) data_providers.DataProvider); ok { + if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, models.Arguments, chan<- interface{}) data_providers.DataProvider); ok { r0 = returnFunc(ctx, subID, topic, args, stream) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(data_providers.DataProvider) } } - if returnFunc, ok := ret.Get(1).(func(context.Context, string, string, models.Arguments, chan<- any) error); ok { + if returnFunc, ok := ret.Get(1).(func(context.Context, string, string, models.Arguments, chan<- interface{}) error); ok { r1 = returnFunc(ctx, subID, topic, args, stream) } else { r1 = ret.Error(1) @@ -77,12 +77,12 @@ type DataProviderFactory_NewDataProvider_Call struct { // - subID string // - topic string // - args models.Arguments -// - stream chan<- any +// - stream chan<- interface{} func (_e *DataProviderFactory_Expecter) NewDataProvider(ctx interface{}, subID interface{}, topic interface{}, args interface{}, stream interface{}) *DataProviderFactory_NewDataProvider_Call { return &DataProviderFactory_NewDataProvider_Call{Call: _e.mock.On("NewDataProvider", ctx, subID, topic, args, stream)} } -func (_c *DataProviderFactory_NewDataProvider_Call) Run(run func(ctx context.Context, subID string, topic string, args models.Arguments, stream chan<- any)) *DataProviderFactory_NewDataProvider_Call { +func (_c *DataProviderFactory_NewDataProvider_Call) Run(run func(ctx context.Context, subID string, topic string, args models.Arguments, stream chan<- interface{})) *DataProviderFactory_NewDataProvider_Call { _c.Call.Run(func(args mock.Arguments) { var arg0 context.Context if args[0] != nil { @@ -100,9 +100,9 @@ func (_c *DataProviderFactory_NewDataProvider_Call) Run(run func(ctx context.Con if args[3] != nil { arg3 = args[3].(models.Arguments) } - var arg4 chan<- any + var arg4 chan<- interface{} if args[4] != nil { - arg4 = args[4].(chan<- any) + arg4 = args[4].(chan<- interface{}) } run( arg0, @@ -120,7 +120,7 @@ func (_c *DataProviderFactory_NewDataProvider_Call) Return(dataProvider data_pro return _c } -func (_c *DataProviderFactory_NewDataProvider_Call) RunAndReturn(run func(ctx context.Context, subID string, topic string, args models.Arguments, stream chan<- any) (data_providers.DataProvider, error)) *DataProviderFactory_NewDataProvider_Call { +func (_c *DataProviderFactory_NewDataProvider_Call) RunAndReturn(run func(ctx context.Context, subID string, topic string, args models.Arguments, stream chan<- interface{}) (data_providers.DataProvider, error)) *DataProviderFactory_NewDataProvider_Call { _c.Call.Return(run) return _c } diff --git a/engine/access/rest/websockets/data_providers/models/base_data_provider.go b/engine/access/rest/websockets/data_providers/models/base_data_provider.go index 8b7d3c507ae..31fd72a7380 100644 --- a/engine/access/rest/websockets/data_providers/models/base_data_provider.go +++ b/engine/access/rest/websockets/data_providers/models/base_data_provider.go @@ -2,7 +2,7 @@ package models // BaseDataProvidersResponse represents a base structure for responses from subscriptions. type BaseDataProvidersResponse struct { - SubscriptionID string `json:"subscription_id"` // Unique subscriptionID - Topic string `json:"topic"` // Topic of the subscription - Payload any `json:"payload"` // Payload that's being returned within a subscription. + SubscriptionID string `json:"subscription_id"` // Unique subscriptionID + Topic string `json:"topic"` // Topic of the subscription + Payload interface{} `json:"payload"` // Payload that's being returned within a subscription. } diff --git a/engine/access/rest/websockets/data_providers/send_and_get_transaction_statuses_provider.go b/engine/access/rest/websockets/data_providers/send_and_get_transaction_statuses_provider.go index ee7d4299e00..9ae1839c01c 100644 --- a/engine/access/rest/websockets/data_providers/send_and_get_transaction_statuses_provider.go +++ b/engine/access/rest/websockets/data_providers/send_and_get_transaction_statuses_provider.go @@ -44,7 +44,7 @@ func NewSendAndGetTransactionStatusesDataProvider( linkGenerator commonmodels.LinkGenerator, topic string, rawArguments wsmodels.Arguments, - send chan<- any, + send chan<- interface{}, chain flow.Chain, ) (*SendAndGetTransactionStatusesDataProvider, error) { args, err := parseSendAndGetTransactionStatusesArguments(rawArguments, chain) diff --git a/engine/access/rest/websockets/data_providers/send_and_get_transaction_statuses_provider_test.go b/engine/access/rest/websockets/data_providers/send_and_get_transaction_statuses_provider_test.go index 43f53c71f58..3e17f49bed3 100644 --- a/engine/access/rest/websockets/data_providers/send_and_get_transaction_statuses_provider_test.go +++ b/engine/access/rest/websockets/data_providers/send_and_get_transaction_statuses_provider_test.go @@ -101,7 +101,7 @@ func (s *TransactionStatusesProviderSuite) TestSendTransactionStatusesDataProvid SendAndGetTransactionStatusesTopic, s.factory, sendTxStatutesTestCases, - func(dataChan chan any) { + func(dataChan chan interface{}) { dataChan <- backendResponse }, s.requireTransactionStatuses, @@ -110,8 +110,8 @@ func (s *TransactionStatusesProviderSuite) TestSendTransactionStatusesDataProvid // requireTransactionStatuses ensures that the received transaction statuses information matches the expected data. func (s *SendTransactionStatusesProviderSuite) requireTransactionStatuses( - actual any, - expected any, + actual interface{}, + expected interface{}, ) { expectedResponse, expectedResponsePayload := extractPayload[*models.TransactionStatusesResponse](s.T(), expected) actualResponse, actualResponsePayload := extractPayload[*models.TransactionStatusesResponse](s.T(), actual) @@ -124,7 +124,7 @@ func (s *SendTransactionStatusesProviderSuite) requireTransactionStatuses( // when invalid arguments are provided. It verifies that appropriate errors are returned // for missing or conflicting arguments. func (s *SendTransactionStatusesProviderSuite) TestSendTransactionStatusesDataProvider_InvalidArguments() { - send := make(chan any) + send := make(chan interface{}) topic := SendAndGetTransactionStatusesTopic for _, test := range invalidSendTransactionStatusesArgumentsTestCases() { @@ -154,84 +154,84 @@ func invalidSendTransactionStatusesArgumentsTestCases() []testErrType { return []testErrType{ { name: "invalid 'script' argument type", - arguments: map[string]any{ + arguments: map[string]interface{}{ "script": 0, }, expectedErrorMsg: "failed to parse transaction", }, { name: "invalid 'script' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "script": "invalid_script", }, expectedErrorMsg: "failed to parse transaction", }, { name: "invalid 'arguments' type", - arguments: map[string]any{ + arguments: map[string]interface{}{ "arguments": 0, }, expectedErrorMsg: "failed to parse transaction", }, { name: "invalid 'arguments' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "arguments": []string{"invalid_base64_1", "invalid_base64_2"}, }, expectedErrorMsg: "failed to parse transaction", }, { name: "invalid 'reference_block_id' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "reference_block_id": "invalid_reference_block_id", }, expectedErrorMsg: "failed to parse transaction", }, { name: "invalid 'gas_limit' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "gas_limit": "-1", }, expectedErrorMsg: "failed to parse transaction", }, { name: "invalid 'payer' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "payer": "invalid_payer", }, expectedErrorMsg: "failed to parse transaction", }, { name: "invalid 'proposal_key' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "proposal_key": "invalid ProposalKey object", }, expectedErrorMsg: "failed to parse transaction", }, { name: "invalid 'authorizers' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "authorizers": []string{"invalid_base64_1", "invalid_base64_2"}, }, expectedErrorMsg: "failed to parse transaction", }, { name: "invalid 'payload_signatures' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "payload_signatures": "invalid TransactionSignature array", }, expectedErrorMsg: "failed to parse transaction", }, { name: "invalid 'envelope_signatures' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "envelope_signatures": "invalid TransactionSignature array", }, expectedErrorMsg: "failed to parse transaction", }, { name: "unexpected argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "unexpected_argument": "dummy", }, expectedErrorMsg: "request body contains unknown field", diff --git a/engine/access/rest/websockets/data_providers/transaction_statuses_provider.go b/engine/access/rest/websockets/data_providers/transaction_statuses_provider.go index a2fde7a7a67..81770055fe6 100644 --- a/engine/access/rest/websockets/data_providers/transaction_statuses_provider.go +++ b/engine/access/rest/websockets/data_providers/transaction_statuses_provider.go @@ -43,7 +43,7 @@ func NewTransactionStatusesDataProvider( linkGenerator commonmodels.LinkGenerator, topic string, rawArguments wsmodels.Arguments, - send chan<- any, + send chan<- interface{}, ) (*TransactionStatusesDataProvider, error) { args, err := parseTransactionStatusesArguments(rawArguments) if err != nil { diff --git a/engine/access/rest/websockets/data_providers/transaction_statuses_provider_test.go b/engine/access/rest/websockets/data_providers/transaction_statuses_provider_test.go index 9576d10e620..8421a28eafa 100644 --- a/engine/access/rest/websockets/data_providers/transaction_statuses_provider_test.go +++ b/engine/access/rest/websockets/data_providers/transaction_statuses_provider_test.go @@ -78,7 +78,7 @@ func (s *TransactionStatusesProviderSuite) TestTransactionStatusesDataProvider_H TransactionStatusesTopic, s.factory, s.subscribeTransactionStatusesDataProviderTestCases(backendResponse), - func(dataChan chan any) { + func(dataChan chan interface{}) { dataChan <- backendResponse }, s.requireTransactionStatuses, @@ -109,8 +109,8 @@ func (s *TransactionStatusesProviderSuite) subscribeTransactionStatusesDataProvi // requireTransactionStatuses ensures that the received transaction statuses information matches the expected data. func (s *TransactionStatusesProviderSuite) requireTransactionStatuses( - actual any, - expected any, + actual interface{}, + expected interface{}, ) { expectedResponse, expectedResponsePayload := extractPayload[*models.TransactionStatusesResponse](s.T(), expected) actualResponse, actualResponsePayload := extractPayload[*models.TransactionStatusesResponse](s.T(), actual) @@ -133,7 +133,7 @@ func backendTransactionStatusesResponse(block *flow.Block) []*accessmodel.Transa var expectedTxResultsResponses []*accessmodel.TransactionResult - for range 2 { + for i := 0; i < 2; i++ { expectedTxResultsResponses = append(expectedTxResultsResponses, &txr) } @@ -144,8 +144,8 @@ func backendTransactionStatusesResponse(block *flow.Block) []*accessmodel.Transa func (s *TransactionStatusesProviderSuite) expectedTransactionStatusesResponses( backendResponses []*accessmodel.TransactionResult, topic string, -) []any { - expectedResponses := make([]any, len(backendResponses)) +) []interface{} { + expectedResponses := make([]interface{}, len(backendResponses)) for i, resp := range backendResponses { expectedResponsePayload := models.NewTransactionStatusesResponse(s.linkGenerator, resp, uint64(i)) @@ -160,16 +160,16 @@ func (s *TransactionStatusesProviderSuite) expectedTransactionStatusesResponses( // TestMessageIndexTransactionStatusesProviderResponse_HappyPath tests that MessageIndex values in response are strictly increasing. func (s *TransactionStatusesProviderSuite) TestMessageIndexTransactionStatusesProviderResponse_HappyPath() { - send := make(chan any, 10) + send := make(chan interface{}, 10) topic := TransactionStatusesTopic txStatusesCount := 4 // Create a channel to simulate the subscription's account statuses channel - txStatusesChan := make(chan any) + txStatusesChan := make(chan interface{}) // Create a mock subscription and mock the channel sub := submock.NewSubscription(s.T()) - sub.On("Channel").Return((<-chan any)(txStatusesChan)) + sub.On("Channel").Return((<-chan interface{})(txStatusesChan)) sub.On("Err").Return(nil).Once() s.api.On( @@ -186,7 +186,7 @@ func (s *TransactionStatusesProviderSuite) TestMessageIndexTransactionStatusesPr ) arguments := - map[string]any{ + map[string]interface{}{ "tx_id": unittest.TransactionFixture().ID().String(), } @@ -217,7 +217,7 @@ func (s *TransactionStatusesProviderSuite) TestMessageIndexTransactionStatusesPr // Simulate emitting data to the tx statuses channel var txResults []*accessmodel.TransactionResult - for range txStatusesCount { + for i := 0; i < txStatusesCount; i++ { txResults = append(txResults, &accessmodel.TransactionResult{ BlockHeight: s.rootBlock.Height, }) @@ -231,7 +231,7 @@ func (s *TransactionStatusesProviderSuite) TestMessageIndexTransactionStatusesPr // Collect responses var responses []*models.TransactionStatusesResponse - for range txStatusesCount { + for i := 0; i < txStatusesCount; i++ { res := <-send _, txStatusesResData := extractPayload[*models.TransactionStatusesResponse](s.T(), res) responses = append(responses, txStatusesResData) @@ -255,7 +255,7 @@ func (s *TransactionStatusesProviderSuite) TestMessageIndexTransactionStatusesPr // when invalid arguments are provided. It verifies that appropriate errors are returned // for missing or conflicting arguments. func (s *TransactionStatusesProviderSuite) TestTransactionStatusesDataProvider_InvalidArguments() { - send := make(chan any) + send := make(chan interface{}) topic := TransactionStatusesTopic @@ -285,26 +285,26 @@ func invalidTransactionStatusesArgumentsTestCases() []testErrType { return []testErrType{ { name: "invalid 'tx_id' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "tx_id": "invalid_tx_id", }, expectedErrorMsg: "invalid ID format", }, { name: "empty 'tx_id' argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "tx_id": "", }, expectedErrorMsg: "'tx_id' must not be empty", }, { name: "missing 'tx_id' argument", - arguments: map[string]any{}, + arguments: map[string]interface{}{}, expectedErrorMsg: "missing 'tx_id' field", }, { name: "unexpected argument", - arguments: map[string]any{ + arguments: map[string]interface{}{ "unexpected_argument": "dummy", "tx_id": unittest.TransactionFixture().ID().String(), }, diff --git a/engine/access/rest/websockets/data_providers/unit_test.go b/engine/access/rest/websockets/data_providers/unit_test.go index b85a655bf2f..de9abde3cba 100644 --- a/engine/access/rest/websockets/data_providers/unit_test.go +++ b/engine/access/rest/websockets/data_providers/unit_test.go @@ -20,7 +20,7 @@ type testType struct { name string arguments wsmodels.Arguments setupBackend func(sub *submock.Subscription) - expectedResponses []any + expectedResponses []interface{} } // testErrType represents an error cases for subscribing @@ -47,19 +47,19 @@ func testHappyPath( topic string, factory *DataProviderFactoryImpl, tests []testType, - sendData func(chan any), - requireFn func(any, any), + sendData func(chan interface{}), + requireFn func(interface{}, interface{}), ) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - send := make(chan any, 10) + send := make(chan interface{}, 10) // Create a channel to simulate the subscription's data channel - dataChan := make(chan any) + dataChan := make(chan interface{}) // Create a mock subscription and mock the channel sub := submock.NewSubscription(t) - sub.On("Channel").Return((<-chan any)(dataChan)) + sub.On("Channel").Return((<-chan interface{})(dataChan)) sub.On("Err").Return(nil) test.setupBackend(sub) @@ -102,7 +102,7 @@ func testHappyPath( } // extractPayload extracts the BaseDataProvidersResponse and its typed Payload. -func extractPayload[T any](t *testing.T, v any) (*models.BaseDataProvidersResponse, T) { +func extractPayload[T any](t *testing.T, v interface{}) (*models.BaseDataProvidersResponse, T) { response, ok := v.(*models.BaseDataProvidersResponse) require.True(t, ok, "Expected *models.BaseDataProvidersResponse, got %T", v) @@ -125,7 +125,7 @@ func TestEnsureAllowedFields(t *testing.T) { } t.Run("Valid fields with all required", func(t *testing.T) { - fields := map[string]any{ + fields := map[string]interface{}{ "start_block_id": "abc", "start_block_height": 123, "event_types": []string{"flow.Event"}, @@ -138,7 +138,7 @@ func TestEnsureAllowedFields(t *testing.T) { }) t.Run("Unexpected field present", func(t *testing.T) { - fields := map[string]any{ + fields := map[string]interface{}{ "start_block_id": "abc", "start_block_height": 123, "unknown_field": "unexpected", @@ -184,7 +184,7 @@ func TestExtractArrayOfStrings(t *testing.T) { }, { name: "Invalid type in array", - args: wsmodels.Arguments{"tags": []any{"a", 123}}, + args: wsmodels.Arguments{"tags": []interface{}{"a", 123}}, key: "tags", required: true, expect: nil, diff --git a/engine/access/rest/websockets/legacy/routes/subscribe_events_test.go b/engine/access/rest/websockets/legacy/routes/subscribe_events_test.go index eb6ac86279d..9f0809ec0f1 100644 --- a/engine/access/rest/websockets/legacy/routes/subscribe_events_test.go +++ b/engine/access/rest/websockets/legacy/routes/subscribe_events_test.go @@ -70,7 +70,7 @@ func (s *SubscribeEventsSuite) SetupTest() { s.blocks = make([]*flow.Block, 0, blockCount) s.blockEvents = make(map[flow.Identifier]flow.EventsList, blockCount) - for i := range blockCount { + for i := 0; i < blockCount; i++ { block := unittest.BlockWithParentFixture(parent) // update for next iteration parent = block.ToHeader() @@ -80,7 +80,7 @@ func (s *SubscribeEventsSuite) SetupTest() { s.blocks = append(s.blocks, block) var events []flow.Event - for j := range testEventTypes { + for j := 0; j < len(testEventTypes); j++ { events = append(events, unittest.EventFixture( unittest.Event.WithEventType(testEventTypes[j]), )) @@ -217,8 +217,8 @@ func (s *SubscribeEventsSuite) TestSubscribeEvents() { } // Create a channel to receive mock EventsResponse objects - ch := make(chan any) - var chReadOnly <-chan any + ch := make(chan interface{}) + var chReadOnly <-chan interface{} // Simulate sending a mock EventsResponse go func() { for _, eventResponse := range subscriptionEventsResponses { @@ -269,8 +269,8 @@ func (s *SubscribeEventsSuite) TestSubscribeEventsHandlesErrors() { invalidBlock := unittest.BlockFixture() subscription := submock.NewSubscription(s.T()) - ch := make(chan any) - var chReadOnly <-chan any + ch := make(chan interface{}) + var chReadOnly <-chan interface{} go func() { close(ch) }() @@ -302,8 +302,8 @@ func (s *SubscribeEventsSuite) TestSubscribeEventsHandlesErrors() { stateStreamBackend := ssmock.NewAPI(s.T()) subscription := submock.NewSubscription(s.T()) - ch := make(chan any) - var chReadOnly <-chan any + ch := make(chan interface{}) + var chReadOnly <-chan interface{} go func() { close(ch) diff --git a/engine/access/rest/websockets/mock/websocket_connection.go b/engine/access/rest/websockets/mock/websocket_connection.go index 873d06fbadb..eacc351edd9 100644 --- a/engine/access/rest/websockets/mock/websocket_connection.go +++ b/engine/access/rest/websockets/mock/websocket_connection.go @@ -82,7 +82,7 @@ func (_c *WebsocketConnection_Close_Call) RunAndReturn(run func() error) *Websoc } // ReadJSON provides a mock function for the type WebsocketConnection -func (_mock *WebsocketConnection) ReadJSON(v any) error { +func (_mock *WebsocketConnection) ReadJSON(v interface{}) error { ret := _mock.Called(v) if len(ret) == 0 { @@ -90,7 +90,7 @@ func (_mock *WebsocketConnection) ReadJSON(v any) error { } var r0 error - if returnFunc, ok := ret.Get(0).(func(any) error); ok { + if returnFunc, ok := ret.Get(0).(func(interface{}) error); ok { r0 = returnFunc(v) } else { r0 = ret.Error(0) @@ -104,16 +104,16 @@ type WebsocketConnection_ReadJSON_Call struct { } // ReadJSON is a helper method to define mock.On call -// - v any +// - v interface{} func (_e *WebsocketConnection_Expecter) ReadJSON(v interface{}) *WebsocketConnection_ReadJSON_Call { return &WebsocketConnection_ReadJSON_Call{Call: _e.mock.On("ReadJSON", v)} } -func (_c *WebsocketConnection_ReadJSON_Call) Run(run func(v any)) *WebsocketConnection_ReadJSON_Call { +func (_c *WebsocketConnection_ReadJSON_Call) Run(run func(v interface{})) *WebsocketConnection_ReadJSON_Call { _c.Call.Run(func(args mock.Arguments) { - var arg0 any + var arg0 interface{} if args[0] != nil { - arg0 = args[0].(any) + arg0 = args[0].(interface{}) } run( arg0, @@ -127,7 +127,7 @@ func (_c *WebsocketConnection_ReadJSON_Call) Return(err error) *WebsocketConnect return _c } -func (_c *WebsocketConnection_ReadJSON_Call) RunAndReturn(run func(v any) error) *WebsocketConnection_ReadJSON_Call { +func (_c *WebsocketConnection_ReadJSON_Call) RunAndReturn(run func(v interface{}) error) *WebsocketConnection_ReadJSON_Call { _c.Call.Return(run) return _c } @@ -332,7 +332,7 @@ func (_c *WebsocketConnection_WriteControl_Call) RunAndReturn(run func(messageTy } // WriteJSON provides a mock function for the type WebsocketConnection -func (_mock *WebsocketConnection) WriteJSON(v any) error { +func (_mock *WebsocketConnection) WriteJSON(v interface{}) error { ret := _mock.Called(v) if len(ret) == 0 { @@ -340,7 +340,7 @@ func (_mock *WebsocketConnection) WriteJSON(v any) error { } var r0 error - if returnFunc, ok := ret.Get(0).(func(any) error); ok { + if returnFunc, ok := ret.Get(0).(func(interface{}) error); ok { r0 = returnFunc(v) } else { r0 = ret.Error(0) @@ -354,16 +354,16 @@ type WebsocketConnection_WriteJSON_Call struct { } // WriteJSON is a helper method to define mock.On call -// - v any +// - v interface{} func (_e *WebsocketConnection_Expecter) WriteJSON(v interface{}) *WebsocketConnection_WriteJSON_Call { return &WebsocketConnection_WriteJSON_Call{Call: _e.mock.On("WriteJSON", v)} } -func (_c *WebsocketConnection_WriteJSON_Call) Run(run func(v any)) *WebsocketConnection_WriteJSON_Call { +func (_c *WebsocketConnection_WriteJSON_Call) Run(run func(v interface{})) *WebsocketConnection_WriteJSON_Call { _c.Call.Run(func(args mock.Arguments) { - var arg0 any + var arg0 interface{} if args[0] != nil { - arg0 = args[0].(any) + arg0 = args[0].(interface{}) } run( arg0, @@ -377,7 +377,7 @@ func (_c *WebsocketConnection_WriteJSON_Call) Return(err error) *WebsocketConnec return _c } -func (_c *WebsocketConnection_WriteJSON_Call) RunAndReturn(run func(v any) error) *WebsocketConnection_WriteJSON_Call { +func (_c *WebsocketConnection_WriteJSON_Call) RunAndReturn(run func(v interface{}) error) *WebsocketConnection_WriteJSON_Call { _c.Call.Return(run) return _c } diff --git a/engine/access/rest_api_test.go b/engine/access/rest_api_test.go index 02893893129..bb7e75176ac 100644 --- a/engine/access/rest_api_test.go +++ b/engine/access/rest_api_test.go @@ -331,7 +331,7 @@ func (suite *RestAPITestSuite) TestGetBlock() { require.NoError(suite.T(), err) assert.Equal(suite.T(), http.StatusOK, resp.StatusCode) assert.Len(suite.T(), actualBlocks, blkCnt) - for i := range blkCnt { + for i := 0; i < blkCnt; i++ { assert.Equal(suite.T(), testBlocks[i].ID().String(), actualBlocks[i].Header.Id) assert.Equal(suite.T(), fmt.Sprintf("%d", testBlocks[i].Height), actualBlocks[i].Header.Height) } @@ -344,7 +344,7 @@ func (suite *RestAPITestSuite) TestGetBlock() { lastIndex := len(testBlocks) var reqHeights = make([]uint64, len(testBlocks)) - for i := range lastIndex { + for i := 0; i < lastIndex; i++ { reqHeights[i] = testBlocks[i].Height } @@ -352,7 +352,7 @@ func (suite *RestAPITestSuite) TestGetBlock() { require.NoError(suite.T(), err) assert.Equal(suite.T(), http.StatusOK, resp.StatusCode) assert.Len(suite.T(), actualBlocks, lastIndex) - for i := range lastIndex { + for i := 0; i < lastIndex; i++ { assert.Equal(suite.T(), testBlocks[i].ID().String(), actualBlocks[i].Header.Id) assert.Equal(suite.T(), fmt.Sprintf("%d", testBlocks[i].Height), actualBlocks[i].Header.Height) } diff --git a/engine/access/rpc/backend/backend_stream_block_digests_test.go b/engine/access/rpc/backend/backend_stream_block_digests_test.go index 77c6164fe82..76e4c508207 100644 --- a/engine/access/rpc/backend/backend_stream_block_digests_test.go +++ b/engine/access/rpc/backend/backend_stream_block_digests_test.go @@ -31,7 +31,7 @@ func (s *BackendBlockDigestSuite) SetupTest() { // TestSubscribeBlockDigestsFromStartBlockID tests the SubscribeBlockDigestsFromStartBlockID method. func (s *BackendBlockDigestSuite) TestSubscribeBlockDigestsFromStartBlockID() { - call := func(ctx context.Context, startValue any, blockStatus flow.BlockStatus) subscription.Subscription { + call := func(ctx context.Context, startValue interface{}, blockStatus flow.BlockStatus) subscription.Subscription { return s.backend.SubscribeBlockDigestsFromStartBlockID(ctx, startValue.(flow.Identifier), blockStatus) } @@ -40,7 +40,7 @@ func (s *BackendBlockDigestSuite) TestSubscribeBlockDigestsFromStartBlockID() { // TestSubscribeBlockDigestsFromStartHeight tests the SubscribeBlockDigestsFromStartHeight method. func (s *BackendBlockDigestSuite) TestSubscribeBlockDigestsFromStartHeight() { - call := func(ctx context.Context, startValue any, blockStatus flow.BlockStatus) subscription.Subscription { + call := func(ctx context.Context, startValue interface{}, blockStatus flow.BlockStatus) subscription.Subscription { return s.backend.SubscribeBlockDigestsFromStartHeight(ctx, startValue.(uint64), blockStatus) } @@ -49,7 +49,7 @@ func (s *BackendBlockDigestSuite) TestSubscribeBlockDigestsFromStartHeight() { // TestSubscribeBlockDigestsFromLatest tests the SubscribeBlockDigestsFromLatest method. func (s *BackendBlockDigestSuite) TestSubscribeBlockDigestsFromLatest() { - call := func(ctx context.Context, startValue any, blockStatus flow.BlockStatus) subscription.Subscription { + call := func(ctx context.Context, startValue interface{}, blockStatus flow.BlockStatus) subscription.Subscription { return s.backend.SubscribeBlockDigestsFromLatest(ctx, blockStatus) } @@ -57,7 +57,7 @@ func (s *BackendBlockDigestSuite) TestSubscribeBlockDigestsFromLatest() { } // requireBlockDigests ensures that the received block digest information matches the expected data. -func (s *BackendBlockDigestSuite) requireBlockDigests(v any, expectedBlock *flow.Block) { +func (s *BackendBlockDigestSuite) requireBlockDigests(v interface{}, expectedBlock *flow.Block) { actualBlock, ok := v.(*flow.BlockDigest) require.True(s.T(), ok, "unexpected response type: %T", v) diff --git a/engine/access/rpc/backend/backend_stream_block_headers_test.go b/engine/access/rpc/backend/backend_stream_block_headers_test.go index d0932d856f2..5994b01cfa3 100644 --- a/engine/access/rpc/backend/backend_stream_block_headers_test.go +++ b/engine/access/rpc/backend/backend_stream_block_headers_test.go @@ -31,7 +31,7 @@ func (s *BackendBlockHeadersSuite) SetupTest() { // TestSubscribeBlockHeadersFromStartBlockID tests the SubscribeBlockHeadersFromStartBlockID method. func (s *BackendBlockHeadersSuite) TestSubscribeBlockHeadersFromStartBlockID() { - call := func(ctx context.Context, startValue any, blockStatus flow.BlockStatus) subscription.Subscription { + call := func(ctx context.Context, startValue interface{}, blockStatus flow.BlockStatus) subscription.Subscription { return s.backend.SubscribeBlockHeadersFromStartBlockID(ctx, startValue.(flow.Identifier), blockStatus) } @@ -40,7 +40,7 @@ func (s *BackendBlockHeadersSuite) TestSubscribeBlockHeadersFromStartBlockID() { // TestSubscribeBlockHeadersFromStartHeight tests the SubscribeBlockHeadersFromStartHeight method. func (s *BackendBlockHeadersSuite) TestSubscribeBlockHeadersFromStartHeight() { - call := func(ctx context.Context, startValue any, blockStatus flow.BlockStatus) subscription.Subscription { + call := func(ctx context.Context, startValue interface{}, blockStatus flow.BlockStatus) subscription.Subscription { return s.backend.SubscribeBlockHeadersFromStartHeight(ctx, startValue.(uint64), blockStatus) } @@ -49,7 +49,7 @@ func (s *BackendBlockHeadersSuite) TestSubscribeBlockHeadersFromStartHeight() { // TestSubscribeBlockHeadersFromLatest tests the SubscribeBlockHeadersFromLatest method. func (s *BackendBlockHeadersSuite) TestSubscribeBlockHeadersFromLatest() { - call := func(ctx context.Context, startValue any, blockStatus flow.BlockStatus) subscription.Subscription { + call := func(ctx context.Context, startValue interface{}, blockStatus flow.BlockStatus) subscription.Subscription { return s.backend.SubscribeBlockHeadersFromLatest(ctx, blockStatus) } @@ -57,7 +57,7 @@ func (s *BackendBlockHeadersSuite) TestSubscribeBlockHeadersFromLatest() { } // requireBlockHeaders ensures that the received block header information matches the expected data. -func (s *BackendBlockHeadersSuite) requireBlockHeaders(v any, expectedBlock *flow.Block) { +func (s *BackendBlockHeadersSuite) requireBlockHeaders(v interface{}, expectedBlock *flow.Block) { actualHeader, ok := v.(*flow.Header) require.True(s.T(), ok, "unexpected response type: %T", v) diff --git a/engine/access/rpc/backend/backend_stream_blocks.go b/engine/access/rpc/backend/backend_stream_blocks.go index 1a48efc4df8..4c7b032fbc7 100644 --- a/engine/access/rpc/backend/backend_stream_blocks.go +++ b/engine/access/rpc/backend/backend_stream_blocks.go @@ -235,7 +235,7 @@ func (b *backendSubscribeBlocks) subscribeFromLatest(ctx context.Context, getDat // getBlockResponse returns a GetDataByHeightFunc that retrieves block information for the specified height. func (b *backendSubscribeBlocks) getBlockResponse(blockStatus flow.BlockStatus) subscription.GetDataByHeightFunc { - return func(_ context.Context, height uint64) (any, error) { + return func(_ context.Context, height uint64) (interface{}, error) { block, err := b.getBlock(height, blockStatus) if err != nil { return nil, err @@ -252,7 +252,7 @@ func (b *backendSubscribeBlocks) getBlockResponse(blockStatus flow.BlockStatus) // getBlockHeaderResponse returns a GetDataByHeightFunc that retrieves block header information for the specified height. func (b *backendSubscribeBlocks) getBlockHeaderResponse(blockStatus flow.BlockStatus) subscription.GetDataByHeightFunc { - return func(_ context.Context, height uint64) (any, error) { + return func(_ context.Context, height uint64) (interface{}, error) { header, err := b.getBlockHeader(height, blockStatus) if err != nil { return nil, err @@ -269,7 +269,7 @@ func (b *backendSubscribeBlocks) getBlockHeaderResponse(blockStatus flow.BlockSt // getBlockDigestResponse returns a GetDataByHeightFunc that retrieves lightweight block information for the specified height. func (b *backendSubscribeBlocks) getBlockDigestResponse(blockStatus flow.BlockStatus) subscription.GetDataByHeightFunc { - return func(_ context.Context, height uint64) (any, error) { + return func(_ context.Context, height uint64) (interface{}, error) { header, err := b.getBlockHeader(height, blockStatus) if err != nil { return nil, err diff --git a/engine/access/rpc/backend/backend_stream_blocks_test.go b/engine/access/rpc/backend/backend_stream_blocks_test.go index 18fe9d4aae0..ff574e6fbda 100644 --- a/engine/access/rpc/backend/backend_stream_blocks_test.go +++ b/engine/access/rpc/backend/backend_stream_blocks_test.go @@ -57,7 +57,7 @@ type BackendBlocksSuite struct { type testType struct { name string highestBackfill int - startValue any + startValue interface{} blockStatus flow.BlockStatus expectedBlocks []*flow.Block } @@ -94,7 +94,7 @@ func (s *BackendBlocksSuite) SetupTest() { s.blockMap[s.rootBlock.Height] = s.rootBlock s.T().Logf("Generating %d blocks, root block: %d %s", blockCount, s.rootBlock.Height, s.rootBlock.ID()) - for range blockCount { + for i := 0; i < blockCount; i++ { block := unittest.BlockWithParentFixture(parent) // update for next iteration parent = block.ToHeader() @@ -309,7 +309,7 @@ func (s *BackendBlocksSuite) setupBlockTrackerMock(highestHeader *flow.Header) { // TestSubscribeBlocksFromStartBlockID tests the SubscribeBlocksFromStartBlockID method. func (s *BackendBlocksSuite) TestSubscribeBlocksFromStartBlockID() { - call := func(ctx context.Context, startValue any, blockStatus flow.BlockStatus) subscription.Subscription { + call := func(ctx context.Context, startValue interface{}, blockStatus flow.BlockStatus) subscription.Subscription { return s.backend.SubscribeBlocksFromStartBlockID(ctx, startValue.(flow.Identifier), blockStatus) } @@ -318,7 +318,7 @@ func (s *BackendBlocksSuite) TestSubscribeBlocksFromStartBlockID() { // TestSubscribeBlocksFromStartHeight tests the SubscribeBlocksFromStartHeight method. func (s *BackendBlocksSuite) TestSubscribeBlocksFromStartHeight() { - call := func(ctx context.Context, startValue any, blockStatus flow.BlockStatus) subscription.Subscription { + call := func(ctx context.Context, startValue interface{}, blockStatus flow.BlockStatus) subscription.Subscription { return s.backend.SubscribeBlocksFromStartHeight(ctx, startValue.(uint64), blockStatus) } @@ -327,7 +327,7 @@ func (s *BackendBlocksSuite) TestSubscribeBlocksFromStartHeight() { // TestSubscribeBlocksFromLatest tests the SubscribeBlocksFromLatest method. func (s *BackendBlocksSuite) TestSubscribeBlocksFromLatest() { - call := func(ctx context.Context, startValue any, blockStatus flow.BlockStatus) subscription.Subscription { + call := func(ctx context.Context, startValue interface{}, blockStatus flow.BlockStatus) subscription.Subscription { return s.backend.SubscribeBlocksFromLatest(ctx, blockStatus) } @@ -360,8 +360,8 @@ func (s *BackendBlocksSuite) TestSubscribeBlocksFromLatest() { // 7. Ensures that there are no new messages waiting after all blocks have been processed. // 8. Cancels the subscription and ensures it shuts down gracefully. func (s *BackendBlocksSuite) subscribe( - subscribeFn func(ctx context.Context, startValue any, blockStatus flow.BlockStatus) subscription.Subscription, - requireFn func(any, *flow.Block), + subscribeFn func(ctx context.Context, startValue interface{}, blockStatus flow.BlockStatus) subscription.Subscription, + requireFn func(interface{}, *flow.Block), tests []testType, ) { for _, test := range tests { @@ -437,7 +437,7 @@ func (s *BackendBlocksSuite) subscribe( } // requireBlocks ensures that the received block information matches the expected data. -func (s *BackendBlocksSuite) requireBlocks(v any, expectedBlock *flow.Block) { +func (s *BackendBlocksSuite) requireBlocks(v interface{}, expectedBlock *flow.Block) { actualBlock, ok := v.(*flow.Block) require.True(s.T(), ok, "unexpected response type: %T", v) diff --git a/engine/access/rpc/backend/events/events_test.go b/engine/access/rpc/backend/events/events_test.go index 0e99b48075c..046b05c12c6 100644 --- a/engine/access/rpc/backend/events/events_test.go +++ b/engine/access/rpc/backend/events/events_test.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "math" - "slices" "sort" "testing" @@ -96,7 +95,7 @@ func (s *EventsSuite) SetupTest() { s.blocks = make([]*flow.Block, blockCount) s.blockIDs = make([]flow.Identifier, blockCount) - for i := range blockCount { + for i := 0; i < blockCount; i++ { var header *flow.Header if i == 0 { header = unittest.BlockHeaderFixture() @@ -138,8 +137,10 @@ func (s *EventsSuite) SetupTest() { }) s.events.On("ByBlockID", mock.Anything).Return(func(blockID flow.Identifier) ([]flow.Event, error) { - if slices.Contains(s.blockIDs, blockID) { - return returnBlockEvents, nil + for _, headerID := range s.blockIDs { + if blockID == headerID { + return returnBlockEvents, nil + } } return nil, storage.ErrNotFound }).Maybe() diff --git a/engine/access/rpc/backend/script_executor_test.go b/engine/access/rpc/backend/script_executor_test.go index c67a2f0743f..321283765cb 100644 --- a/engine/access/rpc/backend/script_executor_test.go +++ b/engine/access/rpc/backend/script_executor_test.go @@ -274,7 +274,7 @@ func versionBeaconEventFixture( ) *flow.SealedVersionBeacon { require.Equal(t, len(heights), len(versions), "the heights array should be the same length as the versions array") var vb []flow.VersionBoundary - for i := range heights { + for i := 0; i < len(heights); i++ { vb = append(vb, flow.VersionBoundary{ BlockHeight: heights[i], Version: versions[i], diff --git a/engine/access/rpc/backend/transactions/error_messages/provider_test.go b/engine/access/rpc/backend/transactions/error_messages/provider_test.go index 176cb3efbcc..2c087fb8a93 100644 --- a/engine/access/rpc/backend/transactions/error_messages/provider_test.go +++ b/engine/access/rpc/backend/transactions/error_messages/provider_test.go @@ -652,7 +652,7 @@ func (suite *Suite) TestLookupByIndex_ExecutionNodeError_TxResultFailed() { func (suite *Suite) TestLookupByBlockID_FromExecutionNode_HappyPath() { resultsByBlockID := make([]flow.LightTransactionResult, 0) - for i := range 5 { + for i := 0; i < 5; i++ { resultsByBlockID = append(resultsByBlockID, flow.LightTransactionResult{ TransactionID: unittest.IdentifierFixture(), Failed: i%2 == 0, // create a mix of failed and non-failed transactions @@ -718,7 +718,7 @@ func (suite *Suite) TestLookupByBlockID_FromExecutionNode_HappyPath() { func (suite *Suite) TestLookupByBlockID_FromStorage_HappyPath() { resultsByBlockID := make([]flow.LightTransactionResult, 0) - for i := range 5 { + for i := 0; i < 5; i++ { resultsByBlockID = append(resultsByBlockID, flow.LightTransactionResult{ TransactionID: unittest.IdentifierFixture(), Failed: i%2 == 0, // create a mix of failed and non-failed transactions diff --git a/engine/access/rpc/backend/transactions/stream/stream_backend.go b/engine/access/rpc/backend/transactions/stream/stream_backend.go index 0b0b9656368..65f029a8d4d 100644 --- a/engine/access/rpc/backend/transactions/stream/stream_backend.go +++ b/engine/access/rpc/backend/transactions/stream/stream_backend.go @@ -177,8 +177,8 @@ func (t *TransactionStream) createSubscription( func (t *TransactionStream) getTransactionStatusResponse( txInfo *TransactionMetadata, startHeight uint64, -) func(context.Context, uint64) (any, error) { - return func(ctx context.Context, height uint64) (any, error) { +) func(context.Context, uint64) (interface{}, error) { + return func(ctx context.Context, height uint64) (interface{}, error) { err := t.checkBlockReady(height) if err != nil { return nil, err diff --git a/engine/access/rpc/connection/cache_test.go b/engine/access/rpc/connection/cache_test.go index 5e84f97efae..37470f14180 100644 --- a/engine/access/rpc/connection/cache_test.go +++ b/engine/access/rpc/connection/cache_test.go @@ -139,7 +139,7 @@ func TestConcurrentConnectionsAndDisconnects(t *testing.T) { wg := sync.WaitGroup{} wg.Add(connectionCount) callCount := atomic.NewInt32(0) - for range connectionCount { + for i := 0; i < connectionCount; i++ { go func() { defer wg.Done() cachedConn, err := cache.GetConnected("foo", cfg, nil, func(string, Config, crypto.PublicKey, *CachedClient) (*grpc.ClientConn, error) { @@ -173,10 +173,10 @@ func TestConcurrentConnectionsAndDisconnects(t *testing.T) { batchSize := 1000 numBatches := 100 - for range numBatches { + for batch := 0; batch < numBatches; batch++ { wg := sync.WaitGroup{} wg.Add(batchSize) - for range batchSize { + for i := 0; i < batchSize; i++ { go func() { defer wg.Done() cachedConn, err := cache.GetConnected("foo", cfg, nil, connectFn) diff --git a/engine/access/rpc/connection/connection_test.go b/engine/access/rpc/connection/connection_test.go index 0777a64df70..4533e469c54 100644 --- a/engine/access/rpc/connection/connection_test.go +++ b/engine/access/rpc/connection/connection_test.go @@ -594,10 +594,12 @@ func TestExecutionNodeClientClosedGracefully(t *testing.T) { var waitGroup sync.WaitGroup - for range nofRequests { + for i := 0; i < nofRequests; i++ { + waitGroup.Add(1) // call Ping request from different goroutines - waitGroup.Go(func() { + go func() { + defer waitGroup.Done() _, err := client.Ping(ctx, req) if err == nil { @@ -605,7 +607,7 @@ func TestExecutionNodeClientClosedGracefully(t *testing.T) { } else { require.Equalf(t, codes.Unavailable, status.Code(err), "unexpected error: %v", err) } - }) + }() } // Close connection @@ -701,7 +703,9 @@ func TestEvictingCacheClients(t *testing.T) { // Schedule the invalidation of the access API client while the Ping call is in progress wg := sync.WaitGroup{} - wg.Go(func() { + wg.Add(1) + go func() { + defer wg.Done() <-startPing // wait until Ping is called @@ -719,7 +723,7 @@ func TestEvictingCacheClients(t *testing.T) { assert.Nil(t, resp) close(returnFromPing) // signal it's ok to return from Ping - }) + }() // Call a gRPC method on the client _, err = client.Ping(ctx, pingReq) @@ -816,7 +820,7 @@ func TestConcurrentConnections(t *testing.T) { var wg sync.WaitGroup wg.Add(requestCount) - for range requestCount { + for i := 0; i < requestCount; i++ { go func() { defer wg.Done() diff --git a/engine/access/rpc/connection/grpc_compression_benchmark_test.go b/engine/access/rpc/connection/grpc_compression_benchmark_test.go index 746047a7cb3..4fed6759681 100644 --- a/engine/access/rpc/connection/grpc_compression_benchmark_test.go +++ b/engine/access/rpc/connection/grpc_compression_benchmark_test.go @@ -43,7 +43,7 @@ func runBenchmark(b *testing.B, compressorName string) { blockHeaders := getHeaders(5) exeResults := make([]*execution.GetEventsForBlockIDsResponse_Result, len(blockHeaders)) - for i := range blockHeaders { + for i := 0; i < len(blockHeaders); i++ { exeResults[i] = &execution.GetEventsForBlockIDsResponse_Result{ BlockId: convert.IdentifierToMessage(blockHeaders[i].ID()), BlockHeight: blockHeaders[i].Height, diff --git a/engine/access/rpc/connection/manager.go b/engine/access/rpc/connection/manager.go index 3bf77f2c30a..00a92ccdc6c 100644 --- a/engine/access/rpc/connection/manager.go +++ b/engine/access/rpc/connection/manager.go @@ -182,8 +182,8 @@ func createRequestWatcherInterceptor(cachedClient *CachedClient) grpc.UnaryClien requestWatcherInterceptor := func( ctx context.Context, method string, - req any, - reply any, + req interface{}, + reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption, @@ -215,8 +215,8 @@ func createClientTimeoutInterceptor(timeout time.Duration) grpc.UnaryClientInter clientTimeoutInterceptor := func( ctx context.Context, method string, - req any, - reply any, + req interface{}, + reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption, @@ -241,8 +241,8 @@ func (m *Manager) createClientInvalidationInterceptor(cachedClient *CachedClient return func( ctx context.Context, method string, - req any, - reply any, + req interface{}, + reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption, @@ -313,8 +313,8 @@ func (m *Manager) createCircuitBreakerInterceptor() grpc.UnaryClientInterceptor circuitBreakerInterceptor := func( ctx context.Context, method string, - req any, - reply any, + req interface{}, + reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption, @@ -326,7 +326,7 @@ func (m *Manager) createCircuitBreakerInterceptor() grpc.UnaryClientInterceptor // "RestoreTimeout" period elapses, the circuit breaker transitions to the "StateHalfOpen" and attempts the // invocation again. If the invocation fails, it returns to the "StateOpen"; otherwise, it transitions to // the "StateClosed" and handles invocations as usual. - _, err := circuitBreaker.Execute(func() (any, error) { + _, err := circuitBreaker.Execute(func() (interface{}, error) { err := invoker(ctx, method, req, reply, cc, opts...) return nil, err }) diff --git a/engine/access/state_stream/backend/backend_account_statuses.go b/engine/access/state_stream/backend/backend_account_statuses.go index 2dc652444bb..d168e7ddd96 100644 --- a/engine/access/state_stream/backend/backend_account_statuses.go +++ b/engine/access/state_stream/backend/backend_account_statuses.go @@ -96,7 +96,7 @@ func (b *AccountStatusesBackend) SubscribeAccountStatusesFromLatestBlock( func (b *AccountStatusesBackend) getAccountStatusResponseFactory( filter state_stream.AccountStatusFilter, ) subscription.GetDataByHeightFunc { - return func(ctx context.Context, height uint64) (any, error) { + return func(ctx context.Context, height uint64) (interface{}, error) { eventsResponse, err := b.eventsProvider.GetAllEventsResponse(ctx, height) if err != nil { if errors.Is(err, storage.ErrNotFound) || diff --git a/engine/access/state_stream/backend/backend_account_statuses_test.go b/engine/access/state_stream/backend/backend_account_statuses_test.go index 4267b279482..65d3e350aa4 100644 --- a/engine/access/state_stream/backend/backend_account_statuses_test.go +++ b/engine/access/state_stream/backend/backend_account_statuses_test.go @@ -31,7 +31,7 @@ var testProtocolEventTypes = []flow.EventType{ type testType struct { name string // Test case name highestBackfill int // Highest backfill index - startValue any + startValue interface{} filters state_stream.AccountStatusFilter // Event filters } @@ -89,7 +89,7 @@ func (s *BackendAccountStatusesSuite) SetupTest() { parent := s.rootBlock.ToHeader() events := s.generateProtocolMockEvents() - for i := range blockCount { + for i := 0; i < blockCount; i++ { block := unittest.BlockWithParentFixture(parent) // update for next iteration parent = block.ToHeader() @@ -267,7 +267,7 @@ func (s *BackendAccountStatusesSuite) generateFiltersForTestCases(baseTests []te // For each test case, it simulates backfill blocks and verifies the expected account events for each block. // It also ensures that the subscription shuts down gracefully after completing the test cases. func (s *BackendAccountStatusesSuite) subscribeToAccountStatuses( - subscribeFn func(ctx context.Context, startValue any, filter state_stream.AccountStatusFilter) subscription.Subscription, + subscribeFn func(ctx context.Context, startValue interface{}, filter state_stream.AccountStatusFilter) subscription.Subscription, tests []testType, ) { ctx, cancel := context.WithCancel(context.Background()) @@ -346,7 +346,7 @@ func (s *BackendAccountStatusesSuite) TestSubscribeAccountStatusesFromStartBlock return s.executionDataTrackerReal.GetStartHeightFromBlockID(startBlockID) }, nil) - call := func(ctx context.Context, startValue any, filter state_stream.AccountStatusFilter) subscription.Subscription { + call := func(ctx context.Context, startValue interface{}, filter state_stream.AccountStatusFilter) subscription.Subscription { return s.backend.SubscribeAccountStatusesFromStartBlockID(ctx, startValue.(flow.Identifier), filter) } @@ -362,7 +362,7 @@ func (s *BackendAccountStatusesSuite) TestSubscribeAccountStatusesFromStartHeigh return s.executionDataTrackerReal.GetStartHeightFromHeight(startHeight) }, nil) - call := func(ctx context.Context, startValue any, filter state_stream.AccountStatusFilter) subscription.Subscription { + call := func(ctx context.Context, startValue interface{}, filter state_stream.AccountStatusFilter) subscription.Subscription { return s.backend.SubscribeAccountStatusesFromStartHeight(ctx, startValue.(uint64), filter) } @@ -378,7 +378,7 @@ func (s *BackendAccountStatusesSuite) TestSubscribeAccountStatusesFromLatestBloc return s.executionDataTrackerReal.GetStartHeightFromLatest(ctx) }, nil) - call := func(ctx context.Context, startValue any, filter state_stream.AccountStatusFilter) subscription.Subscription { + call := func(ctx context.Context, startValue interface{}, filter state_stream.AccountStatusFilter) subscription.Subscription { return s.backend.SubscribeAccountStatusesFromLatestBlock(ctx, filter) } @@ -386,7 +386,7 @@ func (s *BackendAccountStatusesSuite) TestSubscribeAccountStatusesFromLatestBloc } // requireEventsResponse ensures that the received event information matches the expected data. -func (s *BackendAccountStatusesSuite) requireEventsResponse(v any, expected *AccountStatusesResponse) { +func (s *BackendAccountStatusesSuite) requireEventsResponse(v interface{}, expected *AccountStatusesResponse) { actual, ok := v.(*AccountStatusesResponse) require.True(s.T(), ok, "unexpected response type: %T", v) diff --git a/engine/access/state_stream/backend/backend_events.go b/engine/access/state_stream/backend/backend_events.go index a830b8c5e2a..e4c94ffc5dd 100644 --- a/engine/access/state_stream/backend/backend_events.go +++ b/engine/access/state_stream/backend/backend_events.go @@ -132,7 +132,7 @@ func (b *EventsBackend) SubscribeEventsFromLatest(ctx context.Context, filter st // Expected errors during normal operation: // - subscription.ErrBlockNotReady: execution data for the given block height is not available. func (b *EventsBackend) getResponseFactory(filter state_stream.EventFilter) subscription.GetDataByHeightFunc { - return func(ctx context.Context, height uint64) (response any, err error) { + return func(ctx context.Context, height uint64) (response interface{}, err error) { eventsResponse, err := b.eventsProvider.GetAllEventsResponse(ctx, height) if err != nil { if errors.Is(err, storage.ErrNotFound) || diff --git a/engine/access/state_stream/backend/backend_events_test.go b/engine/access/state_stream/backend/backend_events_test.go index 5b4e64ec5b3..6f4181512f8 100644 --- a/engine/access/state_stream/backend/backend_events_test.go +++ b/engine/access/state_stream/backend/backend_events_test.go @@ -338,7 +338,7 @@ func (s *BackendEventsSuite) runTestSubscribeEventsFromLatest() { // 8. Cancels the subscription and ensures it shuts down gracefully. func (s *BackendEventsSuite) subscribe( subscribeFn func(ctx context.Context, startBlockID flow.Identifier, startHeight uint64, filter state_stream.EventFilter) subscription.Subscription, - requireFn func(any, *EventsResponse), + requireFn func(interface{}, *EventsResponse), tests []eventsTestType, ) { ctx, cancel := context.WithCancel(context.Background()) @@ -417,7 +417,7 @@ func (s *BackendEventsSuite) subscribe( } // requireEventsResponse ensures that the received event information matches the expected data. -func (s *BackendEventsSuite) requireEventsResponse(v any, expected *EventsResponse) { +func (s *BackendEventsSuite) requireEventsResponse(v interface{}, expected *EventsResponse) { actual, ok := v.(*EventsResponse) require.True(s.T(), ok, "unexpected response type: %T", v) diff --git a/engine/access/state_stream/backend/backend_executiondata.go b/engine/access/state_stream/backend/backend_executiondata.go index 9aff660a035..954640f3cb9 100644 --- a/engine/access/state_stream/backend/backend_executiondata.go +++ b/engine/access/state_stream/backend/backend_executiondata.go @@ -132,7 +132,7 @@ func (b *ExecutionDataBackend) SubscribeExecutionDataFromLatest(ctx context.Cont return b.subscriptionHandler.Subscribe(ctx, nextHeight, b.getResponse) } -func (b *ExecutionDataBackend) getResponse(ctx context.Context, height uint64) (any, error) { +func (b *ExecutionDataBackend) getResponse(ctx context.Context, height uint64) (interface{}, error) { executionData, err := b.getExecutionData(ctx, height) if err != nil { return nil, fmt.Errorf("could not get execution data for block %d: %w", height, err) diff --git a/engine/access/state_stream/backend/backend_executiondata_test.go b/engine/access/state_stream/backend/backend_executiondata_test.go index 633df65e9b0..f7587affa6d 100644 --- a/engine/access/state_stream/backend/backend_executiondata_test.go +++ b/engine/access/state_stream/backend/backend_executiondata_test.go @@ -98,7 +98,7 @@ func (s *BackendExecutionDataSuite) SetupTest() { var err error parent := s.rootBlock.ToHeader() - for i := range blockCount { + for i := 0; i < blockCount; i++ { block := unittest.BlockWithParentFixture(parent) // update for next iteration parent = block.ToHeader() @@ -109,7 +109,7 @@ func (s *BackendExecutionDataSuite) SetupTest() { numChunks := 5 chunkDatas := make([]*execution_data.ChunkExecutionData, 0, numChunks) - for i := range numChunks { + for i := 0; i < numChunks; i++ { var events flow.EventsList switch { case i >= len(blockEvents.Events): @@ -300,7 +300,7 @@ func generateMockEvents(header *flow.Header, eventCount int) flow.BlockEvents { eventIndex := uint32(0) events := make([]flow.Event, eventCount) - for i := range eventCount { + for i := 0; i < eventCount; i++ { if i > 0 && i%txCount == 0 { txIndex++ txID = unittest.IdentifierFixture() @@ -567,7 +567,7 @@ func (s *BackendExecutionDataSuite) TestSubscribeExecutionFromSporkRootBlock() { ExecutionData: s.execDataMap[s.blocks[0].ID()].BlockExecutionData, } - assertExecutionDataResponse := func(v any, expected *ExecutionDataResponse) { + assertExecutionDataResponse := func(v interface{}, expected *ExecutionDataResponse) { resp, ok := v.(*ExecutionDataResponse) require.True(s.T(), ok, "unexpected response type: %T", v) diff --git a/engine/access/state_stream/backend/handler_test.go b/engine/access/state_stream/backend/handler_test.go index 4d211b63a11..bdf28cda29b 100644 --- a/engine/access/state_stream/backend/handler_test.go +++ b/engine/access/state_stream/backend/handler_test.go @@ -196,7 +196,8 @@ func (s *HandlerTestSuite) TestHeartbeatResponse() { // TestGetExecutionDataByBlockID tests the execution data by block id with different event encoding versions. func TestGetExecutionDataByBlockID(t *testing.T) { - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() ccfEvents, jsonEvents := generateEvents(t, 3) @@ -264,7 +265,8 @@ func TestGetExecutionDataByBlockID(t *testing.T) { func TestExecutionDataStream(t *testing.T) { t.Parallel() - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() // Send a single response. blockHeight := uint64(1) @@ -389,7 +391,8 @@ func TestExecutionDataStream(t *testing.T) { func TestEventStream(t *testing.T) { t.Parallel() - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() blockHeight := uint64(1) blockID := unittest.IdentifierFixture() @@ -510,7 +513,8 @@ func TestEventStream(t *testing.T) { func TestGetRegisterValues(t *testing.T) { t.Parallel() - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() testHeight := uint64(1) diff --git a/engine/access/subscription/streamer_test.go b/engine/access/subscription/streamer_test.go index 16b153e15f4..671c04aae3c 100644 --- a/engine/access/subscription/streamer_test.go +++ b/engine/access/subscription/streamer_test.go @@ -34,7 +34,7 @@ func TestStream(t *testing.T) { sub.On("ID").Return(uuid.NewString()) tests := []testData{} - for i := range 4 { + for i := 0; i < 4; i++ { tests = append(tests, testData{fmt.Sprintf("test%d", i), nil}) } tests = append(tests, testData{"", testErr}) @@ -223,7 +223,7 @@ func TestStreamUnsubscribesOnContextCancel(t *testing.T) { cancels := make([]context.CancelFunc, numStreams) - for i := range numStreams { + for i := 0; i < numStreams; i++ { var ctx context.Context ctx, cancels[i] = context.WithCancel(context.Background()) @@ -247,7 +247,7 @@ func TestStreamUnsubscribesOnContextCancel(t *testing.T) { synctest.Wait() // Cancel streams one by one and verify count decreases - for i := range numStreams { + for i := 0; i < numStreams; i++ { cancels[i]() synctest.Wait() assert.Equal(t, numStreams-i-1, broadcaster.SubscriberCount()) diff --git a/engine/access/subscription/subscription_test.go b/engine/access/subscription/subscription_test.go index 298d78e3cdd..a86422c17fd 100644 --- a/engine/access/subscription/subscription_test.go +++ b/engine/access/subscription/subscription_test.go @@ -26,21 +26,23 @@ func TestSubscription_SendReceive(t *testing.T) { messageCount := 20 messages := []string{} - for i := range messageCount { + for i := 0; i < messageCount; i++ { messages = append(messages, fmt.Sprintf("test messages %d", i)) } receivedCount := 0 wg := sync.WaitGroup{} + wg.Add(1) // receive each message and validate it has the expected value - wg.Go(func() { + go func() { + defer wg.Done() for v := range sub.Channel() { assert.Equal(t, messages[receivedCount], v) receivedCount++ } - }) + }() // send all messages in order for _, d := range messages { @@ -105,7 +107,7 @@ func TestHeightBasedSubscription(t *testing.T) { errNoData := fmt.Errorf("no more data") next := start - getData := func(_ context.Context, height uint64) (any, error) { + getData := func(_ context.Context, height uint64) (interface{}, error) { require.Equal(t, next, height) if height >= last { return nil, errNoData diff --git a/engine/broadcaster_test.go b/engine/broadcaster_test.go index 8f4183aa633..e6f999a4693 100644 --- a/engine/broadcaster_test.go +++ b/engine/broadcaster_test.go @@ -90,14 +90,14 @@ func TestUnsubscribe(t *testing.T) { const numOperations = 100 notifiers := make([]engine.Notifier, numOperations) - for i := range numOperations { + for i := 0; i < numOperations; i++ { notifiers[i] = engine.NewNotifier() } // Subscribe all notifiers concurrently var wg sync.WaitGroup wg.Add(numOperations) - for i := range numOperations { + for i := 0; i < numOperations; i++ { go func(n engine.Notifier) { defer wg.Done() b.Subscribe(n) @@ -109,7 +109,7 @@ func TestUnsubscribe(t *testing.T) { // Unsubscribe all notifiers concurrently wg.Add(numOperations) - for i := range numOperations { + for i := 0; i < numOperations; i++ { go func(n engine.Notifier) { defer wg.Done() b.Unsubscribe(n) @@ -141,7 +141,7 @@ func TestPublish(t *testing.T) { subscribers := sync.WaitGroup{} subscribers.Add(notifierCount) - for range notifierCount { + for i := 0; i < notifierCount; i++ { notifier := engine.NewNotifier() b.Subscribe(notifier) go func() { @@ -172,7 +172,7 @@ func TestPublish(t *testing.T) { subscribers := sync.WaitGroup{} subscribers.Add(notifierCount) - for i := range notifierCount { + for i := 0; i < notifierCount; i++ { notifier := engine.NewNotifier() b.Subscribe(notifier) @@ -194,7 +194,7 @@ func TestPublish(t *testing.T) { publishers := sync.WaitGroup{} publishers.Add(20) - for range 20 { + for i := 0; i < 20; i++ { go func() { defer publishers.Done() b.Publish() diff --git a/engine/collection/compliance/core_test.go b/engine/collection/compliance/core_test.go index 25bfc4940be..aaf44149dc1 100644 --- a/engine/collection/compliance/core_test.go +++ b/engine/collection/compliance/core_test.go @@ -535,7 +535,7 @@ func (cs *CoreSuite) TestProposalBufferingOrder() { var proposals []*cluster.Proposal proposalsLookup := make(map[flow.Identifier]*cluster.Proposal) parent := missing - for range 3 { + for i := 0; i < 3; i++ { block := unittest.ClusterBlockFixture( unittest.ClusterBlock.WithParent(parent), ) diff --git a/engine/collection/compliance/engine_test.go b/engine/collection/compliance/engine_test.go index a466f59f26c..ef050881b46 100644 --- a/engine/collection/compliance/engine_test.go +++ b/engine/collection/compliance/engine_test.go @@ -159,8 +159,9 @@ func (cs *EngineSuite) TearDownTest() { func (cs *EngineSuite) TestSubmittingMultipleEntries() { blockCount := 15 var wg sync.WaitGroup - wg.Go(func() { - for range blockCount { + wg.Add(1) + go func() { + for i := 0; i < blockCount; i++ { block := unittest.ClusterBlockFixture( unittest.ClusterBlock.WithParent(&cs.head.Block), ) @@ -175,8 +176,10 @@ func (cs *EngineSuite) TestSubmittingMultipleEntries() { Message: proposal, }) } - }) - wg.Go(func() { + wg.Done() + }() + wg.Add(1) + go func() { // create a proposal that directly descends from the latest finalized header block := unittest.ClusterBlockFixture( unittest.ClusterBlock.WithParent(&cs.head.Block), @@ -191,7 +194,8 @@ func (cs *EngineSuite) TestSubmittingMultipleEntries() { OriginID: unittest.IdentifierFixture(), Message: proposal, }) - }) + wg.Done() + }() wg.Wait() diff --git a/engine/collection/ingest/engine.go b/engine/collection/ingest/engine.go index adba08851dc..dde2f4753a0 100644 --- a/engine/collection/ingest/engine.go +++ b/engine/collection/ingest/engine.go @@ -134,7 +134,7 @@ func New( // Process processes a transaction message from the network and enqueues the // message. Validation and ingestion is performed in the processQueuedTransactions // worker. -func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event any) error { +func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { select { case <-e.ComponentManager.ShutdownSignal(): e.log.Warn().Msgf("received message from %x after shut down", originID) diff --git a/engine/collection/ingest/rate_limiter.go b/engine/collection/ingest/rate_limiter.go index d31c21f7f67..66733ae03cc 100644 --- a/engine/collection/ingest/rate_limiter.go +++ b/engine/collection/ingest/rate_limiter.go @@ -132,7 +132,7 @@ func RemoveAddresses(r *AddressRateLimiter, addresses []flow.Address) { // parse addresses string into a list of flow addresses func ParseAddresses(addresses string) ([]flow.Address, error) { addressList := make([]flow.Address, 0) - for addr := range strings.SplitSeq(addresses, ",") { + for _, addr := range strings.Split(addresses, ",") { addr = strings.TrimSpace(addr) if addr == "" { continue diff --git a/engine/collection/ingest/rate_limiter_test.go b/engine/collection/ingest/rate_limiter_test.go index a5cb1188c19..38d7d66d9dc 100644 --- a/engine/collection/ingest/rate_limiter_test.go +++ b/engine/collection/ingest/rate_limiter_test.go @@ -69,7 +69,7 @@ func TestLimiterBurst(t *testing.T) { l := ingest.NewAddressRateLimiter(numPerSec, burst) l.AddAddress(limited1) - for i := range burst { + for i := 0; i < burst; i++ { require.False(t, l.IsRateLimited(limited1), fmt.Sprintf("%v-nth call", i)) } @@ -173,7 +173,7 @@ func TestLimiterGetSetConfig(t *testing.T) { l.SetLimitConfig(rate.Limit(20), 4) // verify the quota is reset, and the new limit is applied - for i := range 4 { + for i := 0; i < 4; i++ { require.False(t, l.IsRateLimited(addr1), fmt.Sprintf("fail at %v-th call", i)) } require.True(t, l.IsRateLimited(addr1)) diff --git a/engine/collection/message_hub/message_hub.go b/engine/collection/message_hub/message_hub.go index f8d658f1158..a0b790a537c 100644 --- a/engine/collection/message_hub/message_hub.go +++ b/engine/collection/message_hub/message_hub.go @@ -172,7 +172,7 @@ func NewMessageHub(log zerolog.Logger, // This implementation tolerates if the networking layer sometimes blocks on send requests. // We use by default 5 go-routines here. This is fine, because outbound messages are temporally sparse // under normal operations. Hence, the go-routines should mostly be asleep waiting for work. - for range defaultMessageHubRequestsWorkers { + for i := 0; i < defaultMessageHubRequestsWorkers; i++ { workers.Add(1) componentBuilder.AddWorker(func(ctx irrecoverable.SignalerContext, ready component.ReadyFunc) { defer workers.Done() @@ -449,7 +449,7 @@ func (h *MessageHub) OnOwnProposal(proposal *flow.ProposalHeader, targetPublicat // // Some of the current error returns signal Byzantine behavior, such as forged or malformed // messages. These cases must be logged and routed to a dedicated violation reporting consumer. -func (h *MessageHub) Process(channel channels.Channel, originID flow.Identifier, message any) error { +func (h *MessageHub) Process(channel channels.Channel, originID flow.Identifier, message interface{}) error { switch msg := message.(type) { case *cluster.Proposal: h.compliance.OnClusterBlockProposal(flow.Slashable[*cluster.Proposal]{ diff --git a/engine/collection/synchronization/engine.go b/engine/collection/synchronization/engine.go index 646f30ae8ab..7de58ba6942 100644 --- a/engine/collection/synchronization/engine.go +++ b/engine/collection/synchronization/engine.go @@ -192,7 +192,7 @@ func (e *Engine) Done() <-chan struct{} { } // SubmitLocal submits an event originating on the local node. -func (e *Engine) SubmitLocal(event any) { +func (e *Engine) SubmitLocal(event interface{}) { err := e.ProcessLocal(event) if err != nil { e.log.Fatal().Err(err).Msg("internal error processing event") @@ -202,7 +202,7 @@ func (e *Engine) SubmitLocal(event any) { // Submit submits the given event from the node with the given origin ID // for processing in a non-blocking manner. It returns instantly and logs // a potential processing error internally when done. -func (e *Engine) Submit(channel channels.Channel, originID flow.Identifier, event any) { +func (e *Engine) Submit(channel channels.Channel, originID flow.Identifier, event interface{}) { err := e.Process(channel, originID, event) if err != nil { e.log.Fatal().Err(err).Msg("internal error processing event") @@ -210,13 +210,13 @@ func (e *Engine) Submit(channel channels.Channel, originID flow.Identifier, even } // ProcessLocal processes an event originating on the local node. -func (e *Engine) ProcessLocal(event any) error { +func (e *Engine) ProcessLocal(event interface{}) error { return e.process(e.me.NodeID(), event) } // Process processes the given event from the node with the given origin ID in // a blocking manner. It returns the potential processing error when done. -func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event any) error { +func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { err := e.process(originID, event) if err != nil { if engine.IsIncompatibleInputTypeError(err) { @@ -232,7 +232,7 @@ func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, eve // Error returns: // - IncompatibleInputTypeError if input has unexpected type // - All other errors are potential symptoms of internal state corruption or bugs (fatal). -func (e *Engine) process(originID flow.Identifier, event any) error { +func (e *Engine) process(originID flow.Identifier, event interface{}) error { switch event.(type) { case *flow.RangeRequest, *flow.BatchRequest, *flow.SyncRequest: return e.requestHandler.process(originID, event) diff --git a/engine/collection/synchronization/engine_test.go b/engine/collection/synchronization/engine_test.go index 513e7f2960b..7ae5df6d38c 100644 --- a/engine/collection/synchronization/engine_test.go +++ b/engine/collection/synchronization/engine_test.go @@ -560,7 +560,7 @@ func (ss *SyncSuite) TestProcessingMultipleItems() { <-ss.e.Ready() originID := unittest.IdentifierFixture() - for i := range 5 { + for i := 0; i < 5; i++ { msg := &flow.SyncResponse{ Nonce: uint64(i), Height: uint64(1000 + i), @@ -573,7 +573,7 @@ func (ss *SyncSuite) TestProcessingMultipleItems() { } finalHeight := ss.head.Height - for i := range 5 { + for i := 0; i < 5; i++ { msg := &flow.SyncRequest{ Nonce: uint64(i), Height: finalHeight - 100, diff --git a/engine/collection/synchronization/request_handler.go b/engine/collection/synchronization/request_handler.go index 7e527e056d4..428af23aaee 100644 --- a/engine/collection/synchronization/request_handler.go +++ b/engine/collection/synchronization/request_handler.go @@ -79,7 +79,7 @@ func NewRequestHandlerEngine( } // SubmitLocal submits an event originating on the local node. -func (r *RequestHandlerEngine) SubmitLocal(event any) { +func (r *RequestHandlerEngine) SubmitLocal(event interface{}) { err := r.ProcessLocal(event) if err != nil { r.log.Fatal().Err(err).Msg("internal error processing event") @@ -89,7 +89,7 @@ func (r *RequestHandlerEngine) SubmitLocal(event any) { // Submit submits the given event from the node with the given origin ID // for processing in a non-blocking manner. It returns instantly and logs // a potential processing error internally when done. -func (r *RequestHandlerEngine) Submit(channel channels.Channel, originID flow.Identifier, event any) { +func (r *RequestHandlerEngine) Submit(channel channels.Channel, originID flow.Identifier, event interface{}) { err := r.Process(channel, originID, event) if err != nil { r.log.Fatal().Err(err).Msg("internal error processing event") @@ -97,13 +97,13 @@ func (r *RequestHandlerEngine) Submit(channel channels.Channel, originID flow.Id } // ProcessLocal processes an event originating on the local node. -func (r *RequestHandlerEngine) ProcessLocal(event any) error { +func (r *RequestHandlerEngine) ProcessLocal(event interface{}) error { return r.process(r.me.NodeID(), event) } // Process processes the given event from the node with the given origin ID in // a blocking manner. It returns the potential processing error when done. -func (r *RequestHandlerEngine) Process(channel channels.Channel, originID flow.Identifier, event any) error { +func (r *RequestHandlerEngine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { err := r.process(originID, event) if err != nil { if engine.IsIncompatibleInputTypeError(err) { @@ -119,7 +119,7 @@ func (r *RequestHandlerEngine) Process(channel channels.Channel, originID flow.I // Error returns: // - IncompatibleInputTypeError if input has unexpected type // - All other errors are potential symptoms of internal state corruption or bugs (fatal). -func (r *RequestHandlerEngine) process(originID flow.Identifier, event any) error { +func (r *RequestHandlerEngine) process(originID flow.Identifier, event interface{}) error { return r.requestMessageHandler.Process(originID, event) } @@ -399,7 +399,7 @@ func (r *RequestHandlerEngine) requestProcessingLoop() { // Ready returns a ready channel that is closed once the engine has fully started. func (r *RequestHandlerEngine) Ready() <-chan struct{} { r.lm.OnStart(func() { - for range defaultEngineRequestsWorkers { + for i := 0; i < defaultEngineRequestsWorkers; i++ { r.unit.Launch(r.requestProcessingLoop) } }) diff --git a/engine/common/follower/cache/cache_test.go b/engine/common/follower/cache/cache_test.go index 02a1e75bbaa..fa96d4ec9e4 100644 --- a/engine/common/follower/cache/cache_test.go +++ b/engine/common/follower/cache/cache_test.go @@ -236,10 +236,10 @@ func (s *CacheSuite) TestConcurrentAdd() { var certifiedBlocksLock sync.Mutex var allCertifiedBlocks []flow.CertifiedBlock - for i := range workers { + for i := 0; i < workers; i++ { go func(blocks []*flow.Proposal) { defer wg.Done() - for batch := range batchesPerWorker { + for batch := 0; batch < batchesPerWorker; batch++ { certifiedBlocks, err := s.cache.AddBlocks(blocks[batch*blocksPerBatch : (batch+1)*blocksPerBatch]) require.NoError(s.T(), err) certifiedBlocksLock.Lock() @@ -354,7 +354,7 @@ func (s *CacheSuite) TestAddOverCacheLimit() { var wg sync.WaitGroup wg.Add(workers) - for i := range workers { + for i := 0; i < workers; i++ { go func(blocks []*flow.Proposal) { defer wg.Done() for !done.Load() { diff --git a/engine/common/follower/compliance_core_test.go b/engine/common/follower/compliance_core_test.go index f03e75518b3..a0aad9e24ea 100644 --- a/engine/common/follower/compliance_core_test.go +++ b/engine/common/follower/compliance_core_test.go @@ -303,10 +303,10 @@ func (s *CoreSuite) TestConcurrentAdd() { var wg sync.WaitGroup wg.Add(workers) - for i := range workers { + for i := 0; i < workers; i++ { go func(blocks []*flow.Proposal) { defer wg.Done() - for batch := range batchesPerWorker { + for batch := 0; batch < batchesPerWorker; batch++ { err := s.core.OnBlockRange(s.originID, blocks[batch*blocksPerBatch:(batch+1)*blocksPerBatch]) require.NoError(s.T(), err) } @@ -318,6 +318,6 @@ func (s *CoreSuite) TestConcurrentAdd() { } // blockWithID returns a testify `argumentMatcher` that only accepts blocks with the given ID -func blockWithID(expectedBlockID flow.Identifier) any { +func blockWithID(expectedBlockID flow.Identifier) interface{} { return mock.MatchedBy(func(block *model.CertifiedBlock) bool { return expectedBlockID == block.BlockID() }) } diff --git a/engine/common/follower/compliance_engine.go b/engine/common/follower/compliance_engine.go index 810ff4ca591..4f635e076f3 100644 --- a/engine/common/follower/compliance_engine.go +++ b/engine/common/follower/compliance_engine.go @@ -169,7 +169,7 @@ func NewComplianceLayer( <-e.core.Done() }) - for range defaultBatchProcessingWorkers { + for i := 0; i < defaultBatchProcessingWorkers; i++ { cmBuilder.AddWorker(e.processConnectedBatch) } e.ComponentManager = cmBuilder.Build() @@ -227,7 +227,7 @@ func (e *ComplianceEngine) onFinalizedBlock(block *model.Block) { // // Some of the current error returns signal Byzantine behavior, such as forged or malformed // messages. These cases must be logged and routed to a dedicated violation reporting consumer. -func (e *ComplianceEngine) Process(channel channels.Channel, originID flow.Identifier, message any) error { +func (e *ComplianceEngine) Process(channel channels.Channel, originID flow.Identifier, message interface{}) error { switch msg := message.(type) { case *flow.Proposal: e.OnBlockProposal(flow.Slashable[*flow.Proposal]{ diff --git a/engine/common/follower/integration_test.go b/engine/common/follower/integration_test.go index da60f06d3a5..b94522ef76f 100644 --- a/engine/common/follower/integration_test.go +++ b/engine/common/follower/integration_test.go @@ -236,11 +236,11 @@ func runTestFollowerHappyPath(t *testing.T) { submittingBlocks := atomic.NewBool(true) var wg sync.WaitGroup wg.Add(workers) - for i := range workers { + for i := 0; i < workers; i++ { go func(blocks []*flow.Proposal) { defer wg.Done() for submittingBlocks.Load() { - for batch := range batchesPerWorker { + for batch := 0; batch < batchesPerWorker; batch++ { engine.OnSyncedBlocks(flow.Slashable[[]*flow.Proposal]{ OriginID: originID, Message: blocks[batch*blocksPerBatch : (batch+1)*blocksPerBatch], diff --git a/engine/common/grpc/forwarder/forwarder.go b/engine/common/grpc/forwarder/forwarder.go index 46225ecfd2c..b685fefe780 100644 --- a/engine/common/grpc/forwarder/forwarder.go +++ b/engine/common/grpc/forwarder/forwarder.go @@ -91,7 +91,7 @@ func (f *Forwarder) FaultTolerantClient() (access.AccessAPIClient, io.Closer, er defer f.lock.Unlock() var err error - for range retryMax { + for i := 0; i < retryMax; i++ { f.roundRobin++ f.roundRobin = f.roundRobin % len(f.upstream) err = f.reconnectingClient(f.roundRobin) diff --git a/engine/common/requester/engine.go b/engine/common/requester/engine.go index c361ab14c1f..a5b2cb5fa0c 100644 --- a/engine/common/requester/engine.go +++ b/engine/common/requester/engine.go @@ -197,7 +197,7 @@ func (e *Engine) WithHandle(handle HandleFunc) { // For inputs of unexpected type, a warning is logged and the message is dropped. // // No error returns are expected during normal operations. -func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event any) error { +func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { select { case <-e.ShutdownSignal(): e.log.Warn(). @@ -471,11 +471,15 @@ func (e *Engine) dispatchRequest() (bool, error) { entityIDs = append(entityIDs, entityID) item.NumAttempts++ item.LastRequested = now - item.RetryAfter = min( - // make sure the interval is within parameters - max( + item.RetryAfter = e.cfg.RetryFunction(item.RetryAfter) - e.cfg.RetryFunction(item.RetryAfter), e.cfg.RetryInitial), e.cfg.RetryMaximum) + // make sure the interval is within parameters + if item.RetryAfter < e.cfg.RetryInitial { + item.RetryAfter = e.cfg.RetryInitial + } + if item.RetryAfter > e.cfg.RetryMaximum { + item.RetryAfter = e.cfg.RetryMaximum + } // if we reached the maximum size for a batch, bail if uint(len(entityIDs)) >= e.cfg.BatchThreshold { diff --git a/engine/common/requester/engine_test.go b/engine/common/requester/engine_test.go index 04f73551b5d..871a5aaec52 100644 --- a/engine/common/requester/engine_test.go +++ b/engine/common/requester/engine_test.go @@ -211,7 +211,7 @@ func (s *RequesterEngineSuite) TestDispatchRequestBatchSize() { } // item that has just been added, should be included - for range totalItems { + for i := uint(0); i < totalItems; i++ { item := &Request{ QueryKey: unittest.IdentifierFixture(), NumAttempts: 0, diff --git a/engine/common/rpc/convert/events_test.go b/engine/common/rpc/convert/events_test.go index 7978de5d5cc..7db322f80d4 100644 --- a/engine/common/rpc/convert/events_test.go +++ b/engine/common/rpc/convert/events_test.go @@ -103,7 +103,7 @@ func TestConvertEvents(t *testing.T) { events := make([]flow.Event, eventCount) ccfEvents := make([]flow.Event, eventCount) jsonEvents := make([]flow.Event, eventCount) - for i := range eventCount { + for i := 0; i < eventCount; i++ { cadenceValue := cadence.NewInt(i) ccfPayload, err := ccf.Encode(cadenceValue) @@ -220,7 +220,7 @@ func TestConvertMessagesToBlockEvents(t *testing.T) { count := 2 blockEvents := make([]flow.BlockEvents, count) - for i := range count { + for i := 0; i < count; i++ { header := unittest.BlockHeaderFixture(unittest.WithHeaderHeight(uint64(i))) blockEvents[i] = unittest.BlockEventsFixture(header, 2) } diff --git a/engine/common/rpc/convert/execution_data_test.go b/engine/common/rpc/convert/execution_data_test.go index 92d3db1b39f..2d8ec9d5eb1 100644 --- a/engine/common/rpc/convert/execution_data_test.go +++ b/engine/common/rpc/convert/execution_data_test.go @@ -222,6 +222,7 @@ func TestMessageToRegisterID(t *testing.T) { messages := make([]*entities.RegisterID, len(expected)) for i, regID := range expected { + regID := regID messages[i] = convert.RegisterIDToMessage(regID) require.Equal(t, regID.Owner, string(messages[i].Owner)) require.Equal(t, regID.Key, string(messages[i].Key)) diff --git a/engine/common/rpc/execution_node_identities_provider.go b/engine/common/rpc/execution_node_identities_provider.go index 2037036ee60..aa6d514447f 100644 --- a/engine/common/rpc/execution_node_identities_provider.go +++ b/engine/common/rpc/execution_node_identities_provider.go @@ -94,7 +94,7 @@ func (e *ExecutionNodeIdentitiesProvider) ExecutionNodesForBlockID( executorIDs = executorIdentities.NodeIDs() } else { // try to find at least minExecutionNodesCnt execution node ids from the execution receipts for the given blockID - for attempt := range maxAttemptsForExecutionReceipt { + for attempt := 0; attempt < maxAttemptsForExecutionReceipt; attempt++ { executorIDs, err = e.findAllExecutionNodes(blockID) if err != nil { return nil, err diff --git a/engine/common/rpc/execution_node_identities_provider_test.go b/engine/common/rpc/execution_node_identities_provider_test.go index dd67fa71cb8..4b86b1cb1f6 100644 --- a/engine/common/rpc/execution_node_identities_provider_test.go +++ b/engine/common/rpc/execution_node_identities_provider_test.go @@ -61,7 +61,7 @@ func (suite *ENIdentitiesProviderSuite) TestExecutionNodesForBlockID() { // generate execution receipts receipts := make(flow.ExecutionReceiptList, totalReceipts) - for j := range totalReceipts { + for j := 0; j < totalReceipts; j++ { r := unittest.ReceiptForBlockFixture(block) r.ExecutorID = allExecutionNodes[j].NodeID r.ExecutionResult = executionResult diff --git a/engine/common/synchronization/engine.go b/engine/common/synchronization/engine.go index 4b75c78ed52..cc6ec369064 100644 --- a/engine/common/synchronization/engine.go +++ b/engine/common/synchronization/engine.go @@ -124,7 +124,7 @@ func New( AddWorker(finalizedCacheWorker). AddWorker(e.checkLoop). AddWorker(e.responseProcessingLoop) - for range defaultEngineRequestsWorkers { + for i := 0; i < defaultEngineRequestsWorkers; i++ { builder.AddWorker(e.requestHandler.requestProcessingWorker) } e.Component = builder.Build() @@ -191,7 +191,7 @@ func (e *Engine) setupResponseMessageHandler() error { // Process processes the given event from the node with the given origin ID in // a blocking manner. It returns the potential processing error when done. -func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event any) error { +func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { err := e.process(channel, originID, event) if err != nil { if engine.IsIncompatibleInputTypeError(err) { @@ -207,7 +207,7 @@ func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, eve // Error returns: // - IncompatibleInputTypeError if input has unexpected type // - All other errors are potential symptoms of internal state corruption or bugs (fatal). -func (e *Engine) process(channel channels.Channel, originID flow.Identifier, event any) error { +func (e *Engine) process(channel channels.Channel, originID flow.Identifier, event interface{}) error { switch message := event.(type) { case *flow.BatchRequest: err := e.validateBatchRequestForALSP(originID, message) diff --git a/engine/common/synchronization/engine_spam_test.go b/engine/common/synchronization/engine_spam_test.go index 571ae9808be..91037a3c3ed 100644 --- a/engine/common/synchronization/engine_spam_test.go +++ b/engine/common/synchronization/engine_spam_test.go @@ -33,7 +33,7 @@ func (ss *SyncSuite) TestLoad_Process_SyncRequest_HigherThanReceiver_OutsideTole // reset misbehavior report counter for each subtest misbehaviorsCounter := 0 - for range load { + for i := 0; i < load; i++ { // generate origin and request message originID := unittest.IdentifierFixture() @@ -123,7 +123,7 @@ func (ss *SyncSuite) TestLoad_Process_SyncRequest_HigherThanReceiver_OutsideTole for _, loadGroup := range loadGroups { ss.T().Run(fmt.Sprintf("load test; pfactor=%f lower=%d upper=%d", loadGroup.syncRequestProbabilityFactor, loadGroup.expectedMisbehaviorsLower, loadGroup.expectedMisbehaviorsUpper), func(t *testing.T) { - for i := range load { + for i := 0; i < load; i++ { ss.T().Log("load iteration", i) nonce, err := rand.Uint64() require.NoError(ss.T(), err, "should generate nonce") @@ -239,7 +239,7 @@ func (ss *SyncSuite) TestLoad_Process_RangeRequest_SometimesReportSpam() { misbehaviorsCounter := 0 for _, loadGroup := range loadGroups { - for i := range load { + for i := 0; i < load; i++ { ss.T().Log("load iteration", i) nonce, err := rand.Uint64() @@ -339,7 +339,7 @@ func (ss *SyncSuite) TestLoad_Process_BatchRequest_SometimesReportSpam() { // reset misbehavior report counter for each subtest misbehaviorsCounter := 0 for _, loadGroup := range loadGroups { - for i := range load { + for i := 0; i < load; i++ { ss.T().Log("load iteration", i) nonce, err := rand.Uint64() @@ -388,7 +388,7 @@ func repeatedBlockIDs(n int) []flow.Identifier { blockID := unittest.BlockFixture().ID() arr := make([]flow.Identifier, n) - for i := range n { + for i := 0; i < n; i++ { arr[i] = blockID } return arr diff --git a/engine/common/synchronization/engine_test.go b/engine/common/synchronization/engine_test.go index aa431e02330..2f5c399c6f8 100644 --- a/engine/common/synchronization/engine_test.go +++ b/engine/common/synchronization/engine_test.go @@ -465,7 +465,7 @@ func (ss *SyncSuite) TestProcessingMultipleItems() { defer cancel() originID := unittest.IdentifierFixture() - for i := range 5 { + for i := 0; i < 5; i++ { msg := &flow.SyncResponse{ Nonce: uint64(i), Height: uint64(1000 + i), @@ -479,7 +479,7 @@ func (ss *SyncSuite) TestProcessingMultipleItems() { } finalHeight := ss.head.Height - for i := range 5 { + for i := 0; i < 5; i++ { msg := &flow.SyncRequest{ Nonce: uint64(i), Height: finalHeight - 100, diff --git a/engine/common/synchronization/request_handler.go b/engine/common/synchronization/request_handler.go index 5bf6fc45422..75367e0d616 100644 --- a/engine/common/synchronization/request_handler.go +++ b/engine/common/synchronization/request_handler.go @@ -90,7 +90,7 @@ func NewRequestHandler( // Process processes the given event from the node with the given origin ID in a blocking manner. // No errors are expected during normal operation. -func (r *RequestHandler) Process(channel channels.Channel, originID flow.Identifier, event any) error { +func (r *RequestHandler) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { err := r.requestMessageHandler.Process(originID, event) if err != nil { if engine.IsIncompatibleInputTypeError(err) { diff --git a/engine/common/synchronization/request_handler_engine.go b/engine/common/synchronization/request_handler_engine.go index 7f157f8322a..72321306466 100644 --- a/engine/common/synchronization/request_handler_engine.go +++ b/engine/common/synchronization/request_handler_engine.go @@ -18,14 +18,14 @@ import ( ) type ResponseSender interface { - SendResponse(any, flow.Identifier) error + SendResponse(interface{}, flow.Identifier) error } type ResponseSenderImpl struct { con network.Conduit } -func (r *ResponseSenderImpl) SendResponse(res any, target flow.Identifier) error { +func (r *ResponseSenderImpl) SendResponse(res interface{}, target flow.Identifier) error { switch res.(type) { case *messages.BlockResponse: err := r.con.Unicast(res, target) @@ -98,7 +98,7 @@ func NewRequestHandlerEngine( false, ) builder := component.NewComponentManagerBuilder().AddWorker(finalizedCacheWorker) - for range defaultEngineRequestsWorkers { + for i := 0; i < defaultEngineRequestsWorkers; i++ { builder.AddWorker(e.requestHandler.requestProcessingWorker) } e.Component = builder.Build() @@ -110,6 +110,6 @@ func NewRequestHandlerEngine( return e, nil } -func (r *RequestHandlerEngine) Process(channel channels.Channel, originID flow.Identifier, event any) error { +func (r *RequestHandlerEngine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { return r.requestHandler.Process(channel, originID, event) } diff --git a/engine/common/synchronization/request_heap_test.go b/engine/common/synchronization/request_heap_test.go index 03bf4281605..dfef48c2d12 100644 --- a/engine/common/synchronization/request_heap_test.go +++ b/engine/common/synchronization/request_heap_test.go @@ -15,7 +15,7 @@ func TestRequestQueue_Get(t *testing.T) { q := NewRequestHeap(100) items := 20 messages := make(map[flow.Identifier]*engine.Message) - for range items { + for i := 0; i < items; i++ { msg := &engine.Message{ OriginID: unittest.IdentifierFixture(), Payload: unittest.IdentifierFixture(), @@ -24,7 +24,7 @@ func TestRequestQueue_Get(t *testing.T) { require.True(t, q.Put(msg)) } - for range items { + for i := 0; i < items; i++ { msg, ok := q.Get() require.True(t, ok) expected, ok := messages[msg.OriginID] @@ -77,7 +77,7 @@ func TestRequestQueue_PutAtMaxCapacity(t *testing.T) { // 10 of these elements. By convention, the last-inserted element should be stored (no // ejecting the just stored element). lastMessagePopped := false - for range limit { + for k := uint(0); k < limit; k++ { m, ok := q.Get() require.True(t, ok) diff --git a/engine/common/version/version_control_test.go b/engine/common/version/version_control_test.go index 46b67f5d8e8..5e1db72b919 100644 --- a/engine/common/version/version_control_test.go +++ b/engine/common/version/version_control_test.go @@ -37,7 +37,8 @@ type testCaseConfig struct { // TestVersionControlInitialization tests the initialization process of the VersionControl component func TestVersionControlInitialization(t *testing.T) { - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() sealedRootBlockHeight := uint64(1000) latestBlockHeight := sealedRootBlockHeight + 100 @@ -354,7 +355,8 @@ func TestVersionControlStartHeight(t *testing.T) { // TestVersionControlInitializationWithErrors tests the initialization process of the VersionControl component with error cases func TestVersionControlInitializationWithErrors(t *testing.T) { - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() sealedRootBlockHeight := uint64(1000) latestBlockHeight := sealedRootBlockHeight + 100 diff --git a/engine/common/worker/worker_builder_test.go b/engine/common/worker/worker_builder_test.go index a290b9744ea..e1a0d95b436 100644 --- a/engine/common/worker/worker_builder_test.go +++ b/engine/common/worker/worker_builder_test.go @@ -89,7 +89,7 @@ func TestWorkerBuilder_UnhappyPaths(t *testing.T) { unittest.RequireCloseBefore(t, firstEventArrived, 100*time.Millisecond, "first event not distributed") // now the worker is blocked, we submit the rest of the events so that the queue is full - for i := range size { + for i := 0; i < size; i++ { event := fmt.Sprintf("test-event-%d", i) require.True(t, pool.Submit(event)) // we also check that re-submitting the same event fails as duplicate event already is in the queue. @@ -111,7 +111,7 @@ func TestWorkerPool_TwoWorkers_ConcurrentEvents(t *testing.T) { tc := make([]string, size) - for i := range size { + for i := 0; i < size; i++ { tc[i] = fmt.Sprintf("test-event-%d", i) } @@ -147,7 +147,7 @@ func TestWorkerPool_TwoWorkers_ConcurrentEvents(t *testing.T) { unittest.RequireCloseBefore(t, cm.Ready(), 100*time.Millisecond, "could not start worker") - for i := range size { + for i := 0; i < size; i++ { go func(i int) { require.True(t, pool.Submit(tc[i])) }(i) diff --git a/engine/consensus/approvals/aggregated_signatures_test.go b/engine/consensus/approvals/aggregated_signatures_test.go index 9022e75fa9d..1ea8d6846a9 100644 --- a/engine/consensus/approvals/aggregated_signatures_test.go +++ b/engine/consensus/approvals/aggregated_signatures_test.go @@ -114,7 +114,7 @@ func TestAggregatedSignatures_PutSignature_Sequence(t *testing.T) { sigs, err := NewAggregatedSignatures(chunks) require.NoError(t, err) - for index := range chunks { + for index := uint64(0); index < chunks; index++ { n, err := sigs.PutSignature(index, flow.AggregatedSignature{}) require.NoError(t, err) require.Equal(t, n, index+1) @@ -132,7 +132,7 @@ func TestAggregatedSignatures_Collect(t *testing.T) { // collecting over signatures with missing chunks results in empty array require.Len(t, sigs.Collect(), int(chunks)) - for index := range chunks { + for index := uint64(0); index < chunks; index++ { _, err := sigs.PutSignature(index, sig) require.NoError(t, err) require.Len(t, sigs.Collect(), int(chunks)) diff --git a/engine/consensus/approvals/approval_collector.go b/engine/consensus/approvals/approval_collector.go index c42a32c3a6c..03447ec91ba 100644 --- a/engine/consensus/approvals/approval_collector.go +++ b/engine/consensus/approvals/approval_collector.go @@ -71,7 +71,7 @@ func NewApprovalCollector( // The high-level logic is: as soon as we have collected enough approvals, we aggregate // them and store them in collector.aggregatedSignatures. If we don't require any signatures, // this condition is satisfied right away. Hence, we add aggregated signature for each chunk. - for i := range numberOfChunks { + for i := uint64(0); i < numberOfChunks; i++ { _, err := collector.aggregatedSignatures.PutSignature(i, flow.AggregatedSignature{}) if err != nil { return nil, fmt.Errorf("sealing result %x failed: %w", result.ID(), err) diff --git a/engine/consensus/approvals/approvals_lru_cache_test.go b/engine/consensus/approvals/approvals_lru_cache_test.go index 42f8c0726bb..9b08c1a0bd7 100644 --- a/engine/consensus/approvals/approvals_lru_cache_test.go +++ b/engine/consensus/approvals/approvals_lru_cache_test.go @@ -37,10 +37,12 @@ func TestApprovalsLRUCacheSecondaryIndexPurgeConcurrently(t *testing.T) { var wg sync.WaitGroup for i := 0; i < 2*numElements; i++ { - wg.Go(func() { + wg.Add(1) + go func() { + defer wg.Done() approval := unittest.ResultApprovalFixture() cache.Put(approval) - }) + }() } wg.Wait() require.Len(t, cache.byResultID, int(numElements)) diff --git a/engine/consensus/approvals/assignment_collector_tree_test.go b/engine/consensus/approvals/assignment_collector_tree_test.go index b469e8c3a2b..0c84a7abbe4 100644 --- a/engine/consensus/approvals/assignment_collector_tree_test.go +++ b/engine/consensus/approvals/assignment_collector_tree_test.go @@ -109,10 +109,10 @@ func (s *AssignmentCollectorTreeSuite) TestGetSize_ConcurrentAccess() { var wg sync.WaitGroup wg.Add(numberOfWorkers) - for worker := range numberOfWorkers { + for worker := 0; worker < numberOfWorkers; worker++ { go func(workerIndex int) { defer wg.Done() - for i := range batchSize { + for i := 0; i < batchSize; i++ { result := &receipts[workerIndex*batchSize+i].ExecutionResult collector, err := s.collectorTree.GetOrCreateCollector(result) require.NoError(s.T(), err) @@ -233,7 +233,7 @@ func (s *AssignmentCollectorTreeSuite) TestGetOrCreateCollector_AddingSealedColl // generate a few sealed blocks prevSealedBlock := block.ToHeader() - for range 5 { + for i := 0; i < 5; i++ { sealedBlock := unittest.BlockHeaderWithParentFixture(prevSealedBlock) s.MarkFinalized(sealedBlock) _ = s.collectorTree.FinalizeForkAtLevel(sealedBlock, sealedBlock) @@ -270,7 +270,7 @@ func (s *AssignmentCollectorTreeSuite) TestFinalizeForkAtLevel_ProcessableAfterS unittest.WithPreviousResult(*s.IncorporatedResult.Result), unittest.WithExecutionResultBlockID(s.IncorporatedBlock.ID())) s.prepareMockedCollector(firstResult) - for i := range forks { + for i := 0; i < len(forks); i++ { fork := unittest.ChainFixtureFrom(3, s.IncorporatedBlock) forks[i] = fork prevResult := firstResult diff --git a/engine/consensus/approvals/caching_assignment_collector_test.go b/engine/consensus/approvals/caching_assignment_collector_test.go index eba7125f4d1..2a27faeb018 100644 --- a/engine/consensus/approvals/caching_assignment_collector_test.go +++ b/engine/consensus/approvals/caching_assignment_collector_test.go @@ -56,7 +56,7 @@ func (s *CachingAssignmentCollectorTestSuite) TestProcessApproval() { require.True(s.T(), engine.IsInvalidInputError(err)) var expected []*flow.ResultApproval - for i := range 5 { + for i := 0; i < 5; i++ { approval := unittest.ResultApprovalFixture( unittest.WithBlockID(s.executedBlock.ID()), unittest.WithExecutionResultID(s.result.ID()), @@ -78,7 +78,7 @@ func (s *CachingAssignmentCollectorTestSuite) TestProcessIncorporatedResult() { // processing valid IR should result in no error var expected []*flow.IncorporatedResult - for range 5 { + for i := 0; i < 5; i++ { IR := unittest.IncorporatedResult.Fixture( unittest.IncorporatedResult.WithResult(s.result), ) diff --git a/engine/consensus/approvals/request_tracker_test.go b/engine/consensus/approvals/request_tracker_test.go index 7dbe68a4719..4661f6e8c0c 100644 --- a/engine/consensus/approvals/request_tracker_test.go +++ b/engine/consensus/approvals/request_tracker_test.go @@ -42,7 +42,7 @@ func (s *RequestTrackerTestSuite) TestTryUpdate_CreateAndUpdate() { s.headers.On("ByBlockID", executedBlock.ID()).Return(executedBlock.ToHeader(), nil) result := unittest.ExecutionResultFixture(unittest.WithBlock(executedBlock)) chunks := 5 - for i := range chunks { + for i := 0; i < chunks; i++ { _, updated, err := s.tracker.TryUpdate(result, executedBlock.ID(), uint64(i)) require.NoError(s.T(), err) require.False(s.T(), updated) @@ -51,7 +51,7 @@ func (s *RequestTrackerTestSuite) TestTryUpdate_CreateAndUpdate() { // wait for maximum blackout period time.Sleep(time.Second * 3) - for i := range chunks { + for i := 0; i < chunks; i++ { item, updated, err := s.tracker.TryUpdate(result, executedBlock.ID(), uint64(i)) require.NoError(s.T(), err) require.True(s.T(), updated) @@ -69,19 +69,21 @@ func (s *RequestTrackerTestSuite) TestTryUpdate_ConcurrentTracking() { result := unittest.ExecutionResultFixture(unittest.WithBlock(executedBlock)) chunks := 5 var wg sync.WaitGroup - for range 10 { - wg.Go(func() { - for i := range chunks { + for times := 0; times < 10; times++ { + wg.Add(1) + go func() { + for i := 0; i < chunks; i++ { _, updated, err := s.tracker.TryUpdate(result, executedBlock.ID(), uint64(i)) require.NoError(s.T(), err) require.True(s.T(), updated) } - }) + wg.Done() + }() } wg.Wait() - for i := range chunks { + for i := 0; i < chunks; i++ { tracker, ok := s.tracker.index[result.ID()][executedBlock.ID()][uint64(i)] require.True(s.T(), ok) require.Equal(s.T(), uint(10), tracker.Requests) diff --git a/engine/consensus/approvals/testutil/testutil.go b/engine/consensus/approvals/testutil/testutil.go index a24edcb80e3..97420f1072a 100644 --- a/engine/consensus/approvals/testutil/testutil.go +++ b/engine/consensus/approvals/testutil/testutil.go @@ -50,7 +50,7 @@ func (s *BaseApprovalsTestSuite) SetupTest() { s.PublicKey = &module.PublicKey{} // setup identities - for range 5 { + for j := 0; j < 5; j++ { identity := unittest.IdentityFixture(unittest.WithRole(flow.RoleVerification)) verifiers = append(verifiers, identity.NodeID) s.AuthorizedVerifiers[identity.NodeID] = identity diff --git a/engine/consensus/approvals/tracker/record.go b/engine/consensus/approvals/tracker/record.go index 4135c8475eb..9c240ca6bf1 100644 --- a/engine/consensus/approvals/tracker/record.go +++ b/engine/consensus/approvals/tracker/record.go @@ -4,7 +4,6 @@ import ( "encoding/hex" "encoding/json" "fmt" - "maps" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/storage" @@ -57,7 +56,9 @@ func (r *SealingRecord) ApprovalsRequested(requestCount uint) { // plus auxiliary data. func (r *SealingRecord) Generate() (Rec, error) { rec := make(Rec) - maps.Copy(rec, r.entries) + for k, v := range r.entries { + rec[k] = v + } irID := r.IncorporatedResult.ID() result := r.IncorporatedResult.Result diff --git a/engine/consensus/approvals/verifying_assignment_collector_test.go b/engine/consensus/approvals/verifying_assignment_collector_test.go index 86b13ffb12a..3d1208c22f7 100644 --- a/engine/consensus/approvals/verifying_assignment_collector_test.go +++ b/engine/consensus/approvals/verifying_assignment_collector_test.go @@ -320,7 +320,7 @@ func (s *AssignmentCollectorTestSuite) TestRequestMissingApprovals() { incorporatedBlocks := make([]*flow.Header, 0) lastHeight := uint64(rand.Uint32()) - for range 2 { + for i := 0; i < 2; i++ { incorporatedBlock := unittest.BlockHeaderFixture() incorporatedBlock.Height = lastHeight lastHeight++ diff --git a/engine/consensus/compliance/core_test.go b/engine/consensus/compliance/core_test.go index a5b6e19dd43..23b98835ae2 100644 --- a/engine/consensus/compliance/core_test.go +++ b/engine/consensus/compliance/core_test.go @@ -580,7 +580,7 @@ func (cs *CoreSuite) TestProposalBufferingOrder() { // create a chain of descendants var proposals []*flow.Proposal parent := missingProposal - for range 3 { + for i := 0; i < 3; i++ { descendant := unittest.BlockWithParentFixture(parent.Block.ToHeader()) proposal := unittest.ProposalFromBlock(descendant) proposals = append(proposals, proposal) diff --git a/engine/consensus/compliance/engine_test.go b/engine/consensus/compliance/engine_test.go index a10248423e7..9f7062faa45 100644 --- a/engine/consensus/compliance/engine_test.go +++ b/engine/consensus/compliance/engine_test.go @@ -66,8 +66,9 @@ func (cs *EngineSuite) TestSubmittingMultipleEntries() { blockCount := 15 var wg sync.WaitGroup - wg.Go(func() { - for range blockCount { + wg.Add(1) + go func() { + for i := 0; i < blockCount; i++ { block := unittest.BlockWithParentFixture(cs.head) proposal := unittest.ProposalFromBlock(block) hotstuffProposal := model.SignedProposalFromBlock(proposal) @@ -80,8 +81,10 @@ func (cs *EngineSuite) TestSubmittingMultipleEntries() { Message: proposal, }) } - }) - wg.Go(func() { + wg.Done() + }() + wg.Add(1) + go func() { // create a proposal that directly descends from the latest finalized header block := unittest.BlockWithParentFixture(cs.head) proposal := unittest.ProposalFromBlock(block) @@ -94,7 +97,8 @@ func (cs *EngineSuite) TestSubmittingMultipleEntries() { OriginID: unittest.IdentifierFixture(), Message: proposal, }) - }) + wg.Done() + }() // wait for all messages to be delivered to the engine message queue wg.Wait() diff --git a/engine/consensus/ingestion/engine.go b/engine/consensus/ingestion/engine.go index 3145894d04f..e556fc2f766 100644 --- a/engine/consensus/ingestion/engine.go +++ b/engine/consensus/ingestion/engine.go @@ -86,7 +86,7 @@ func New( componentManagerBuilder := component.NewComponentManagerBuilder() - for range defaultIngestionEngineWorkers { + for i := 0; i < defaultIngestionEngineWorkers; i++ { componentManagerBuilder.AddWorker(func(ctx irrecoverable.SignalerContext, ready component.ReadyFunc) { ready() err := e.loop(ctx) @@ -108,7 +108,7 @@ func New( } // SubmitLocal submits an event originating on the local node. -func (e *Engine) SubmitLocal(event any) { +func (e *Engine) SubmitLocal(event interface{}) { err := e.ProcessLocal(event) if err != nil { e.log.Fatal().Err(err).Msg("internal error processing event") @@ -118,7 +118,7 @@ func (e *Engine) SubmitLocal(event any) { // Submit submits the given event from the node with the given origin ID // for processing in a non-blocking manner. It returns instantly and logs // a potential processing error internally when done. -func (e *Engine) Submit(channel channels.Channel, originID flow.Identifier, event any) { +func (e *Engine) Submit(channel channels.Channel, originID flow.Identifier, event interface{}) { err := e.Process(channel, originID, event) if err != nil { e.log.Fatal().Err(err).Msg("internal error processing event") @@ -126,13 +126,13 @@ func (e *Engine) Submit(channel channels.Channel, originID flow.Identifier, even } // ProcessLocal processes an event originating on the local node. -func (e *Engine) ProcessLocal(event any) error { +func (e *Engine) ProcessLocal(event interface{}) error { return e.messageHandler.Process(e.me.NodeID(), event) } // Process processes the given event from the node with the given origin ID in // a blocking manner. It returns error only in unexpected scenario. -func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event any) error { +func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { err := e.messageHandler.Process(originID, event) if err != nil { if engine.IsIncompatibleInputTypeError(err) { diff --git a/engine/consensus/ingestion/engine_test.go b/engine/consensus/ingestion/engine_test.go index a30df703ac8..29d59b3adf7 100644 --- a/engine/consensus/ingestion/engine_test.go +++ b/engine/consensus/ingestion/engine_test.go @@ -79,7 +79,8 @@ func (s *IngestionSuite) TestSubmittingMultipleEntries() { processed := atomic.NewUint64(0) var wg sync.WaitGroup - wg.Go(func() { + wg.Add(1) + go func() { for i := 0; i < int(count); i++ { guarantee := s.validGuarantee() s.pool.On("Has", guarantee.ID()).Return(false) @@ -90,7 +91,8 @@ func (s *IngestionSuite) TestSubmittingMultipleEntries() { // execute the vote submission _ = s.ingest.Process(channels.ProvideCollections, originID, guarantee) } - }) + wg.Done() + }() wg.Wait() diff --git a/engine/consensus/matching/core_test.go b/engine/consensus/matching/core_test.go index 7de4c4e405d..6ef122693e8 100644 --- a/engine/consensus/matching/core_test.go +++ b/engine/consensus/matching/core_test.go @@ -235,7 +235,7 @@ func (ms *MatchingSuite) TestRequestPendingReceipts() { n := 100 orderedBlocks := make([]flow.Block, 0, n) parentBlock := ms.UnfinalizedBlock - for range n { + for i := 0; i < n; i++ { block := unittest.BlockWithParentFixture(parentBlock.ToHeader()) ms.Extend(block) orderedBlocks = append(orderedBlocks, *block) diff --git a/engine/consensus/matching/engine.go b/engine/consensus/matching/engine.go index 00dbb5778c6..ae8cc30429b 100644 --- a/engine/consensus/matching/engine.go +++ b/engine/consensus/matching/engine.go @@ -108,7 +108,7 @@ func NewEngine( // Process receives events from the network and checks their type, // before enqueuing them to be processed by a worker in a non-blocking manner. // No errors expected during normal operation (errors are logged instead). -func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event any) error { +func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { receipt, ok := event.(*flow.ExecutionReceipt) if !ok { e.log.Warn().Msgf("%v delivered unsupported message %T through %v", originID, event, channel) diff --git a/engine/consensus/matching/engine_test.go b/engine/consensus/matching/engine_test.go index 24bf0159cb8..e0b82d00f59 100644 --- a/engine/consensus/matching/engine_test.go +++ b/engine/consensus/matching/engine_test.go @@ -134,12 +134,14 @@ func (s *MatchingEngineSuite) TestMultipleProcessingItems() { } var wg sync.WaitGroup - wg.Go(func() { + wg.Add(1) + go func() { + defer wg.Done() for _, receipt := range receipts { err := s.engine.Process(channels.ReceiveReceipts, originID, receipt) s.Require().NoError(err, "should add receipt and result to mempool if valid") } - }) + }() wg.Wait() diff --git a/engine/consensus/message_hub/message_hub.go b/engine/consensus/message_hub/message_hub.go index 926c8e84e72..a84ab22900c 100644 --- a/engine/consensus/message_hub/message_hub.go +++ b/engine/consensus/message_hub/message_hub.go @@ -153,7 +153,7 @@ func NewMessageHub(log zerolog.Logger, // This implementation tolerates if the networking layer sometimes blocks on send requests. // We use by default 5 go-routines here. This is fine, because outbound messages are temporally sparse // under normal operations. Hence, the go-routines should mostly be asleep waiting for work. - for range defaultMessageHubRequestsWorkers { + for i := 0; i < defaultMessageHubRequestsWorkers; i++ { componentBuilder.AddWorker(func(ctx irrecoverable.SignalerContext, ready component.ReadyFunc) { ready() hub.queuedMessagesProcessingLoop(ctx) @@ -470,7 +470,7 @@ func (h *MessageHub) OnOwnProposal(proposal *flow.ProposalHeader, targetPublicat // // Some of the current error returns signal Byzantine behavior, such as forged or malformed // messages. These cases must be logged and routed to a dedicated violation reporting consumer. -func (h *MessageHub) Process(channel channels.Channel, originID flow.Identifier, message any) error { +func (h *MessageHub) Process(channel channels.Channel, originID flow.Identifier, message interface{}) error { switch msg := message.(type) { case *flow.Proposal: h.compliance.OnBlockProposal(flow.Slashable[*flow.Proposal]{ diff --git a/engine/consensus/sealing/core.go b/engine/consensus/sealing/core.go index 9a15c6bd7af..8db0bc27f5a 100644 --- a/engine/consensus/sealing/core.go +++ b/engine/consensus/sealing/core.go @@ -453,13 +453,16 @@ func (c *Core) checkEmergencySealing(observer consensus.SealingObservation, last // we will check all the unsealed finalized height except the last approvals.DefaultEmergencySealingThresholdForFinalization // number of finalized heights - heightCountForCheckingEmergencySealing := min( - // If there are too many unsealed and finalized blocks, we don't have to check emergency sealing for all of them, - // instead, only check for at most 100 blocks. This limits computation cost. - // Note: the block builder also limits the max number of seals that can be included in a new block to `maxSealCount`. - // While `maxSealCount` doesn't have to be the same value as the limit below, there is little benefit of our limit - // exceeding `maxSealCount`. - unsealedFinalizedCount-approvals.DefaultEmergencySealingThresholdForFinalization, 100) + heightCountForCheckingEmergencySealing := unsealedFinalizedCount - approvals.DefaultEmergencySealingThresholdForFinalization + + // If there are too many unsealed and finalized blocks, we don't have to check emergency sealing for all of them, + // instead, only check for at most 100 blocks. This limits computation cost. + // Note: the block builder also limits the max number of seals that can be included in a new block to `maxSealCount`. + // While `maxSealCount` doesn't have to be the same value as the limit below, there is little benefit of our limit + // exceeding `maxSealCount`. + if heightCountForCheckingEmergencySealing > 100 { + heightCountForCheckingEmergencySealing = 100 + } // if block is emergency sealable depends on it's incorporated block height // collectors tree stores collector by executed block height // we need to select multiple levels to find eligible collectors for emergency sealing diff --git a/engine/consensus/sealing/core_test.go b/engine/consensus/sealing/core_test.go index 419536774df..cee3e95cfc6 100644 --- a/engine/consensus/sealing/core_test.go +++ b/engine/consensus/sealing/core_test.go @@ -192,7 +192,7 @@ func (s *ApprovalProcessingCoreTestSuite) TestOnBlockFinalized_RejectOldFinalize func (s *ApprovalProcessingCoreTestSuite) TestProcessFinalizedBlock_CollectorsCleanup() { blockID := s.Block.ID() numResults := uint(10) - for range numResults { + for i := uint(0); i < numResults; i++ { // all results incorporated in different blocks incorporatedBlock := unittest.BlockHeaderWithParentFixture(s.IncorporatedBlock) s.Blocks[incorporatedBlock.ID()] = incorporatedBlock @@ -351,7 +351,7 @@ func (s *ApprovalProcessingCoreTestSuite) TestOnBlockFinalized_EmergencySealing( lastFinalizedBlock := s.IncorporatedBlock s.MarkFinalized(lastFinalizedBlock) - for range approvals.DefaultEmergencySealingThresholdForFinalization { + for i := 0; i < approvals.DefaultEmergencySealingThresholdForFinalization; i++ { finalizedBlock := unittest.BlockHeaderWithParentFixture(lastFinalizedBlock) s.Blocks[finalizedBlock.ID()] = finalizedBlock s.MarkFinalized(finalizedBlock) @@ -534,7 +534,7 @@ func (s *ApprovalProcessingCoreTestSuite) TestRequestPendingApprovals() { // create blocks unsealedFinalizedBlocks := make([]flow.Block, 0, n) parentBlock := s.ParentBlock - for range n { + for i := 0; i < n; i++ { block := unittest.BlockWithParentFixture(parentBlock) s.Blocks[block.ID()] = block.ToHeader() s.IdentitiesCache[block.ID()] = s.AuthorizedVerifiers @@ -629,7 +629,7 @@ func (s *ApprovalProcessingCoreTestSuite) TestRequestPendingApprovals() { // process two more blocks, this will trigger requesting approvals for lastSealed + 1 height // but they will be in blackout period - for range 2 { + for i := 0; i < 2; i++ { finalized := unsealedFinalizedBlocks[lastProcessedIndex].ToHeader() s.MarkFinalized(finalized) err := s.core.ProcessFinalizedBlock(finalized.ID()) @@ -717,7 +717,7 @@ func (s *ApprovalProcessingCoreTestSuite) TestRepopulateAssignmentCollectorTree( assigner.On("Assign", s.IncorporatedResult.Result, mock.Anything).Return(s.ChunksAssignment, nil) // two forks - for i := range 2 { + for i := 0; i < 2; i++ { fork := unittest.ChainFixtureFrom(i+3, s.IncorporatedBlock) prevResult := s.IncorporatedResult.Result // create execution results for all blocks except last one, since it won't be valid by definition diff --git a/engine/consensus/sealing/engine.go b/engine/consensus/sealing/engine.go index be2fe8fd18b..367e7c3cdd5 100644 --- a/engine/consensus/sealing/engine.go +++ b/engine/consensus/sealing/engine.go @@ -27,7 +27,7 @@ import ( type Event struct { OriginID flow.Identifier - Msg any + Msg interface{} } // defaultApprovalQueueCapacity maximum capacity of approvals queue @@ -171,7 +171,7 @@ func NewEngine(log zerolog.Logger, // reason it is factored out from NewEngine is so that it can be used in tests. func (e *Engine) buildComponentManager() *component.ComponentManager { builder := component.NewComponentManagerBuilder() - for range defaultSealingEngineWorkers { + for i := 0; i < defaultSealingEngineWorkers; i++ { builder.AddWorker(e.loop) } builder.AddWorker(e.finalizationProcessingLoop) @@ -287,7 +287,7 @@ func (e *Engine) setupMessageHandler(getSealingConfigs module.SealingConfigsGett } // Process sends event into channel with pending events. Generally speaking shouldn't lock for too long. -func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event any) error { +func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { err := e.messageHandler.Process(originID, event) if err != nil { if engine.IsIncompatibleInputTypeError(err) { diff --git a/engine/consensus/sealing/engine_test.go b/engine/consensus/sealing/engine_test.go index 33abd35a650..4ddeb82cc35 100644 --- a/engine/consensus/sealing/engine_test.go +++ b/engine/consensus/sealing/engine_test.go @@ -173,7 +173,7 @@ func (s *SealingEngineSuite) TestMultipleProcessingItems() { responseApprovals := make([]*flow.ApprovalResponse, 0) approverID := unittest.IdentifierFixture() for _, receipt := range receipts { - for range numApprovalsPerReceipt { + for j := 0; j < numApprovalsPerReceipt; j++ { approval := unittest.ResultApprovalFixture( unittest.WithExecutionResultID(receipt.ExecutionResult.ID()), unittest.WithApproverID(approverID), @@ -192,19 +192,23 @@ func (s *SealingEngineSuite) TestMultipleProcessingItems() { } var wg sync.WaitGroup - wg.Go(func() { + wg.Add(1) + go func() { + defer wg.Done() for _, approval := range approvals { err := s.engine.Process(channels.ReceiveApprovals, approverID, approval) s.Require().NoError(err, "should process approval (trusted)") } - }) - wg.Go(func() { + }() + wg.Add(1) + go func() { + defer wg.Done() for _, resp := range responseApprovals { err := s.engine.Process(channels.ReceiveApprovals, approverID, resp) s.Require().NoError(err, "should process approval (converted from wire)") } - }) + }() wg.Wait() diff --git a/engine/enqueue_test.go b/engine/enqueue_test.go index ce36fbd5cd7..cd743c32a07 100644 --- a/engine/enqueue_test.go +++ b/engine/enqueue_test.go @@ -26,7 +26,7 @@ type TestEngine struct { queueB *engine.FifoMessageStore mu sync.RWMutex - messages []any + messages []interface{} } type messageA struct { @@ -109,7 +109,7 @@ func NewEngine(log zerolog.Logger, capacity int) (*TestEngine, error) { return eng, nil } -func (e *TestEngine) Process(originID flow.Identifier, event any) error { +func (e *TestEngine) Process(originID flow.Identifier, event interface{}) error { return e.messageHandler.Process(originID, event) } @@ -303,7 +303,7 @@ func TestProcessMessageMultiAll(t *testing.T) { WithEngine(t, func(eng *TestEngine) { count := 100 - for i := range count { + for i := 0; i < count; i++ { require.NoError(t, eng.Process(unittest.IdentifierFixture(), &messageA{n: i})) } @@ -320,7 +320,7 @@ func TestProcessMessageMultiInterval(t *testing.T) { WithEngine(t, func(eng *TestEngine) { count := 100 - for i := range count { + for i := 0; i < count; i++ { time.Sleep(1 * time.Millisecond) require.NoError(t, eng.Process(unittest.IdentifierFixture(), &messageB{n: i})) } @@ -338,7 +338,7 @@ func TestProcessMessageMultiConcurrent(t *testing.T) { WithEngine(t, func(eng *TestEngine) { count := 100 var sent sync.WaitGroup - for i := range count { + for i := 0; i < count; i++ { sent.Add(1) go func(i int) { require.NoError(t, eng.Process(unittest.IdentifierFixture(), &messageA{n: i})) diff --git a/engine/execution/block_result.go b/engine/execution/block_result.go index a491b92793b..232875f7e4b 100644 --- a/engine/execution/block_result.go +++ b/engine/execution/block_result.go @@ -2,7 +2,6 @@ package execution import ( "fmt" - "maps" "math" "github.com/onflow/flow-go/fvm/storage/snapshot" @@ -115,7 +114,9 @@ func (er *BlockExecutionResult) AllConvertedServiceEvents() flow.ServiceEventLis func (er *BlockExecutionResult) AllUpdatedRegisters() []flow.RegisterEntry { updates := make(map[flow.RegisterID]flow.RegisterValue) for _, ce := range er.collectionExecutionResults { - maps.Copy(updates, ce.executionSnapshot.WriteSet) + for regID, regVal := range ce.executionSnapshot.WriteSet { + updates[regID] = regVal + } } res := make([]flow.RegisterEntry, 0, len(updates)) for regID, regVal := range updates { diff --git a/engine/execution/block_result_test.go b/engine/execution/block_result_test.go index 7a69925630b..3890f476e87 100644 --- a/engine/execution/block_result_test.go +++ b/engine/execution/block_result_test.go @@ -32,7 +32,7 @@ func TestBlockExecutionResult_ServiceEventCountForChunk(t *testing.T) { nChunks := rand.Intn(10) + 1 // always contains at least system chunk blockResult := makeBlockExecutionResultFixture(make([]int, nChunks)) // all chunks should have 0 service event count - for chunkIndex := range nChunks { + for chunkIndex := 0; chunkIndex < nChunks; chunkIndex++ { count := blockResult.ServiceEventCountForChunk(chunkIndex) assert.Equal(t, uint16(0), count) } @@ -75,7 +75,7 @@ func TestBlockExecutionResult_ServiceEventCountForChunk(t *testing.T) { blockResult := makeBlockExecutionResultFixture(serviceEventAllocation) // all chunks should have service event count of 1 - for chunkIndex := range nChunks { + for chunkIndex := 0; chunkIndex < nChunks; chunkIndex++ { count := blockResult.ServiceEventCountForChunk(chunkIndex) assert.Equal(t, uint16(1), count) } diff --git a/engine/execution/computation/committer/committer.go b/engine/execution/computation/committer/committer.go index 2eea9297f34..86d72db1ead 100644 --- a/engine/execution/computation/committer/committer.go +++ b/engine/execution/computation/committer/committer.go @@ -42,9 +42,11 @@ func (committer *LedgerViewCommitter) CommitView( ) { var err1, err2 error var wg sync.WaitGroup - wg.Go(func() { + wg.Add(1) + go func() { proof, err2 = committer.collectProofs(snapshot, baseStorageSnapshot) - }) + wg.Done() + }() newCommit, trieUpdate, newStorageSnapshot, err1 = execState.CommitDelta( committer.ledger, diff --git a/engine/execution/computation/computer/computer_test.go b/engine/execution/computation/computer/computer_test.go index b2f165455f3..87e2441c496 100644 --- a/engine/execution/computation/computer/computer_test.go +++ b/engine/execution/computation/computer/computer_test.go @@ -539,7 +539,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { assert.Equal(t, result.BlockExecutionResult.Size(), collectionCount+1) // system chunk // all events should have been collected - for i := range collectionCount { + for i := 0; i < collectionCount; i++ { events := result.CollectionExecutionResultAt(i).Events() assert.Len(t, events, eventsPerCollection) } @@ -551,8 +551,8 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { // events should have been indexed by transaction and event k := 0 - for expectedTxIndex := range totalTransactionCount { - for expectedEventIndex := range eventsPerTransaction { + for expectedTxIndex := 0; expectedTxIndex < totalTransactionCount; expectedTxIndex++ { + for expectedEventIndex := 0; expectedEventIndex < eventsPerTransaction; expectedEventIndex++ { e := events[k] assert.EqualValues(t, expectedEventIndex, int(e.EventIndex)) assert.EqualValues(t, expectedTxIndex, e.TransactionIndex) @@ -1040,7 +1040,7 @@ func assertEventHashesMatch( require.Equal(t, execResSize, expectedNoOfChunks) require.Equal(t, execResSize, attestResSize) - for i := range expectedNoOfChunks { + for i := 0; i < expectedNoOfChunks; i++ { events := result.CollectionExecutionResultAt(i).Events() calculatedHash, err := flow.EventsMerkleRootHash(events) require.NoError(t, err) @@ -1833,7 +1833,7 @@ func generateBlockWithVisitor( guarantees := make([]*flow.CollectionGuarantee, collectionCount) completeCollections := make(map[flow.Identifier]*entity.CompleteCollection) - for i := range collectionCount { + for i := 0; i < collectionCount; i++ { collection := generateCollection(transactionCount, addressGenerator, visitor) collections[i] = collection guarantees[i] = collection.Guarantee @@ -1863,7 +1863,7 @@ func generateCollection( ) *entity.CompleteCollection { transactions := make([]*flow.TransactionBody, transactionCount) - for i := range transactionCount { + for i := 0; i < transactionCount; i++ { nextAddress, err := addressGenerator.NextAddress() if err != nil { panic(fmt.Errorf("cannot generate next address in test: %w", err)) @@ -2016,7 +2016,7 @@ func (testVM) Inspect( func generateEvents(eventCount int, txIndex uint32) []flow.Event { events := make([]flow.Event, eventCount) - for i := range eventCount { + for i := 0; i < eventCount; i++ { // creating some dummy event event := flow.Event{ Type: "whatever", @@ -2149,22 +2149,22 @@ func NewTestLogger() *TestLogger { type LogEntry struct { Level string Message string - Fields map[string]any + Fields map[string]interface{} } func (tl *TestLogger) Logs() []LogEntry { var entries []LogEntry - lines := strings.SplitSeq(tl.buffer.String(), "\n") - for line := range lines { + lines := strings.Split(tl.buffer.String(), "\n") + for _, line := range lines { if line == "" { continue } - var rawEntry map[string]any + var rawEntry map[string]interface{} if err := json.Unmarshal([]byte(line), &rawEntry); err != nil { continue } entry := LogEntry{ - Fields: make(map[string]any), + Fields: make(map[string]interface{}), } for k, v := range rawEntry { switch k { @@ -2185,7 +2185,7 @@ func (tl *TestLogger) HasLog(message string) bool { return strings.Contains(tl.buffer.String(), message) } -func (tl *TestLogger) HasLogWithField(message string, fieldName string, fieldValue any) bool { +func (tl *TestLogger) HasLogWithField(message string, fieldName string, fieldValue interface{}) bool { for _, entry := range tl.Logs() { if strings.Contains(entry.Message, message) { if val, ok := entry.Fields[fieldName]; ok { diff --git a/engine/execution/computation/execution_verification_test.go b/engine/execution/computation/execution_verification_test.go index 7e8a66fa41d..a95f4e2afe3 100644 --- a/engine/execution/computation/execution_verification_test.go +++ b/engine/execution/computation/execution_verification_test.go @@ -78,14 +78,14 @@ func Test_ExecutionMatchesVerification(t *testing.T) { }`), "Foo") emitTxBuilder := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` import Foo from 0x%s transaction { prepare() {} execute { Foo.emitEvent() } - }`, chain.ServiceAddress())) + }`, chain.ServiceAddress()))) err := testutil.SignTransactionAsServiceAccount(deployTxBuilder, 0, chain) require.NoError(t, err) @@ -125,14 +125,14 @@ func Test_ExecutionMatchesVerification(t *testing.T) { }`), "Foo") emitTx1Builder := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` import Foo from 0x%s transaction { prepare() {} execute { Foo.emitEvent() } - }`, chain.ServiceAddress())) + }`, chain.ServiceAddress()))) // copy txs emitTx2Builder := *emitTx1Builder @@ -174,7 +174,7 @@ func Test_ExecutionMatchesVerification(t *testing.T) { colResult := cr.CollectionExecutionResultAt(colIndex) txResults := colResult.TransactionResults() require.Len(t, txResults, expResCount) - for i := range expResCount { + for i := 0; i < expResCount; i++ { require.Empty(t, txResults[i].ErrorMessage) } } @@ -602,7 +602,7 @@ func TestTransactionFeeDeduction(t *testing.T) { transferTokensTx := func(chain flow.Chain) *flow.TransactionBodyBuilder { return flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` // This transaction is a template for a transaction that // could be used by anyone to send tokens to another account // that has been set up to receive tokens. @@ -640,7 +640,7 @@ func TestTransactionFeeDeduction(t *testing.T) { // Deposit the withdrawn tokens in the recipient's receiver receiverRef.deposit(from: <-self.sentVault) } - }`, sc.FungibleToken.Address, sc.FlowToken.Address), + }`, sc.FungibleToken.Address, sc.FlowToken.Address)), ) } diff --git a/engine/execution/computation/manager_benchmark_test.go b/engine/execution/computation/manager_benchmark_test.go index c031e5b8aa8..39dab40c887 100644 --- a/engine/execution/computation/manager_benchmark_test.go +++ b/engine/execution/computation/manager_benchmark_test.go @@ -66,7 +66,7 @@ func createAccounts( accs := &testAccounts{ accounts: make([]testAccount, num), } - for i := range num { + for i := 0; i < num; i++ { accs.accounts[i] = testAccount{ address: addresses[i], privateKey: privateKeys[i], @@ -264,9 +264,9 @@ func createBlock(b *testing.B, parentBlock *flow.Block, accs *testAccounts, colN collections := make([]*flow.Collection, colNum) guarantees := make([]*flow.CollectionGuarantee, colNum) - for c := range colNum { + for c := 0; c < colNum; c++ { transactions := make([]*flow.TransactionBody, txNum) - for t := range txNum { + for t := 0; t < txNum; t++ { transactions[t] = createTokenTransferTransaction(b, accs) } diff --git a/engine/execution/computation/manager_test.go b/engine/execution/computation/manager_test.go index f6538824a7f..afed9fa844a 100644 --- a/engine/execution/computation/manager_test.go +++ b/engine/execution/computation/manager_test.go @@ -251,14 +251,14 @@ func TestExecuteScript(t *testing.T) { sc := systemcontracts.SystemContractsForChain(execCtx.Chain.ChainID()) - script := fmt.Appendf(nil, + script := []byte(fmt.Sprintf( ` import FungibleToken from %s access(all) fun main() {} `, sc.FungibleToken.Address.HexWithPrefix(), - ) + )) bservice := requesterunit.MockBlobService(blockstore.NewBlockstore(dssync.MutexWrap(datastore.NewMapDatastore()))) trackerStorage := mocktracker.NewMockStorage() @@ -319,14 +319,14 @@ func TestExecuteScript_BalanceScriptFailsIfViewIsEmpty(t *testing.T) { sc := systemcontracts.SystemContractsForChain(execCtx.Chain.ChainID()) - script := fmt.Appendf(nil, + script := []byte(fmt.Sprintf( ` access(all) fun main(): UFix64 { return getAccount(%s).balance } `, sc.FungibleToken.Address.HexWithPrefix(), - ) + )) bservice := requesterunit.MockBlobService(blockstore.NewBlockstore(dssync.MutexWrap(datastore.NewMapDatastore()))) trackerStorage := mocktracker.NewMockStorage() @@ -762,7 +762,8 @@ func TestExecuteScriptCancelled(t *testing.T) { var value []byte var wg sync.WaitGroup reqCtx, cancel := context.WithCancel(context.Background()) - wg.Go(func() { + wg.Add(1) + go func() { header := unittest.BlockHeaderFixture() value, _, err = manager.ExecuteScript( reqCtx, @@ -770,7 +771,8 @@ func TestExecuteScriptCancelled(t *testing.T) { nil, header, nil) - }) + wg.Done() + }() cancel() wg.Wait() require.Nil(t, value) diff --git a/engine/execution/computation/metrics/collector_test.go b/engine/execution/computation/metrics/collector_test.go index 8eb0b4ca7e3..14882c5f1c0 100644 --- a/engine/execution/computation/metrics/collector_test.go +++ b/engine/execution/computation/metrics/collector_test.go @@ -40,11 +40,11 @@ func Test_CollectorCollection(t *testing.T) { wg := sync.WaitGroup{} wg.Add(16 * 16 * 16) - for height := range 16 { + for height := 0; height < 16; height++ { // for each height we add multiple blocks. Only one block will be popped per height - for block := range 16 { + for block := 0; block < 16; block++ { // for each block we add multiple transactions - for transaction := range 16 { + for transaction := 0; transaction < 16; transaction++ { go func(h, b, t int) { defer wg.Done() @@ -74,7 +74,7 @@ func Test_CollectorCollection(t *testing.T) { data := collector.Pop(startHeight, flow.ZeroID) require.Nil(t, data) - for height := range 16 { + for height := 0; height < 16; height++ { block := flow.Identifier{} block[0] = byte(height) // always pop the first block each height diff --git a/engine/execution/ingestion/core.go b/engine/execution/ingestion/core.go index 32f9b64af3c..fa42ccd3e54 100644 --- a/engine/execution/ingestion/core.go +++ b/engine/execution/ingestion/core.go @@ -108,7 +108,7 @@ func NewCore( builder := component.NewComponentManagerBuilder().AddWorker(e.launchWorkerToHandleBlocks) - for range MaxConcurrentBlockExecutor { + for w := 0; w < MaxConcurrentBlockExecutor; w++ { builder.AddWorker(e.launchWorkerToExecuteBlocks) } diff --git a/engine/execution/ingestion/throttle.go b/engine/execution/ingestion/throttle.go index da07a3afed0..bbf02dd46fb 100644 --- a/engine/execution/ingestion/throttle.go +++ b/engine/execution/ingestion/throttle.go @@ -127,7 +127,10 @@ func (c *BlockThrottle) Init(processables chan<- BlockIDHeight, threshold int) e c.processables = processables - lastFinalizedToLoad := min(c.loaded+uint64(threshold), c.finalized) + lastFinalizedToLoad := c.loaded + uint64(threshold) + if lastFinalizedToLoad > c.finalized { + lastFinalizedToLoad = c.finalized + } loadedAll := lastFinalizedToLoad == c.finalized diff --git a/engine/execution/ingestion/uploader/manager.go b/engine/execution/ingestion/uploader/manager.go index cb20933f384..747fcd18a17 100644 --- a/engine/execution/ingestion/uploader/manager.go +++ b/engine/execution/ingestion/uploader/manager.go @@ -68,6 +68,7 @@ func (m *Manager) Upload( var group errgroup.Group for _, uploader := range m.uploaders { + uploader := uploader group.Go(func() error { span, _ := m.tracer.StartSpanFromContext(ctx, trace.EXEUploadCollections) diff --git a/engine/execution/ingestion/uploader/model.go b/engine/execution/ingestion/uploader/model.go index e34bdd40715..fc39dd08393 100644 --- a/engine/execution/ingestion/uploader/model.go +++ b/engine/execution/ingestion/uploader/model.go @@ -25,13 +25,13 @@ func ComputationResultToBlockData(computationResult *execution.ComputationResult AllResults := computationResult.AllTransactionResults() txResults := make([]*flow.TransactionResult, len(AllResults)) - for i := range AllResults { + for i := 0; i < len(AllResults); i++ { txResults[i] = &AllResults[i] } eventsList := computationResult.AllEvents() events := make([]*flow.Event, len(eventsList)) - for i := range eventsList { + for i := 0; i < len(eventsList); i++ { events[i] = &eventsList[i] } diff --git a/engine/execution/ingestion/uploader/uploader.go b/engine/execution/ingestion/uploader/uploader.go index 2d1490094ac..2abb6a9078b 100644 --- a/engine/execution/ingestion/uploader/uploader.go +++ b/engine/execution/ingestion/uploader/uploader.go @@ -37,7 +37,7 @@ func NewAsyncUploader(uploader Uploader, queue: make(chan *execution.ComputationResult, 20000), } builder := component.NewComponentManagerBuilder() - for range 10 { + for i := 0; i < 10; i++ { builder.AddWorker(a.UploadWorker) } a.cm = builder.Build() diff --git a/engine/execution/provider/engine.go b/engine/execution/provider/engine.go index 7cc1859b70e..1bdab991ed1 100644 --- a/engine/execution/provider/engine.go +++ b/engine/execution/provider/engine.go @@ -40,7 +40,7 @@ type NoopEngine struct { module.NoopReadyDoneAware } -func (*NoopEngine) Process(channel channels.Channel, originID flow.Identifier, message any) error { +func (*NoopEngine) Process(channel channels.Channel, originID flow.Identifier, message interface{}) error { return nil } @@ -163,7 +163,7 @@ func New( cm := component.NewComponentManagerBuilder() cm.AddWorker(engine.processQueuedChunkDataPackRequestsShovelerWorker) - for range chdpRequestWorkers { + for i := uint(0); i < chdpRequestWorkers; i++ { cm.AddWorker(engine.processChunkDataPackRequestWorker) } @@ -251,7 +251,7 @@ func (e *Engine) processChunkDataPackRequestWorker(ctx irrecoverable.SignalerCon } } -func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event any) error { +func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { select { case <-e.cm.ShutdownSignal(): e.log.Warn().Msgf("received message from %x after shut down", originID) diff --git a/engine/execution/rpc/engine_test.go b/engine/execution/rpc/engine_test.go index b63e71651f0..562d0e5ee34 100644 --- a/engine/execution/rpc/engine_test.go +++ b/engine/execution/rpc/engine_test.go @@ -726,7 +726,7 @@ func (suite *Suite) TestGetTransactionResultsByBlockID() { convertedEventsForTx1 := make([]*entities.Event, len(eventsForTx1)) convertedEventsForTx2 := make([]*entities.Event, len(eventsForTx2)) - for j := range eventsForTx1 { + for j := 0; j < len(eventsForTx1); j++ { e := unittest.EventFixture( unittest.Event.WithEventType(flow.EventAccountCreated), unittest.Event.WithTransactionIndex(0), @@ -737,7 +737,7 @@ func (suite *Suite) TestGetTransactionResultsByBlockID() { eventsForBlock[j] = e convertedEventsForTx1[j] = convert.EventToMessage(e) } - for j := range eventsForTx2 { + for j := 0; j < len(eventsForTx2); j++ { e := unittest.EventFixture( unittest.Event.WithEventType(flow.EventAccountCreated), unittest.Event.WithTransactionIndex(1), diff --git a/engine/execution/state/unittest/fixtures.go b/engine/execution/state/unittest/fixtures.go index 7feaf3565d6..f76d74dac9a 100644 --- a/engine/execution/state/unittest/fixtures.go +++ b/engine/execution/state/unittest/fixtures.go @@ -46,7 +46,7 @@ func ComputationResultForBlockFixture( numberOfChunks := len(collections) + 1 ceds := make([]*execution_data.ChunkExecutionData, numberOfChunks) startState := *completeBlock.StartState - for i := range numberOfChunks { + for i := 0; i < numberOfChunks; i++ { ceds[i] = unittest.ChunkExecutionDataFixture(t, 1024) endState := unittest.StateCommitmentFixture() computationResult.CollectionExecutionResultAt(i).UpdateExecutionSnapshot(StateInteractionsFixture()) diff --git a/engine/execution/storehouse/background_indexer_factory_test.go b/engine/execution/storehouse/background_indexer_factory_test.go index 445bb24e9ef..506ae6513af 100644 --- a/engine/execution/storehouse/background_indexer_factory_test.go +++ b/engine/execution/storehouse/background_indexer_factory_test.go @@ -338,7 +338,7 @@ func TestLoadBackgroundIndexerEngine_Indexing(t *testing.T) { blocks := make([]*flow.Block, numBlocks) parentHeader := sealedRoot - for i := range numBlocks { + for i := 0; i < numBlocks; i++ { height := startHeight + uint64(i) + 1 block := unittest.BlockWithParentFixture(parentHeader) blocks[i] = block @@ -397,7 +397,7 @@ func TestLoadBackgroundIndexerEngine_Indexing(t *testing.T) { resultsReader := storagemock.NewExecutionResults(t) // Create execution data and results for all blocks - for i := range numBlocks { + for i := 0; i < numBlocks; i++ { block := blocks[i] // Create valid register entries and convert to trie update @@ -407,7 +407,7 @@ func TestLoadBackgroundIndexerEngine_Indexing(t *testing.T) { Owner: "owner", Key: fmt.Sprintf("key%d", i), }, - Value: fmt.Appendf(nil, "value%d", i), + Value: []byte(fmt.Sprintf("value%d", i)), }, } @@ -496,7 +496,7 @@ func TestLoadBackgroundIndexerEngine_Indexing(t *testing.T) { // The finalized reader subscribes to protocolEvents during bootstrapping, so it will receive these events // We need to finalize them sequentially so the finalized reader's lastHeight is updated correctly // The FinalizedReader's BlockFinalized method is called synchronously, so we don't need long waits - for i := range numBlocks { + for i := 0; i < numBlocks; i++ { block := blocks[i] protocolEvents.BlockFinalized(block.ToHeader()) // Small wait to ensure the event is processed @@ -514,7 +514,7 @@ func TestLoadBackgroundIndexerEngine_Indexing(t *testing.T) { finalSnapshot.On("Head").Return(finalizedBlock.ToHeader(), nil) // Notify the follower distributor to trigger the background indexer - for i := range numBlocks { + for i := 0; i < numBlocks; i++ { block := blocks[i] hotstuffBlock := &model.Block{ BlockID: block.ID(), @@ -530,7 +530,7 @@ func TestLoadBackgroundIndexerEngine_Indexing(t *testing.T) { // Notify that blocks were executed (this triggers indexing) // The background indexer will process all finalized and executed blocks sequentially // We may need to trigger multiple times as blocks get processed - for range 10 { + for attempt := 0; attempt < 10; attempt++ { blockExecutedNotifier.OnExecuted() time.Sleep(200 * time.Millisecond) diff --git a/engine/execution/storehouse/checkpoint_validator.go b/engine/execution/storehouse/checkpoint_validator.go index a06a76945e7..99534fadacc 100644 --- a/engine/execution/storehouse/checkpoint_validator.go +++ b/engine/execution/storehouse/checkpoint_validator.go @@ -79,7 +79,7 @@ func ValidateWithCheckpoint( start := time.Now() log.Info().Msgf("validation registers from checkpoint with %v worker", workerCount) - for range workerCount { + for i := 0; i < workerCount; i++ { g.Go(func() error { return validatingRegisterInStore(gCtx, log, store, leafNodeChan, blockHeight, &mismatchErrorCount) }) diff --git a/engine/execution/storehouse/in_memory_register_store_test.go b/engine/execution/storehouse/in_memory_register_store_test.go index 6c8bd2a224f..f7f417375da 100644 --- a/engine/execution/storehouse/in_memory_register_store_test.go +++ b/engine/execution/storehouse/in_memory_register_store_test.go @@ -632,7 +632,9 @@ func TestInMemoryRegisterStore(t *testing.T) { var wg sync.WaitGroup savedHeights := make(chan uint64, 100) - wg.Go(func() { + wg.Add(1) + go func() { + defer wg.Done() lastPrunedHeight := pruned for savedHeight := range savedHeights { @@ -644,7 +646,7 @@ func TestInMemoryRegisterStore(t *testing.T) { require.NoError(t, err) lastPrunedHeight = rdHeight } - }) + }() // save 100 blocks for i := 1; i < count; i++ { diff --git a/engine/execution/storehouse/register_store_test.go b/engine/execution/storehouse/register_store_test.go index 3f2e877f779..c746a05dcba 100644 --- a/engine/execution/storehouse/register_store_test.go +++ b/engine/execution/storehouse/register_store_test.go @@ -557,14 +557,16 @@ func TestRegisterStoreConcurrentFinalizeAndExecute(t *testing.T) { var wg sync.WaitGroup savedHeights := make(chan uint64, len(headerByHeight)) // enough buffer so that producer won't be blocked - wg.Go(func() { + wg.Add(1) + go func() { + defer wg.Done() for savedHeight := range savedHeights { err := finalized.MockFinal(savedHeight) require.NoError(t, err) require.NoError(t, rs.OnBlockFinalized(), fmt.Sprintf("saved height %v", savedHeight)) } - }) + }() for height := rootHeight + 1; height <= endHeight; height++ { if height >= 50 { diff --git a/engine/execution/testutil/fixtures.go b/engine/execution/testutil/fixtures.go index 8e905994317..9fd5a1e0e1c 100644 --- a/engine/execution/testutil/fixtures.go +++ b/engine/execution/testutil/fixtures.go @@ -36,11 +36,11 @@ import ( func CreateContractDeploymentTransaction(contractName string, contract string, authorizer flow.Address, chain flow.Chain) *flow.TransactionBodyBuilder { encoded := hex.EncodeToString([]byte(contract)) - script := fmt.Appendf(nil, `transaction { + script := []byte(fmt.Sprintf(`transaction { prepare(signer: auth(AddContract) &Account, service: &Account) { signer.contracts.add(name: "%s", code: "%s".decodeHex()) } - }`, contractName, encoded) + }`, contractName, encoded)) txBodyBuilder := flow.NewTransactionBodyBuilder(). SetScript(script). @@ -54,11 +54,11 @@ func UpdateContractDeploymentTransaction(contractName string, contract string, a encoded := hex.EncodeToString([]byte(contract)) return flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, `transaction { + SetScript([]byte(fmt.Sprintf(`transaction { prepare(signer: auth(UpdateContract) &Account, service: &Account) { signer.contracts.update(name: "%s", code: "%s".decodeHex()) } - }`, contractName, encoded), + }`, contractName, encoded)), ). AddAuthorizer(authorizer). AddAuthorizer(chain.ServiceAddress()) @@ -68,22 +68,22 @@ func UpdateContractUnathorizedDeploymentTransaction(contractName string, contrac encoded := hex.EncodeToString([]byte(contract)) return flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, `transaction { + SetScript([]byte(fmt.Sprintf(`transaction { prepare(signer: auth(UpdateContract) &Account) { signer.contracts.update(name: "%s", code: "%s".decodeHex()) } - }`, contractName, encoded), + }`, contractName, encoded)), ). AddAuthorizer(authorizer) } func RemoveContractDeploymentTransaction(contractName string, authorizer flow.Address, chain flow.Chain) *flow.TransactionBodyBuilder { return flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, `transaction { + SetScript([]byte(fmt.Sprintf(`transaction { prepare(signer: auth(RemoveContract) &Account, service: &Account) { signer.contracts.remove(name: "%s") } - }`, contractName), + }`, contractName)), ). AddAuthorizer(authorizer). AddAuthorizer(chain.ServiceAddress()) @@ -91,11 +91,11 @@ func RemoveContractDeploymentTransaction(contractName string, authorizer flow.Ad func RemoveContractUnathorizedDeploymentTransaction(contractName string, authorizer flow.Address) *flow.TransactionBodyBuilder { return flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, `transaction { + SetScript([]byte(fmt.Sprintf(`transaction { prepare(signer: auth(RemoveContract) &Account) { signer.contracts.remove(name: "%s") } - }`, contractName), + }`, contractName)), ). AddAuthorizer(authorizer) } @@ -104,11 +104,11 @@ func CreateUnauthorizedContractDeploymentTransaction(contractName string, contra encoded := hex.EncodeToString([]byte(contract)) return flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, `transaction { + SetScript([]byte(fmt.Sprintf(`transaction { prepare(signer: auth(AddContract) &Account) { signer.contracts.add(name: "%s", code: "%s".decodeHex()) } - }`, contractName, encoded), + }`, contractName, encoded)), ). AddAuthorizer(authorizer) } @@ -165,7 +165,7 @@ func SignTransactionAsServiceAccount(tx *flow.TransactionBodyBuilder, seqNum uin // GenerateAccountPrivateKeys generates a number of private keys. func GenerateAccountPrivateKeys(numberOfPrivateKeys int) ([]flow.AccountPrivateKey, error) { var privateKeys []flow.AccountPrivateKey - for range numberOfPrivateKeys { + for i := 0; i < numberOfPrivateKeys; i++ { pk, err := GenerateAccountPrivateKey() if err != nil { return nil, err @@ -251,13 +251,14 @@ func CreateAccountsWithSimpleAddresses( cadPublicKey := BytesToCadenceArray(encPublicKey) encCadPublicKey, _ := jsoncdc.Encode(cadPublicKey) - script := - fmt.Appendf(nil, + script := []byte( + fmt.Sprintf( scriptTemplate, accountKey.SignAlgo.String(), accountKey.HashAlgo.String(), accountKey.Weight, - ) + ), + ) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(script). @@ -443,7 +444,7 @@ func CreateMultiAccountCreationTransaction(t *testing.T, chain flow.Chain, n int // CreateAddAnAccountKeyMultipleTimesTransaction generates a tx that adds a key several times to an account. // this can be used to exhaust an account's storage. func CreateAddAnAccountKeyMultipleTimesTransaction(t *testing.T, accountKey *flow.AccountPrivateKey, counts int) *flow.TransactionBodyBuilder { - script := fmt.Appendf(nil, ` + script := []byte(fmt.Sprintf(` transaction(counts: Int, key: [UInt8]) { prepare(signer: auth(AddKey) &Account) { var i = 0 @@ -461,7 +462,7 @@ func CreateAddAnAccountKeyMultipleTimesTransaction(t *testing.T, accountKey *flo } } } - `, accountKey.SignAlgo.String(), accountKey.HashAlgo.String()) + `, accountKey.SignAlgo.String(), accountKey.HashAlgo.String())) arg1, err := jsoncdc.Encode(cadence.NewInt(counts)) require.NoError(t, err) diff --git a/engine/execution/testutil/fixtures_checker_heavy_contract.go b/engine/execution/testutil/fixtures_checker_heavy_contract.go index 007fe26d434..9740f654af8 100644 --- a/engine/execution/testutil/fixtures_checker_heavy_contract.go +++ b/engine/execution/testutil/fixtures_checker_heavy_contract.go @@ -10,7 +10,7 @@ func DeployLocalReplayLimitedTransaction(authorizer flow.Address, chain flow.Cha var builder strings.Builder builder.WriteString("let t = T") - for range 30 { + for i := 0; i < 30; i++ { builder.WriteString("()") @@ -26,9 +26,9 @@ func DeployLocalReplayLimitedTransaction(authorizer flow.Address, chain flow.Cha func DeployGlobalReplayLimitedTransaction(authorizer flow.Address, chain flow.Chain) *flow.TransactionBodyBuilder { var builder strings.Builder - for range 2 { + for j := 0; j < 2; j++ { builder.WriteString(";let t = T") - for range 16 { + for i := 0; i < 16; i++ { builder.WriteString("(from: /storage/counter) counter?.add(2) } - }`, counter)). + }`, counter))). AddAuthorizer(signer) } diff --git a/engine/execution/testutil/fixtures_event.go b/engine/execution/testutil/fixtures_event.go index c33bd362607..b976f96fba2 100644 --- a/engine/execution/testutil/fixtures_event.go +++ b/engine/execution/testutil/fixtures_event.go @@ -34,7 +34,7 @@ func UpdateEventContractTransaction(authorizer flow.Address, chain flow.Chain, e func CreateEmitEventTransaction(contractAccount, signer flow.Address) *flow.TransactionBodyBuilder { return flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` import EventContract from 0x%s transaction { @@ -42,7 +42,7 @@ func CreateEmitEventTransaction(contractAccount, signer flow.Address) *flow.Tran execute { EventContract.EmitEvent() } - }`, contractAccount), + }`, contractAccount)), ). AddAuthorizer(signer) } diff --git a/engine/execution/testutil/fixtures_token.go b/engine/execution/testutil/fixtures_token.go index 7e66349a547..0c93c24b39c 100644 --- a/engine/execution/testutil/fixtures_token.go +++ b/engine/execution/testutil/fixtures_token.go @@ -13,7 +13,7 @@ import ( func CreateTokenTransferTransaction(chain flow.Chain, amount int, to flow.Address, signer flow.Address) *flow.TransactionBodyBuilder { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) return flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` import FungibleToken from 0x%s import FlowToken from 0x%s @@ -32,7 +32,7 @@ func CreateTokenTransferTransaction(chain flow.Chain, amount int, to flow.Addres ?? panic("Could not borrow receiver reference to the recipient's Vault") receiverRef.deposit(from: <-self.sentVault) } - }`, sc.FungibleToken.Address.Hex(), sc.FlowToken.Address.Hex())). + }`, sc.FungibleToken.Address.Hex(), sc.FlowToken.Address.Hex()))). AddArgument(jsoncdc.MustEncode(cadence.UFix64(amount))). AddArgument(jsoncdc.MustEncode(cadence.NewAddress(to))). AddAuthorizer(signer) diff --git a/engine/ghost/client/ghost_client.go b/engine/ghost/client/ghost_client.go index ad5cf132062..219ddf230a8 100644 --- a/engine/ghost/client/ghost_client.go +++ b/engine/ghost/client/ghost_client.go @@ -53,7 +53,7 @@ func (c *GhostClient) Close() error { return c.close() } -func (c *GhostClient) Send(ctx context.Context, channel channels.Channel, event any, targetIDs ...flow.Identifier) error { +func (c *GhostClient) Send(ctx context.Context, channel channels.Channel, event interface{}, targetIDs ...flow.Identifier) error { message, err := c.codec.Encode(event) if err != nil { @@ -94,7 +94,7 @@ type FlowMessageStreamReader struct { codec network.Codec } -func (fmsr *FlowMessageStreamReader) Next() (flow.Identifier, any, error) { +func (fmsr *FlowMessageStreamReader) Next() (flow.Identifier, interface{}, error) { msg, err := fmsr.stream.Recv() if errors.Is(err, io.EOF) { // read done. diff --git a/engine/protocol/api_test.go b/engine/protocol/api_test.go index dbfedc2c3c1..42f1f23f45c 100644 --- a/engine/protocol/api_test.go +++ b/engine/protocol/api_test.go @@ -589,7 +589,7 @@ func (suite *Suite) TestGetBlockHeaderByHeight_InternalFailure() { suite.assertAllExpectations() } -func (suite *Suite) checkResponse(resp any, err error) { +func (suite *Suite) checkResponse(resp interface{}, err error) { suite.Require().NoError(err) suite.Require().NotNil(resp) } diff --git a/engine/verification/assigner/blockconsumer/consumer_test.go b/engine/verification/assigner/blockconsumer/consumer_test.go index 96a190483aa..11c1aaef99d 100644 --- a/engine/verification/assigner/blockconsumer/consumer_test.go +++ b/engine/verification/assigner/blockconsumer/consumer_test.go @@ -52,7 +52,7 @@ func TestProduceConsume(t *testing.T) { withConsumer(t, 10, 3, neverFinish, func(consumer *blockconsumer.BlockConsumer, blocks []*flow.Block, followerDistributor *pubsub.FollowerDistributor) { unittest.RequireCloseBefore(t, consumer.Ready(), time.Second, "could not start consumer") - for range blocks { + for i := 0; i < len(blocks); i++ { // consumer is only required to be "notified" that a new finalized block available. // It keeps track of the last finalized block it has read, and read the next height upon // getting notified as follows: @@ -93,7 +93,7 @@ func TestProduceConsume(t *testing.T) { }() processAll.Add(len(blocks)) - for range blocks { + for i := 0; i < len(blocks); i++ { // consumer is only required to be "notified" that a new finalized block available. // It keeps track of the last finalized block it has read, and read the next height upon // getting notified as follows: diff --git a/engine/verification/fetcher/chunkconsumer/consumer_test.go b/engine/verification/fetcher/chunkconsumer/consumer_test.go index a52c3a089b1..e0079bf5cd4 100644 --- a/engine/verification/fetcher/chunkconsumer/consumer_test.go +++ b/engine/verification/fetcher/chunkconsumer/consumer_test.go @@ -72,9 +72,11 @@ func TestProduceConsume(t *testing.T) { lock.Lock() defer lock.Unlock() called = append(called, locator) - finishAll.Go(func() { + finishAll.Add(1) + go func() { notifier.Notify(locator.ID()) - }) + finishAll.Done() + }() } WithConsumer(t, alwaysFinish, func(consumer *chunkconsumer.ChunkConsumer, chunksQueue storage.ChunksQueue) { <-consumer.Ready() @@ -117,7 +119,7 @@ func TestProduceConsume(t *testing.T) { locators := unittest.ChunkLocatorListFixture(100) - for i := range locators { + for i := 0; i < len(locators); i++ { go func(i int) { ok, err := chunksQueue.StoreChunkLocator(locators[i]) require.NoError(t, err, fmt.Sprintf("chunk locator %v can't be stored", i)) diff --git a/engine/verification/fetcher/engine_test.go b/engine/verification/fetcher/engine_test.go index bbfb55ad512..3af15e04fc0 100644 --- a/engine/verification/fetcher/engine_test.go +++ b/engine/verification/fetcher/engine_test.go @@ -578,7 +578,7 @@ func mockReceiptsBlockID(t *testing.T, agreeExecutors := flow.IdentityList{} disagreeExecutors := flow.IdentityList{} - for range agrees { + for i := 0; i < agrees; i++ { receipt := unittest.ExecutionReceiptFixture(unittest.WithResult(result)) require.NotContains(t, agreeExecutors.NodeIDs(), receipt.ExecutorID) // should not have duplicate executors agreeExecutors = append(agreeExecutors, unittest.IdentityFixture( @@ -587,7 +587,7 @@ func mockReceiptsBlockID(t *testing.T, agreeReceipts = append(agreeReceipts, receipt) } - for range disagrees { + for i := 0; i < disagrees; i++ { disagreeResult := unittest.ExecutionResultFixture() require.NotEqual(t, disagreeResult.ID(), result.ID()) diff --git a/engine/verification/utils/unittest/fixture.go b/engine/verification/utils/unittest/fixture.go index 885bc3d11e2..018b769b4f6 100644 --- a/engine/verification/utils/unittest/fixture.go +++ b/engine/verification/utils/unittest/fixture.go @@ -415,7 +415,7 @@ func CompleteExecutionReceiptChainFixture(t *testing.T, "number of executors in the tests should be greater than or equal to the number of receipts per block") var sourcesIndex = 0 - for range count { + for i := 0; i < count; i++ { // Generates two blocks as parent <- R <- C where R is a reference block containing guarantees, // and C is a container block containing execution receipt for R. receipts, allData, head := ExecutionReceiptsFromParentBlockFixture(t, parent, rootProtocolStateID, builder, sources[sourcesIndex:]) diff --git a/engine/verification/verifier/engine.go b/engine/verification/verifier/engine.go index 47c508afdff..2d35b9f3a45 100644 --- a/engine/verification/verifier/engine.go +++ b/engine/verification/verifier/engine.go @@ -99,7 +99,7 @@ func (e *Engine) Done() <-chan struct{} { } // SubmitLocal submits an event originating on the local node. -func (e *Engine) SubmitLocal(event any) { +func (e *Engine) SubmitLocal(event interface{}) { e.unit.Launch(func() { err := e.ProcessLocal(event) if err != nil { @@ -111,7 +111,7 @@ func (e *Engine) SubmitLocal(event any) { // Submit submits the given event from the node with the given origin ID // for processing in a non-blocking manner. It returns instantly and logs // a potential processing error internally when done. -func (e *Engine) Submit(channel channels.Channel, originID flow.Identifier, event any) { +func (e *Engine) Submit(channel channels.Channel, originID flow.Identifier, event interface{}) { e.unit.Launch(func() { err := e.Process(channel, originID, event) if err != nil { @@ -121,7 +121,7 @@ func (e *Engine) Submit(channel channels.Channel, originID flow.Identifier, even } // ProcessLocal processes an event originating on the local node. -func (e *Engine) ProcessLocal(event any) error { +func (e *Engine) ProcessLocal(event interface{}) error { return e.unit.Do(func() error { return e.process(e.me.NodeID(), event) }) @@ -129,14 +129,14 @@ func (e *Engine) ProcessLocal(event any) error { // Process processes the given event from the node with the given origin ID in // a blocking manner. It returns the potential processing error when done. -func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event any) error { +func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { return e.unit.Do(func() error { return e.process(originID, event) }) } // process receives verifiable chunks, evaluate them and send them for chunk verifier -func (e *Engine) process(originID flow.Identifier, event any) error { +func (e *Engine) process(originID flow.Identifier, event interface{}) error { var err error switch resource := event.(type) { diff --git a/engine/verification/verifier/verifiers.go b/engine/verification/verifier/verifiers.go index 56c350ba64b..d416d15a94e 100644 --- a/engine/verification/verifier/verifiers.go +++ b/engine/verification/verifier/verifiers.go @@ -256,9 +256,11 @@ func verifyConcurrently( // Start nWorker workers var wg sync.WaitGroup for i := 0; i < int(nWorker); i++ { - wg.Go(func() { + wg.Add(1) + go func() { + defer wg.Done() worker() - }) + }() } // Send tasks to workers diff --git a/fvm/accounts_test.go b/fvm/accounts_test.go index b9d3147af32..80368ecda66 100644 --- a/fvm/accounts_test.go +++ b/fvm/accounts_test.go @@ -142,11 +142,12 @@ func addAccountCreator( snapshotTree snapshot.SnapshotTree, account flow.Address, ) snapshot.SnapshotTree { - script := - fmt.Appendf(nil, addAccountCreatorTransactionTemplate, + script := []byte( + fmt.Sprintf(addAccountCreatorTransactionTemplate, chain.ServiceAddress().String(), account.String(), - ) + ), + ) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(script). @@ -173,12 +174,13 @@ func removeAccountCreator( snapshotTree snapshot.SnapshotTree, account flow.Address, ) snapshot.SnapshotTree { - script := - fmt.Appendf(nil, + script := []byte( + fmt.Sprintf( removeAccountCreatorTransactionTemplate, chain.ServiceAddress(), account.String(), - ) + ), + ) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(script). @@ -886,7 +888,7 @@ func TestAddAccountKey(t *testing.T) { _, publicKeyArg := newAccountKey(t, privateKey, accountKeyAPIVersionV2) txBody, err := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, + SetScript([]byte(fmt.Sprintf( ` transaction(key: [UInt8]) { prepare(signer: auth(AddKey) &Account) { @@ -903,7 +905,7 @@ func TestAddAccountKey(t *testing.T) { } `, hashAlgo, - )). + ))). SetPayer(address). AddArgument(publicKeyArg). AddAuthorizer(address). @@ -973,7 +975,7 @@ func TestRemoveAccountKey(t *testing.T) { const keyCount = 2 - for range keyCount { + for i := 0; i < keyCount; i++ { snapshotTree, _ = addAccountKey( t, vm, @@ -1037,7 +1039,7 @@ func TestRemoveAccountKey(t *testing.T) { const keyCount = 2 const keyIndex = keyCount - 1 - for range keyCount { + for i := 0; i < keyCount; i++ { snapshotTree, _ = addAccountKey( t, vm, @@ -1096,7 +1098,7 @@ func TestRemoveAccountKey(t *testing.T) { const keyCount = 2 const keyIndex = keyCount - 1 - for range keyCount { + for i := 0; i < keyCount; i++ { snapshotTree, _ = addAccountKey( t, vm, @@ -1165,7 +1167,7 @@ func TestRemoveAccountKey(t *testing.T) { const keyCount = 2 - for range keyCount { + for i := 0; i < keyCount; i++ { snapshotTree, _ = addAccountKey( t, vm, @@ -1184,7 +1186,7 @@ func TestRemoveAccountKey(t *testing.T) { SetPayer(address). AddAuthorizer(address) - for i := range keyCount { + for i := 0; i < keyCount; i++ { keyIndexArg, err := jsoncdc.Encode(cadence.NewInt(i)) require.NoError(t, err) @@ -1237,7 +1239,7 @@ func TestGetAccountKey(t *testing.T) { const keyCount = 2 - for range keyCount { + for i := 0; i < keyCount; i++ { snapshotTree, _ = addAccountKey( t, vm, @@ -1292,7 +1294,7 @@ func TestGetAccountKey(t *testing.T) { const keyIndex = keyCount - 1 keys := make([]flow.AccountPublicKey, keyCount) - for i := range keyCount { + for i := 0; i < keyCount; i++ { snapshotTree, keys[i] = addAccountKey( t, vm, @@ -1357,7 +1359,7 @@ func TestGetAccountKey(t *testing.T) { const keyIndex = keyCount - 1 keys := make([]flow.AccountPublicKey, keyCount) - for i := range keyCount { + for i := 0; i < keyCount; i++ { // Use the old version of API to add the key snapshotTree, keys[i] = addAccountKey( @@ -1423,7 +1425,7 @@ func TestGetAccountKey(t *testing.T) { const keyCount = 2 keys := make([]flow.AccountPublicKey, keyCount) - for i := range keyCount { + for i := 0; i < keyCount; i++ { snapshotTree, keys[i] = addAccountKey( t, @@ -1443,7 +1445,7 @@ func TestGetAccountKey(t *testing.T) { SetPayer(address). AddAuthorizer(address) - for i := range keyCount { + for i := 0; i < keyCount; i++ { keyIndexArg, err := jsoncdc.Encode(cadence.NewInt(i)) require.NoError(t, err) @@ -1462,7 +1464,7 @@ func TestGetAccountKey(t *testing.T) { assert.Len(t, output.Logs, 2) - for i := range keyCount { + for i := 0; i < keyCount; i++ { expected := fmt.Sprintf( "AccountKey("+ "keyIndex: %d, "+ @@ -1525,12 +1527,12 @@ func TestAccountBalanceFields(t *testing.T) { snapshotTree = snapshotTree.Append(executionSnapshot) - script := fvm.Script(fmt.Appendf(nil, ` + script := fvm.Script([]byte(fmt.Sprintf(` access(all) fun main(): UFix64 { let acc = getAccount(0x%s) return acc.balance } - `, account.Hex())) + `, account.Hex()))) _, output, err = vm.Run(ctx, script, snapshotTree) require.NoError(t, err) @@ -1555,12 +1557,12 @@ func TestAccountBalanceFields(t *testing.T) { nonExistentAddress, err := chain.AddressAtIndex(100) require.NoError(t, err) - script := fvm.Script(fmt.Appendf(nil, ` + script := fvm.Script([]byte(fmt.Sprintf(` access(all) fun main(): UFix64 { let acc = getAccount(0x%s) return acc.balance } - `, nonExistentAddress)) + `, nonExistentAddress))) _, output, err := vm.Run(ctx, script, snapshotTree) require.NoError(t, err) @@ -1586,12 +1588,12 @@ func TestAccountBalanceFields(t *testing.T) { ctx, snapshotTree) - script := fvm.Script(fmt.Appendf(nil, ` + script := fvm.Script([]byte(fmt.Sprintf(` access(all) fun main(): UFix64 { let acc = getAccount(0x%s) return acc.balance } - `, address)) + `, address))) snapshot := errorOnAddressSnapshotWrapper{ snapshotTree: snapshotTree, @@ -1642,12 +1644,12 @@ func TestAccountBalanceFields(t *testing.T) { snapshotTree = snapshotTree.Append(executionSnapshot) - script := fvm.Script(fmt.Appendf(nil, ` + script := fvm.Script([]byte(fmt.Sprintf(` access(all) fun main(): UFix64 { let acc = getAccount(0x%s) return acc.availableBalance } - `, account.Hex())) + `, account.Hex()))) _, output, err = vm.Run(ctx, script, snapshotTree) assert.NoError(t, err) @@ -1669,12 +1671,12 @@ func TestAccountBalanceFields(t *testing.T) { nonExistentAddress, err := chain.AddressAtIndex(100) require.NoError(t, err) - script := fvm.Script(fmt.Appendf(nil, ` + script := fvm.Script([]byte(fmt.Sprintf(` access(all) fun main(): UFix64 { let acc = getAccount(0x%s) return acc.availableBalance } - `, nonExistentAddress)) + `, nonExistentAddress))) _, output, err := vm.Run(ctx, script, snapshotTree) assert.NoError(t, err) @@ -1718,12 +1720,12 @@ func TestAccountBalanceFields(t *testing.T) { snapshotTree = snapshotTree.Append(executionSnapshot) - script := fvm.Script(fmt.Appendf(nil, ` + script := fvm.Script([]byte(fmt.Sprintf(` access(all) fun main(): UFix64 { let acc = getAccount(0x%s) return acc.availableBalance } - `, account.Hex())) + `, account.Hex()))) _, output, err = vm.Run(ctx, script, snapshotTree) assert.NoError(t, err) @@ -1775,12 +1777,12 @@ func TestGetStorageCapacity(t *testing.T) { snapshotTree = snapshotTree.Append(executionSnapshot) - script := fvm.Script(fmt.Appendf(nil, ` + script := fvm.Script([]byte(fmt.Sprintf(` access(all) fun main(): UInt64 { let acc = getAccount(0x%s) return acc.storage.capacity } - `, account)) + `, account))) _, output, err = vm.Run(ctx, script, snapshotTree) require.NoError(t, err) @@ -1804,12 +1806,12 @@ func TestGetStorageCapacity(t *testing.T) { nonExistentAddress, err := chain.AddressAtIndex(100) require.NoError(t, err) - script := fvm.Script(fmt.Appendf(nil, ` + script := fvm.Script([]byte(fmt.Sprintf(` access(all) fun main(): UInt64 { let acc = getAccount(0x%s) return acc.storage.capacity } - `, nonExistentAddress)) + `, nonExistentAddress))) _, output, err := vm.Run(ctx, script, snapshotTree) @@ -1832,12 +1834,12 @@ func TestGetStorageCapacity(t *testing.T) { run(func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { address := chain.ServiceAddress() - script := fvm.Script(fmt.Appendf(nil, ` + script := fvm.Script([]byte(fmt.Sprintf(` access(all) fun main(): UInt64 { let acc = getAccount(0x%s) return acc.storage.capacity } - `, address)) + `, address))) storageSnapshot := errorOnAddressSnapshotWrapper{ owner: address, diff --git a/fvm/crypto/hash_test.go b/fvm/crypto/hash_test.go index 39f00c0a635..11701587981 100644 --- a/fvm/crypto/hash_test.go +++ b/fvm/crypto/hash_test.go @@ -3,7 +3,6 @@ package crypto_test import ( "crypto/rand" "crypto/sha256" - sha30 "crypto/sha3" "crypto/sha512" "testing" @@ -25,7 +24,7 @@ func TestPrefixedHash(t *testing.T) { return h[:] }, hash.SHA3_256: func(data []byte) []byte { - h := sha30.Sum256(data) + h := sha3.Sum256(data) return h[:] }, hash.SHA2_384: func(data []byte) []byte { @@ -33,7 +32,7 @@ func TestPrefixedHash(t *testing.T) { return h[:] }, hash.SHA3_384: func(data []byte) []byte { - h := sha30.Sum384(data) + h := sha3.Sum384(data) return h[:] }, hash.Keccak_256: func(data []byte) []byte { diff --git a/fvm/environment/accounts.go b/fvm/environment/accounts.go index 33da3240c9e..6af89260b0c 100644 --- a/fvm/environment/accounts.go +++ b/fvm/environment/accounts.go @@ -469,7 +469,7 @@ func (a *StatefulAccounts) GetAccountPublicKeys( } publicKeys = make([]flow.AccountPublicKey, count) - for i := range count { + for i := uint32(0); i < count; i++ { publicKey, err := a.GetAccountPublicKey(address, i) if err != nil { return nil, err diff --git a/fvm/environment/contract_updater.go b/fvm/environment/contract_updater.go index a167d0efa3f..958b5802f1d 100644 --- a/fvm/environment/contract_updater.go +++ b/fvm/environment/contract_updater.go @@ -3,7 +3,6 @@ package environment import ( "bytes" "fmt" - "slices" "sort" "github.com/onflow/cadence" @@ -521,9 +520,11 @@ func (updater *ContractUpdaterImpl) isAuthorized( ) bool { accts := updater.GetAuthorizedAccounts(path) for _, authorized := range accts { - if slices.Contains(signingAccounts, authorized) { - // a single authorized singer is enough - return true + for _, signer := range signingAccounts { + if signer == authorized { + // a single authorized singer is enough + return true + } } } return false diff --git a/fvm/environment/evm_block_hash_list.go b/fvm/environment/evm_block_hash_list.go index 733e0b8bcc9..cd85d2f4093 100644 --- a/fvm/environment/evm_block_hash_list.go +++ b/fvm/environment/evm_block_hash_list.go @@ -171,7 +171,7 @@ func (bhl *BlockHashList) updateBlockHashAt(idx int, bh gethCommon.Hash) error { // store bucket return bhl.backend.SetValue( bhl.rootAddress[:], - fmt.Appendf(nil, blockHashListBucketKeyFormat, bucketNumber), + []byte(fmt.Sprintf(blockHashListBucketKeyFormat, bucketNumber)), cpy, ) } @@ -180,7 +180,7 @@ func (bhl *BlockHashList) updateBlockHashAt(idx int, bh gethCommon.Hash) error { func (bhl *BlockHashList) fetchBucket(num int) ([]byte, error) { data, err := bhl.backend.GetValue( bhl.rootAddress[:], - fmt.Appendf(nil, blockHashListBucketKeyFormat, num), + []byte(fmt.Sprintf(blockHashListBucketKeyFormat, num)), ) if err != nil { return nil, err diff --git a/fvm/environment/evm_block_hash_list_test.go b/fvm/environment/evm_block_hash_list_test.go index e95b21ea42c..8e731ada078 100644 --- a/fvm/environment/evm_block_hash_list_test.go +++ b/fvm/environment/evm_block_hash_list_test.go @@ -29,7 +29,7 @@ func TestBlockHashList(t *testing.T) { require.Equal(t, gethCommon.Hash{}, h) // first add blocks for the full range of capacity - for i := range capacity { + for i := 0; i < capacity; i++ { err := bhl.Push(uint64(i), gethCommon.Hash{byte(i)}) require.NoError(t, err) require.Equal(t, uint64(0), bhl.MinAvailableHeight()) @@ -40,7 +40,7 @@ func TestBlockHashList(t *testing.T) { } // check the value for all of them - for i := range capacity { + for i := 0; i < capacity; i++ { found, h, err := bhl.BlockHashByHeight(uint64(i)) require.NoError(t, err) require.True(t, found) @@ -58,7 +58,7 @@ func TestBlockHashList(t *testing.T) { require.Equal(t, uint64(i), bhl.MaxAvailableHeight()) } // check that old block has been replaced - for i := range 3 { + for i := 0; i < 3; i++ { found, _, err := bhl.BlockHashByHeight(uint64(i)) require.NoError(t, err) require.False(t, found) diff --git a/fvm/environment/evm_block_store_benchmark_test.go b/fvm/environment/evm_block_store_benchmark_test.go index be8cacd7695..7f7e5170a21 100644 --- a/fvm/environment/evm_block_store_benchmark_test.go +++ b/fvm/environment/evm_block_store_benchmark_test.go @@ -18,7 +18,7 @@ func benchmarkBlockProposalGrowth(b *testing.B, txCounts int) { testutils.RunWithTestFlowEVMRootAddress(b, backend, func(rootAddr flow.Address) { bs := environment.NewBlockStore(flow.Testnet, backend, backend, backend, rootAddr) - for range txCounts { + for i := 0; i < txCounts; i++ { bp, err := bs.BlockProposal() require.NoError(b, err) res := testutils.RandomResultFixture(b) diff --git a/fvm/environment/program_recovery.go b/fvm/environment/program_recovery.go index de849c40595..834c4fd07b9 100644 --- a/fvm/environment/program_recovery.go +++ b/fvm/environment/program_recovery.go @@ -41,7 +41,7 @@ func RecoverProgram( } func RecoveredFungibleTokenCode(fungibleTokenAddress common.Address, contractName string) []byte { - return fmt.Appendf(nil, + return []byte(fmt.Sprintf( //language=Cadence ` import FungibleToken from %[1]s @@ -126,11 +126,11 @@ func RecoveredFungibleTokenCode(fungibleTokenAddress common.Address, contractNam "A version of the contract has been recovered to allow access to the fields declared in the FT standard.", contractName, ), - ) + )) } func RecoveredNonFungibleTokenCode(nonFungibleTokenAddress common.Address, contractName string) []byte { - return fmt.Appendf(nil, + return []byte(fmt.Sprintf( //language=Cadence ` import NonFungibleToken from %[1]s @@ -239,7 +239,7 @@ func RecoveredNonFungibleTokenCode(nonFungibleTokenAddress common.Address, contr "A version of the contract has been recovered to allow access to the fields declared in the NFT standard.", contractName, ), - ) + )) } func importsAddressLocation(program *ast.Program, address common.Address, name string) bool { diff --git a/fvm/environment/programs_test.go b/fvm/environment/programs_test.go index 5d5d3dab45a..e6cc695268f 100644 --- a/fvm/environment/programs_test.go +++ b/fvm/environment/programs_test.go @@ -752,13 +752,13 @@ func Test_ProgramsDoubleCounting(t *testing.T) { func callTx(name string, address flow.Address) (*flow.TransactionBody, error) { return flow.NewTransactionBodyBuilder().SetScript( - fmt.Appendf(nil, ` + []byte(fmt.Sprintf(` import %s from %s transaction { prepare() { log(%s.hello()) } - }`, name, address.HexWithPrefix(), name), + }`, name, address.HexWithPrefix(), name)), ). SetPayer(address). Build() @@ -769,11 +769,11 @@ func contractDeployTx(name, code string, address flow.Address) (*flow.Transactio return flow.NewTransactionBodyBuilder(). SetScript( - fmt.Appendf(nil, `transaction { + []byte(fmt.Sprintf(`transaction { prepare(signer: auth(AddContract) &Account) { signer.contracts.add(name: "%s", code: "%s".decodeHex()) } - }`, name, encoded), + }`, name, encoded)), ). AddAuthorizer(address). SetPayer(address). @@ -785,11 +785,11 @@ func updateContractTx(name, code string, address flow.Address) (*flow.Transactio return flow.NewTransactionBodyBuilder(). SetScript( - fmt.Appendf(nil, `transaction { + []byte(fmt.Sprintf(`transaction { prepare(signer: auth(UpdateContract) &Account) { signer.contracts.update(name: "%s", code: "%s".decodeHex()) } - }`, name, encoded), + }`, name, encoded)), ). AddAuthorizer(address). SetPayer(address). diff --git a/fvm/environment/random_generator_test.go b/fvm/environment/random_generator_test.go index 6db0769de3d..85f1244e9fb 100644 --- a/fvm/environment/random_generator_test.go +++ b/fvm/environment/random_generator_test.go @@ -26,7 +26,7 @@ func TestRandomGenerator(t *testing.T) { randomSourceHistoryProvider, txId) numbers := make([]uint64, N) - for i := range N { + for i := 0; i < N; i++ { var buffer [8]byte err := urg.ReadRandom(buffer[:]) require.NoError(t, err) @@ -38,7 +38,7 @@ func TestRandomGenerator(t *testing.T) { // basic randomness test to check outputs are "uniformly" spread over the // output space t.Run("randomness test", func(t *testing.T) { - for range 10 { + for i := 0; i < 10; i++ { txId := unittest.TransactionFixture().ID() urg := environment.NewRandomGenerator( tracing.NewTracerSpan(), @@ -62,7 +62,7 @@ func TestRandomGenerator(t *testing.T) { // tests that has deterministic outputs. t.Run("PRG-based Random", func(t *testing.T) { - for range 10 { + for i := 0; i < 10; i++ { txId := unittest.TransactionFixture().ID() N := 100 r1 := getRandoms(txId[:], N) @@ -73,7 +73,7 @@ func TestRandomGenerator(t *testing.T) { t.Run("transaction specific randomness", func(t *testing.T) { txns := [][]uint64{} - for range 10 { + for i := 0; i < 10; i++ { txId := unittest.TransactionFixture().ID() N := 2 txns = append(txns, getRandoms(txId[:], N)) diff --git a/fvm/environment/uuids_test.go b/fvm/environment/uuids_test.go index bc1975b3db1..8166f715cb1 100644 --- a/fvm/environment/uuids_test.go +++ b/fvm/environment/uuids_test.go @@ -19,20 +19,20 @@ func TestUUIDPartition(t *testing.T) { // With enough samples, all partitions should be used. (The first 1500 blocks // only uses 254 partitions) - for range 2500 { + for numBlocks := 0; numBlocks < 2500; numBlocks++ { blockId := blockHeader.ID() partition0 := uuidPartition(blockId, 0) usedPartitions[partition0] = struct{}{} - for txnIndex := range 256 { + for txnIndex := 0; txnIndex < 256; txnIndex++ { partition := uuidPartition(blockId, uint32(txnIndex)) // Ensure neighboring transactions uses neighoring partitions. require.Equal(t, partition, partition0+byte(txnIndex)) // Ensure wrap around. - for i := range 5 { + for i := 0; i < 5; i++ { require.Equal( t, partition, @@ -47,7 +47,7 @@ func TestUUIDPartition(t *testing.T) { } func TestUUIDGeneratorInitializePartitionNoHeader(t *testing.T) { - for txnIndex := range uint32(256) { + for txnIndex := uint32(0); txnIndex < 256; txnIndex++ { uuids := NewUUIDGenerator( tracing.NewTracerSpan(), zerolog.Nop(), @@ -68,10 +68,10 @@ func TestUUIDGeneratorInitializePartitionNoHeader(t *testing.T) { func TestUUIDGeneratorInitializePartition(t *testing.T) { blockHeader := &flow.Header{} - for range 10 { + for numBlocks := 0; numBlocks < 10; numBlocks++ { blockId := blockHeader.ID() - for txnIndex := range uint32(256) { + for txnIndex := uint32(0); txnIndex < 256; txnIndex++ { uuids := NewUUIDGenerator( tracing.NewTracerSpan(), zerolog.Nop(), @@ -99,7 +99,7 @@ func TestUUIDGeneratorInitializePartition(t *testing.T) { } func TestUUIDGeneratorIdGeneration(t *testing.T) { - for txnIndex := range uint32(256) { + for txnIndex := uint32(0); txnIndex < 256; txnIndex++ { testUUIDGenerator(t, &flow.Header{}, txnIndex) } } @@ -312,7 +312,7 @@ func TestUUIDGeneratorHardcodedPartitionIdGeneration(t *testing.T) { err = uuids.setCounter(cafBad) require.NoError(t, err) - for i := range 5 { + for i := 0; i < 5; i++ { value, err = uuids.GenerateUUID() require.NoError(t, err) require.Equal(t, value, decafBad+uint64(i)) diff --git a/fvm/evm/emulator/state/base_test.go b/fvm/evm/emulator/state/base_test.go index 034fc28cf2c..fec5bc6b082 100644 --- a/fvm/evm/emulator/state/base_test.go +++ b/fvm/evm/emulator/state/base_test.go @@ -312,7 +312,7 @@ func TestBaseView(t *testing.T) { nonces := make(map[gethCommon.Address]uint64) balances := make(map[gethCommon.Address]*uint256.Int) codeHashes := make(map[gethCommon.Address]gethCommon.Hash) - for range accountCounts { + for i := 0; i < accountCounts; i++ { addr := testutils.RandomCommonAddress(t) balance := testutils.RandomUint256Int(1000) nonce := testutils.RandomBigInt(1000).Uint64() @@ -360,7 +360,7 @@ func TestBaseView(t *testing.T) { codeCounts := 10 codeByCodeHash := make(map[gethCommon.Hash][]byte) refCountByCodeHash := make(map[gethCommon.Hash]uint64) - for i := range codeCounts { + for i := 0; i < codeCounts; i++ { code := testutils.RandomData(t) codeHash := testutils.RandomCommonHash(t) @@ -417,7 +417,7 @@ func TestBaseView(t *testing.T) { slotCounts := 10 values := make(map[gethCommon.Hash]gethCommon.Hash) - for range slotCounts { + for i := 0; i < slotCounts; i++ { key := testutils.RandomCommonHash(t) value := testutils.RandomCommonHash(t) diff --git a/fvm/evm/emulator/state/delta_test.go b/fvm/evm/emulator/state/delta_test.go index 24ee7d3ee2f..9ca089888af 100644 --- a/fvm/evm/emulator/state/delta_test.go +++ b/fvm/evm/emulator/state/delta_test.go @@ -583,7 +583,7 @@ func TestDeltaView(t *testing.T) { t.Run("test dirty addresses functionality", func(t *testing.T) { addrCount := 6 addresses := make([]gethCommon.Address, addrCount) - for i := range addrCount { + for i := 0; i < addrCount; i++ { addresses[i] = testutils.RandomCommonAddress(t) } diff --git a/fvm/evm/emulator/state/importer.go b/fvm/evm/emulator/state/importer.go index 9d366610a47..5eae814086d 100644 --- a/fvm/evm/emulator/state/importer.go +++ b/fvm/evm/emulator/state/importer.go @@ -3,6 +3,7 @@ package state import ( "encoding/gob" "fmt" + "io/ioutil" "os" "path/filepath" "strings" @@ -81,12 +82,12 @@ func ImportEVMState(path string) (*EVMState, error) { var codes []*CodeInContext var slots []*types.SlotEntry // Import codes - codesData, err := os.ReadFile(filepath.Join(path, ExportedCodesFileName)) + codesData, err := ioutil.ReadFile(filepath.Join(path, ExportedCodesFileName)) if err != nil { return nil, fmt.Errorf("error opening codes file: %w", err) } - codesLines := strings.SplitSeq(string(codesData), "\n") - for line := range codesLines { + codesLines := strings.Split(string(codesData), "\n") + for _, line := range codesLines { if line == "" { continue } @@ -98,12 +99,12 @@ func ImportEVMState(path string) (*EVMState, error) { } // Import slots - slotsData, err := os.ReadFile(filepath.Join(path, ExportedSlotsFileName)) + slotsData, err := ioutil.ReadFile(filepath.Join(path, ExportedSlotsFileName)) if err != nil { return nil, fmt.Errorf("error opening slots file: %w", err) } - slotsLines := strings.SplitSeq(string(slotsData), "\n") - for line := range slotsLines { + slotsLines := strings.Split(string(slotsData), "\n") + for _, line := range slotsLines { if line == "" { continue } @@ -115,12 +116,12 @@ func ImportEVMState(path string) (*EVMState, error) { } // Import accounts - accountsData, err := os.ReadFile(filepath.Join(path, ExportedAccountsFileName)) + accountsData, err := ioutil.ReadFile(filepath.Join(path, ExportedAccountsFileName)) if err != nil { return nil, fmt.Errorf("error opening accounts file: %w", err) } - accountsLines := strings.SplitSeq(string(accountsData), "\n") - for line := range accountsLines { + accountsLines := strings.Split(string(accountsData), "\n") + for _, line := range accountsLines { if line == "" { continue } diff --git a/fvm/evm/emulator/state/stateDB.go b/fvm/evm/emulator/state/stateDB.go index 26de1e598af..08a60146751 100644 --- a/fvm/evm/emulator/state/stateDB.go +++ b/fvm/evm/emulator/state/stateDB.go @@ -4,7 +4,6 @@ import ( "bytes" stdErrors "errors" "fmt" - "maps" "sort" gethCommon "github.com/ethereum/go-ethereum/common" @@ -430,7 +429,9 @@ func (db *StateDB) Logs( func (db *StateDB) Preimages() map[gethCommon.Hash][]byte { preImages := make(map[gethCommon.Hash][]byte, 0) for _, view := range db.views { - maps.Copy(preImages, view.Preimages()) + for k, v := range view.Preimages() { + preImages[k] = v + } } return preImages } diff --git a/fvm/evm/emulator/state/state_growth_test.go b/fvm/evm/emulator/state/state_growth_test.go index 81de6987fce..1dd133fe651 100644 --- a/fvm/evm/emulator/state/state_growth_test.go +++ b/fvm/evm/emulator/state/state_growth_test.go @@ -131,7 +131,7 @@ func Test_AccountCreations(t *testing.T) { accountChart := "accounts,storage_size" maxAccounts := 50_000 - for i := range maxAccounts { + for i := 0; i < maxAccounts; i++ { err = tester.run(func(state types.StateDB) { state.AddBalance(tester.newAddress(), uint256.NewInt(100), tracing.BalanceChangeUnspecified) }) @@ -158,7 +158,7 @@ func Test_AccountContractInteraction(t *testing.T) { // build test contract storage state contractState := make(map[common.Hash]common.Hash) - for i := range 10 { + for i := 0; i < 10; i++ { h := common.HexToHash(fmt.Sprintf("%d", i)) v := common.HexToHash(fmt.Sprintf("%d %s", i, make([]byte, 32))) contractState[h] = v @@ -168,7 +168,7 @@ func Test_AccountContractInteraction(t *testing.T) { code := make([]byte, 50000) interactions := 50000 - for i := range interactions { + for i := 0; i < interactions; i++ { err = tester.run(func(state types.StateDB) { // create a new account accAddr := tester.newAddress() diff --git a/fvm/evm/emulator/state/updateCommitter_test.go b/fvm/evm/emulator/state/updateCommitter_test.go index ea4e6f7d843..ab0be67a08f 100644 --- a/fvm/evm/emulator/state/updateCommitter_test.go +++ b/fvm/evm/emulator/state/updateCommitter_test.go @@ -114,13 +114,13 @@ func BenchmarkDeltaCommitter(b *testing.B) { dc := state.NewUpdateCommitter() numberOfAccountUpdates := 10 - for range numberOfAccountUpdates { + for i := 0; i < numberOfAccountUpdates; i++ { err := dc.UpdateAccount(addr.ToCommon(), balance, nonce, randomHash) require.NoError(b, err) } numberOfSlotUpdates := 10 - for range numberOfSlotUpdates { + for i := 0; i < numberOfSlotUpdates; i++ { err := dc.UpdateSlot(addr.ToCommon(), randomHash, randomHash) require.NoError(b, err) } diff --git a/fvm/evm/evm_test.go b/fvm/evm/evm_test.go index 2fcc609843b..f7f89778bdd 100644 --- a/fvm/evm/evm_test.go +++ b/fvm/evm/evm_test.go @@ -55,7 +55,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -71,7 +71,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -160,7 +160,7 @@ func TestEVMRun(t *testing.T) { require.Equal(t, types.BalanceToBigInt(coinbaseBalance).Uint64(), txEventPayload.GasConsumed) // query the value - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -175,7 +175,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) innerTxBytes = testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), @@ -225,7 +225,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -246,7 +246,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) num := int64(42) callData := cadence.NewArray( @@ -327,7 +327,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -348,7 +348,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) num := int64(42) callData := cadence.NewArray( @@ -401,7 +401,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -422,7 +422,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) num := int64(42) callData := cadence.NewArray( @@ -475,7 +475,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -510,7 +510,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -576,7 +576,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -593,7 +593,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -657,7 +657,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -674,7 +674,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -738,7 +738,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -755,7 +755,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -819,7 +819,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -836,7 +836,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -899,7 +899,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -916,7 +916,7 @@ func TestEVMRun(t *testing.T) { `, sc.EVMContract.Address.HexWithPrefix(), types.ExecutionErrCodeExecutionReverted, - ) + )) num := int64(12) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, @@ -957,7 +957,7 @@ func TestEVMRun(t *testing.T) { snapshot = snapshot.Append(state) // query the value - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -967,7 +967,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) innerTxBytes = testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), @@ -1013,7 +1013,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -1028,7 +1028,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) num := int64(12) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, @@ -1094,7 +1094,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -1110,7 +1110,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -1180,7 +1180,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -1196,7 +1196,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -1267,7 +1267,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ @@ -1281,7 +1281,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -1341,7 +1341,7 @@ func TestEVMRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ @@ -1354,7 +1354,7 @@ func TestEVMRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -1457,7 +1457,7 @@ func TestEVMBatchRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - batchRunCode := fmt.Appendf(nil, + batchRunCode := []byte(fmt.Sprintf( ` import EVM from %s @@ -1475,7 +1475,7 @@ func TestEVMBatchRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -1484,7 +1484,7 @@ func TestEVMBatchRun(t *testing.T) { batchCount := 5 var storedValues []int64 txBytes := make([]cadence.Value, batchCount) - for i := range batchCount { + for i := 0; i < batchCount; i++ { num := int64(i) storedValues = append(storedValues, num) // prepare batch of transaction payloads @@ -1586,7 +1586,7 @@ func TestEVMBatchRun(t *testing.T) { ) // retrieve the values - retrieveCode := fmt.Appendf(nil, + retrieveCode := []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -1596,7 +1596,7 @@ func TestEVMBatchRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), @@ -1649,7 +1649,7 @@ func TestEVMBatchRun(t *testing.T) { // we make transaction at specific index invalid to fail const failedTxIndex = 3 sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - batchRunCode := fmt.Appendf(nil, + batchRunCode := []byte(fmt.Sprintf( ` import EVM from %s @@ -1673,12 +1673,12 @@ func TestEVMBatchRun(t *testing.T) { `, sc.EVMContract.Address.HexWithPrefix(), failedTxIndex, - ) + )) batchCount := 5 var num int64 txBytes := make([]cadence.Value, batchCount) - for i := range batchCount { + for i := 0; i < batchCount; i++ { num = int64(i) if i == failedTxIndex { @@ -1729,7 +1729,7 @@ func TestEVMBatchRun(t *testing.T) { snapshot = snapshot.Append(state) // retrieve the values - retrieveCode := fmt.Appendf(nil, + retrieveCode := []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -1739,7 +1739,7 @@ func TestEVMBatchRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), @@ -1790,7 +1790,7 @@ func TestEVMBatchRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - batchRunCode := fmt.Appendf(nil, + batchRunCode := []byte(fmt.Sprintf( ` import EVM from %s @@ -1817,12 +1817,12 @@ func TestEVMBatchRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) batchCount := 6 var num int64 txBytes := make([]cadence.Value, batchCount) - for i := range batchCount { + for i := 0; i < batchCount; i++ { gas := uint64(100_000) if i%2 == 0 { // fail with too low gas limit @@ -1876,7 +1876,7 @@ func TestEVMBatchRun(t *testing.T) { snapshot = snapshot.Append(state) // retrieve the values - retrieveCode := fmt.Appendf(nil, + retrieveCode := []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -1886,7 +1886,7 @@ func TestEVMBatchRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), @@ -1936,7 +1936,7 @@ func TestEVMBatchRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - batchRunCode := fmt.Appendf(nil, + batchRunCode := []byte(fmt.Sprintf( ` import EVM from %s @@ -1948,7 +1948,7 @@ func TestEVMBatchRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -2021,7 +2021,7 @@ func TestEVMBlockData(t *testing.T) { ) { // query the block timestamp - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -2031,7 +2031,7 @@ func TestEVMBlockData(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), @@ -2085,7 +2085,7 @@ func TestEVMAddressDeposit(t *testing.T) { testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -2106,7 +2106,7 @@ func TestEVMAddressDeposit(t *testing.T) { `, sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), - ) + )) addr := RandomAddress(t) @@ -2179,7 +2179,7 @@ func TestCOAAddressDeposit(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -2200,7 +2200,7 @@ func TestCOAAddressDeposit(t *testing.T) { sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), sc.FlowServiceAccount.Address.HexWithPrefix(), - ) + )) script := fvm.Script(code) @@ -2282,7 +2282,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -2312,7 +2312,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { `, sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), - ) + )) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). @@ -2349,7 +2349,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -2377,7 +2377,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { `, sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), - ) + )) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). @@ -2421,7 +2421,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -2449,7 +2449,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { `, sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), - ) + )) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). @@ -2493,7 +2493,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -2521,7 +2521,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { `, sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), - ) + )) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). @@ -2565,7 +2565,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -2593,7 +2593,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { `, sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), - ) + )) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). @@ -2630,7 +2630,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -2658,7 +2658,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { `, sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), - ) + )) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). @@ -2702,7 +2702,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -2740,7 +2740,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), sc.FlowServiceAccount.Address.HexWithPrefix(), - ) + )) addr := cadence.NewArray( unittest.BytesToCdcUInt8(RandomAddress(t).Bytes()), @@ -2770,7 +2770,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -2800,7 +2800,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), sc.FlowServiceAccount.Address.HexWithPrefix(), - ) + )) script := fvm.Script(code) @@ -2822,7 +2822,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -2850,7 +2850,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), sc.FlowServiceAccount.Address.HexWithPrefix(), - ) + )) script := fvm.Script(code). WithArguments(json.MustEncode( @@ -2887,7 +2887,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -2905,7 +2905,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) num := int64(42) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, @@ -2961,7 +2961,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { ) snapshot = snapshot.Append(state) - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s @@ -2989,7 +2989,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) data := json.MustEncode( cadence.NewArray( @@ -3035,7 +3035,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -3053,7 +3053,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) num := int64(42) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, @@ -3109,7 +3109,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { ) snapshot = snapshot.Append(state) - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s @@ -3138,7 +3138,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) signatureValue, err := cadence.NewString("retrieve()") require.NoError(t, err) @@ -3185,7 +3185,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -3210,7 +3210,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), sc.FlowServiceAccount.Address.HexWithPrefix(), - ) + )) script := fvm.Script(code). WithArguments(json.MustEncode( @@ -3247,7 +3247,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -3272,7 +3272,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), sc.FlowServiceAccount.Address.HexWithPrefix(), - ) + )) script := fvm.Script(code). WithArguments(json.MustEncode( @@ -3318,7 +3318,7 @@ func TestDryRun(t *testing.T) { vm fvm.VM, snapshot snapshot.SnapshotTree, ) *types.ResultSummary { - code := fmt.Appendf(nil, ` + code := []byte(fmt.Sprintf(` import EVM from %s access(all) @@ -3329,7 +3329,7 @@ func TestDryRun(t *testing.T) { ) }`, evmAddress, - ) + )) innerTxBytes, err := tx.MarshalBinary() require.NoError(t, err) @@ -3422,7 +3422,7 @@ func TestDryRun(t *testing.T) { require.Equal(t, types.StatusSuccessful, dryRunResult.Status) require.Greater(t, dryRunResult.GasConsumed, uint64(0)) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -3432,7 +3432,7 @@ func TestDryRun(t *testing.T) { } `, evmAddress, - ) + )) // Use the gas estimation from Evm.dryRun with some buffer gasLimit := dryRunResult.GasConsumed + gethParams.SstoreSentryGasEIP2200 @@ -3483,7 +3483,7 @@ func TestDryRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -3498,7 +3498,7 @@ func TestDryRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) num := int64(12) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, @@ -3551,7 +3551,7 @@ func TestDryRun(t *testing.T) { require.Equal(t, types.StatusSuccessful, dryRunResult.Status) require.Greater(t, dryRunResult.GasConsumed, uint64(0)) - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -3561,7 +3561,7 @@ func TestDryRun(t *testing.T) { } `, evmAddress, - ) + )) // Decrease nonce because we are Cadence using scripts, and not // transactions, which means that no state change is happening. @@ -3612,7 +3612,7 @@ func TestDryRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -3627,7 +3627,7 @@ func TestDryRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) num := int64(100) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, @@ -3681,7 +3681,7 @@ func TestDryRun(t *testing.T) { require.Equal(t, types.StatusSuccessful, dryRunResult.Status) require.Greater(t, dryRunResult.GasConsumed, uint64(0)) - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -3691,7 +3691,7 @@ func TestDryRun(t *testing.T) { } `, evmAddress, - ) + )) // use the gas estimation from Evm.dryRun with the necessary buffer gas gasLimit := dryRunResult.GasConsumed + gethParams.SstoreClearsScheduleRefundEIP3529 @@ -3760,7 +3760,7 @@ func TestDryRun(t *testing.T) { require.Greater(t, result.GasConsumed, uint64(0)) // query the value make sure it's not updated - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -3770,7 +3770,7 @@ func TestDryRun(t *testing.T) { } `, evmAddress, - ) + )) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), @@ -3870,7 +3870,7 @@ func TestDryRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -3885,7 +3885,7 @@ func TestDryRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) num := int64(100) evmTx := gethTypes.NewTransaction( @@ -3937,7 +3937,7 @@ func TestDryRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -3955,7 +3955,7 @@ func TestDryRun(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) num := int64(100) evmTx := gethTypes.NewTransaction( @@ -4057,7 +4057,7 @@ func TestDryRun(t *testing.T) { big.NewInt(0), ) - code := fmt.Appendf(nil, ` + code := []byte(fmt.Sprintf(` import EVM from %s transaction(dryTx: [UInt8], realTx: [UInt8], coinbaseBytes: [UInt8; 20]) { @@ -4072,7 +4072,7 @@ func TestDryRun(t *testing.T) { assert(runResult.status == EVM.Status.successful, message: "run after dry run failed") } } - `, sc.EVMContract.Address.HexWithPrefix()) + `, sc.EVMContract.Address.HexWithPrefix())) dryTxArg := cadence.NewArray( unittest.BytesToCdcUInt8(dryTxBytes), @@ -4120,7 +4120,7 @@ func TestDryCall(t *testing.T) { vm fvm.VM, snapshot snapshot.SnapshotTree, ) (*types.ResultSummary, *snapshot.ExecutionSnapshot) { - code := fmt.Appendf(nil, ` + code := []byte(fmt.Sprintf(` import EVM from %s access(all) @@ -4134,7 +4134,7 @@ func TestDryCall(t *testing.T) { ) }`, evmAddress, - ) + )) require.NotNil(t, tx.To()) to := tx.To().Hex() @@ -4235,7 +4235,7 @@ func TestDryCall(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -4250,7 +4250,7 @@ func TestDryCall(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) num := int64(42) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, @@ -4296,7 +4296,7 @@ func TestDryCall(t *testing.T) { ) snapshot = snapshot.Append(state) - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s @@ -4322,7 +4322,7 @@ func TestDryCall(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) data := json.MustEncode( cadence.NewArray( @@ -4387,7 +4387,7 @@ func TestDryCall(t *testing.T) { require.Greater(t, result.GasConsumed, uint64(0)) // query the value make sure it's not updated - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -4397,7 +4397,7 @@ func TestDryCall(t *testing.T) { } `, evmAddress, - ) + )) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), @@ -4490,7 +4490,7 @@ func TestDryCall(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -4510,7 +4510,7 @@ func TestDryCall(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) num := int64(100) evmTx := gethTypes.NewTransaction( @@ -4561,7 +4561,7 @@ func TestDryCall(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -4584,7 +4584,7 @@ func TestDryCall(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) num := int64(100) evmTx := gethTypes.NewTransaction( @@ -4671,7 +4671,7 @@ func TestDryCallCacheInvalidationAfterDeposit(t *testing.T) { oneFlow := new(big.Int).SetUint64(1e18) checkBalanceOneFlowData := testContract.MakeCallData(t, "checkBalance", addr.ToCommon(), oneFlow) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -4751,7 +4751,7 @@ func TestDryCallCacheInvalidationAfterDeposit(t *testing.T) { `, sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), - ) + )) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). @@ -4801,7 +4801,7 @@ func TestDryCallWithSigAndArgs(t *testing.T) { vm fvm.VM, snapshot snapshot.SnapshotTree, ) (*ResultDecoded, *snapshot.ExecutionSnapshot) { - code := fmt.Appendf(nil, ` + code := []byte(fmt.Sprintf(` import EVM from %s access(all) @@ -4817,7 +4817,7 @@ func TestDryCallWithSigAndArgs(t *testing.T) { ) }`, evmAddress, - ) + )) toAddress, err := cadence.NewString(to.Hex()) require.NoError(t, err) @@ -4936,7 +4936,7 @@ func TestDryCallWithSigAndArgs(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -4951,7 +4951,7 @@ func TestDryCallWithSigAndArgs(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) num := int64(42) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, @@ -4997,7 +4997,7 @@ func TestDryCallWithSigAndArgs(t *testing.T) { ) snapshot = snapshot.Append(state) - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s @@ -5024,7 +5024,7 @@ func TestDryCallWithSigAndArgs(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) signatureValue, err := cadence.NewString("retrieve()") require.NoError(t, err) @@ -5096,7 +5096,7 @@ func TestDryCallWithSigAndArgs(t *testing.T) { require.Greater(t, result.GasConsumed, uint64(0)) // query the value make sure it's not updated - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -5106,7 +5106,7 @@ func TestDryCallWithSigAndArgs(t *testing.T) { } `, evmAddress, - ) + )) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), @@ -5212,7 +5212,7 @@ func TestCadenceArch(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -5224,7 +5224,7 @@ func TestCadenceArch(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), testContract.MakeCallData(t, "verifyArchCallToFlowBlockHeight", ctx.BlockHeader.Height), @@ -5264,7 +5264,7 @@ func TestCadenceArch(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -5277,7 +5277,7 @@ func TestCadenceArch(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), testContract.MakeCallData(t, "verifyArchCallToRevertibleRandom"), @@ -5345,7 +5345,7 @@ func TestCadenceArch(t *testing.T) { ctx.EntropyProvider = testutil.EntropyProviderFixture(entropy) // fix the entropy txBody, err := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` import RandomBeaconHistory from %s transaction { @@ -5355,7 +5355,7 @@ func TestCadenceArch(t *testing.T) { ?? panic("Couldn't borrow RandomBeaconHistory.Heartbeat Resource") randomBeaconHistoryHeartbeat.heartbeat(randomSourceHistory: randomSourceHistory()) } - }`, sc.RandomBeaconHistory.Address.HexWithPrefix()), + }`, sc.RandomBeaconHistory.Address.HexWithPrefix())), ). SetPayer(sc.FlowServiceAccount.Address). AddAuthorizer(sc.FlowServiceAccount.Address). @@ -5368,7 +5368,7 @@ func TestCadenceArch(t *testing.T) { snapshot = snapshot.Append(s) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -5381,7 +5381,7 @@ func TestCadenceArch(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) // we fake progressing to new block height since random beacon does the check the // current height (2) is bigger than the height requested (1) @@ -5445,7 +5445,7 @@ func TestCadenceArch(t *testing.T) { ctx.BlockHeader = block1.ToHeader() txBody, err := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` import RandomBeaconHistory from %s transaction { @@ -5455,7 +5455,7 @@ func TestCadenceArch(t *testing.T) { ?? panic("Couldn't borrow RandomBeaconHistory.Heartbeat Resource") randomBeaconHistoryHeartbeat.heartbeat(randomSourceHistory: randomSourceHistory()) } - }`, sc.RandomBeaconHistory.Address.HexWithPrefix()), + }`, sc.RandomBeaconHistory.Address.HexWithPrefix())), ). SetPayer(sc.FlowServiceAccount.Address). AddAuthorizer(sc.FlowServiceAccount.Address). @@ -5470,7 +5470,7 @@ func TestCadenceArch(t *testing.T) { height = 1337 // invalid // we make sure the transaction fails, due to requested height being invalid - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -5481,7 +5481,7 @@ func TestCadenceArch(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) // we fake progressing to new block height since random beacon does the check the // current height (2) is bigger than the height requested (1) @@ -5576,7 +5576,7 @@ func TestCadenceArch(t *testing.T) { require.NoError(t, err) // create transaction for proof verification - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -5588,7 +5588,7 @@ func TestCadenceArch(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), testContract.MakeCallData(t, "verifyArchCallToVerifyCOAOwnershipProof", @@ -5686,7 +5686,7 @@ func TestCadenceArch(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -5756,7 +5756,7 @@ func TestCadenceArch(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). @@ -5813,7 +5813,7 @@ func TestCadenceArch(t *testing.T) { require.NoError(t, err) // create transaction for proof verification - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -5823,7 +5823,7 @@ func TestCadenceArch(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), testContract.MakeCallData(t, "verifyArchCallToVerifyCOAOwnershipProof", @@ -5887,7 +5887,7 @@ func TestNativePrecompiles(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -5903,7 +5903,7 @@ func TestNativePrecompiles(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -5975,7 +5975,7 @@ func TestEVMFileSystemContract(t *testing.T) { *snapshot.ExecutionSnapshot, fvm.ProcedureOutput, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -5987,7 +5987,7 @@ func TestEVMFileSystemContract(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -6156,7 +6156,7 @@ func TestEVMaddressFromString(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -6171,7 +6171,7 @@ func TestEVMaddressFromString(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) script := fvm.Script(code) _, output, err := vm.Run(ctx, script, snapshot) @@ -6190,7 +6190,7 @@ func TestEVMaddressFromString(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -6205,7 +6205,7 @@ func TestEVMaddressFromString(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) script := fvm.Script(code) _, output, err := vm.Run(ctx, script, snapshot) @@ -6224,7 +6224,7 @@ func TestEVMaddressFromString(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -6239,7 +6239,7 @@ func TestEVMaddressFromString(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) script := fvm.Script(code) _, output, err := vm.Run(ctx, script, snapshot) @@ -6263,7 +6263,7 @@ func TestEVMaddressFromString(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -6274,7 +6274,7 @@ func TestEVMaddressFromString(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) script := fvm.Script(code) _, output, err := vm.Run(ctx, script, snapshot) @@ -6298,7 +6298,7 @@ func TestEVMaddressFromString(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -6313,7 +6313,7 @@ func TestEVMaddressFromString(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) script := fvm.Script(code) _, output, err := vm.Run(ctx, script, snapshot) @@ -6337,7 +6337,7 @@ func TestEVMaddressFromString(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -6352,7 +6352,7 @@ func TestEVMaddressFromString(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) script := fvm.Script(code) _, output, err := vm.Run(ctx, script, snapshot) @@ -6374,7 +6374,7 @@ func TestEVMPauseFunctionality(t *testing.T) { chain := flow.Emulator.Chain() sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s @@ -6386,7 +6386,7 @@ func TestEVMPauseFunctionality(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). @@ -6415,7 +6415,7 @@ func TestEVMPauseFunctionality(t *testing.T) { snapshot = snapshot.Append(state) t.Run("testing EOA deposit when EVM is paused", func(t *testing.T) { - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -6436,7 +6436,7 @@ func TestEVMPauseFunctionality(t *testing.T) { `, sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), - ) + )) addr := RandomAddress(t) txBody, err = flow.NewTransactionBodyBuilder(). @@ -6461,7 +6461,7 @@ func TestEVMPauseFunctionality(t *testing.T) { }) t.Run("testing EVM.run when EVM is paused", func(t *testing.T) { - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s @@ -6477,7 +6477,7 @@ func TestEVMPauseFunctionality(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -6521,7 +6521,7 @@ func TestEVMPauseFunctionality(t *testing.T) { }) t.Run("testing EVM.batchRun when EVM is paused", func(t *testing.T) { - batchRunCode := fmt.Appendf(nil, + batchRunCode := []byte(fmt.Sprintf( ` import EVM from %s @@ -6539,7 +6539,7 @@ func TestEVMPauseFunctionality(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -6547,7 +6547,7 @@ func TestEVMPauseFunctionality(t *testing.T) { batchCount := 5 txBytes := make([]cadence.Value, batchCount) - for i := range batchCount { + for i := 0; i < batchCount; i++ { num := int64(i) // prepare batch of transaction payloads tx := testAccount.PrepareSignAndEncodeTx(t, @@ -6594,7 +6594,7 @@ func TestEVMPauseFunctionality(t *testing.T) { }) t.Run("testing EVM.createCadenceOwnedAccount when EVM is paused", func(t *testing.T) { - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s @@ -6611,7 +6611,7 @@ func TestEVMPauseFunctionality(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -6643,7 +6643,7 @@ func TestEVMPauseFunctionality(t *testing.T) { }) t.Run("testing CadenceOwnedAccount.deploy when EVM is paused", func(t *testing.T) { - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s @@ -6661,7 +6661,7 @@ func TestEVMPauseFunctionality(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) coinbaseAddr := types.Address{1, 2, 3} coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) @@ -6693,7 +6693,7 @@ func TestEVMPauseFunctionality(t *testing.T) { }) t.Run("testing CadenceOwnedAccount.call when EVM is paused", func(t *testing.T) { - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s @@ -6715,7 +6715,7 @@ func TestEVMPauseFunctionality(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) data := json.MustEncode( cadence.NewArray( @@ -6749,7 +6749,7 @@ func TestEVMPauseFunctionality(t *testing.T) { }) t.Run("testing CadenceOwnedAccount.deposit when EVM is paused", func(t *testing.T) { - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -6771,7 +6771,7 @@ func TestEVMPauseFunctionality(t *testing.T) { `, sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), - ) + )) txBody, err = flow.NewTransactionBodyBuilder(). SetScript(code). @@ -6792,7 +6792,7 @@ func TestEVMPauseFunctionality(t *testing.T) { }) t.Run("testing CadenceOwnedAccount.withdraw when EVM is paused", func(t *testing.T) { - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s import FlowToken from %s @@ -6811,7 +6811,7 @@ func TestEVMPauseFunctionality(t *testing.T) { `, sc.EVMContract.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), - ) + )) txBody, err = flow.NewTransactionBodyBuilder(). SetScript(code). @@ -6832,7 +6832,7 @@ func TestEVMPauseFunctionality(t *testing.T) { }) t.Run("testing CadenceOwnedAccount.callWithSigAndArgs when EVM is paused", func(t *testing.T) { - code = fmt.Appendf(nil, + code = []byte(fmt.Sprintf( ` import EVM from %s @@ -6856,7 +6856,7 @@ func TestEVMPauseFunctionality(t *testing.T) { } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) data := json.MustEncode( cadence.NewArray( @@ -6912,7 +6912,7 @@ func createAndFundFlowAccount( // fund the account with 100 tokens sc := systemcontracts.SystemContractsForChain(ctx.Chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import FlowToken from %s import FungibleToken from %s @@ -6937,7 +6937,7 @@ func createAndFundFlowAccount( sc.FlowToken.Address.HexWithPrefix(), sc.FungibleToken.Address.HexWithPrefix(), flowAccount.HexWithPrefix(), - ) + )) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). @@ -6976,7 +6976,7 @@ func setupCOA( sc := systemcontracts.SystemContractsForChain(ctx.Chain.ChainID()) // create a COA and store it under flow account - script := fmt.Appendf(nil, + script := []byte(fmt.Sprintf( ` import EVM from %s import FungibleToken from %s @@ -7009,7 +7009,7 @@ func setupCOA( sc.EVMContract.Address.HexWithPrefix(), sc.FungibleToken.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), - ) + )) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(script). @@ -7040,7 +7040,7 @@ func callEVMHeartBeat( ) (*events.BlockEventPayload, snapshot.SnapshotTree) { sc := systemcontracts.SystemContractsForChain(ctx.Chain.ChainID()) - heartBeatCode := fmt.Appendf(nil, + heartBeatCode := []byte(fmt.Sprintf( ` import EVM from %s transaction { @@ -7053,7 +7053,7 @@ func callEVMHeartBeat( } `, sc.EVMContract.Address.HexWithPrefix(), - ) + )) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(heartBeatCode). SetPayer(sc.FlowServiceAccount.Address). @@ -7082,14 +7082,14 @@ func getFlowAccountBalance( snap snapshot.SnapshotTree, address flow.Address, ) uint64 { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` access(all) fun main(): UFix64 { return getAccount(%s).balance } `, address.HexWithPrefix(), - ) + )) script := fvm.Script(code) _, output, err := vm.Run( @@ -7110,7 +7110,7 @@ func getEVMAccountBalance( snap snapshot.SnapshotTree, address types.Address, ) types.Balance { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -7121,7 +7121,7 @@ func getEVMAccountBalance( systemcontracts.SystemContractsForChain( ctx.Chain.ChainID(), ).EVMContract.Address.HexWithPrefix(), - ) + )) script := fvm.Script(code).WithArguments( json.MustEncode( @@ -7148,7 +7148,7 @@ func getEVMAccountNonce( snap snapshot.SnapshotTree, address types.Address, ) uint64 { - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import EVM from %s access(all) @@ -7159,7 +7159,7 @@ func getEVMAccountNonce( systemcontracts.SystemContractsForChain( ctx.Chain.ChainID(), ).EVMContract.Address.HexWithPrefix(), - ) + )) script := fvm.Script(code).WithArguments( json.MustEncode( diff --git a/fvm/evm/handler/handler_benchmark_test.go b/fvm/evm/handler/handler_benchmark_test.go index fa0c360426e..7fe9326014f 100644 --- a/fvm/evm/handler/handler_benchmark_test.go +++ b/fvm/evm/handler/handler_benchmark_test.go @@ -25,14 +25,14 @@ func benchmarkStorageGrowth(b *testing.B, accountCount, setupKittyCount, txPerBl accounts := make([]types.Account, accountCount) // setup several of accounts // note that trie growth is the function of number of accounts - for i := range accountCount { + for i := 0; i < accountCount; i++ { account := handler.AccountByAddress(handler.DeployCOA(uint64(i+1)), true) account.Deposit(types.NewFlowTokenVault(types.NewBalanceFromUFix64(100))) accounts[i] = account } backend.DropEvents() // mint kitties - for i := range setupKittyCount { + for i := 0; i < setupKittyCount; i++ { account := accounts[i%accountCount] matronId := testutils.RandomBigInt(1000) sireId := testutils.RandomBigInt(1000) diff --git a/fvm/evm/offchain/sync/replayer_test.go b/fvm/evm/offchain/sync/replayer_test.go index 9eebe0255c5..d92a12bb644 100644 --- a/fvm/evm/offchain/sync/replayer_test.go +++ b/fvm/evm/offchain/sync/replayer_test.go @@ -37,7 +37,7 @@ func TestChainReplay(t *testing.T) { totalTxCount := 0 // case: check sequential updates to a slot - for i := range 5 { + for i := 0; i < 5; i++ { tx := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), testContract.MakeCallData(t, "checkThenStore", big.NewInt(int64(i)), big.NewInt(int64(i+1))), @@ -53,7 +53,7 @@ func TestChainReplay(t *testing.T) { // case: add batch run BatchRun batchSize := 4 txBatch := make([][]byte, batchSize) - for i := range batchSize { + for i := 0; i < batchSize; i++ { txBatch[i] = testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), testContract.MakeCallData(t, "store", big.NewInt(int64(i))), diff --git a/fvm/evm/offchain/utils/verify.go b/fvm/evm/offchain/utils/verify.go index 7074c3d95e6..9335beb6230 100644 --- a/fvm/evm/offchain/utils/verify.go +++ b/fvm/evm/offchain/utils/verify.go @@ -5,7 +5,6 @@ import ( "context" "errors" "fmt" - "maps" "strings" "github.com/onflow/cadence" @@ -258,7 +257,9 @@ func VerifyRegisterUpdates(expectedUpdates map[flow.RegisterID]flow.RegisterValu delete(actualUpdates, k) } - maps.Copy(additionalUpdates, actualUpdates) + for k, v := range actualUpdates { + additionalUpdates[k] = v + } // Build a combined error message var errorMessage strings.Builder diff --git a/fvm/evm/testutils/backend.go b/fvm/evm/testutils/backend.go index 85c3c368111..428c74504e2 100644 --- a/fvm/evm/testutils/backend.go +++ b/fvm/evm/testutils/backend.go @@ -4,7 +4,6 @@ import ( "crypto/rand" "encoding/binary" "fmt" - maps0 "maps" "testing" gocommon "github.com/ethereum/go-ethereum/common" @@ -135,9 +134,13 @@ func GetSimpleValueStorePopulated( CloneFunc: func() *TestValueStore { // clone data newData := make(map[string][]byte) - maps0.Copy(newData, data) + for k, v := range data { + newData[k] = v + } newAllocator := make(map[string]uint64) - maps0.Copy(newAllocator, allocator) + for k, v := range allocator { + newAllocator[k] = v + } // clone allocator return GetSimpleValueStorePopulated(newData, newAllocator) }, @@ -145,9 +148,13 @@ func GetSimpleValueStorePopulated( DumpFunc: func() (map[string][]byte, map[string]uint64) { // clone data newData := make(map[string][]byte) - maps0.Copy(newData, data) + for k, v := range data { + newData[k] = v + } newAllocator := make(map[string]uint64) - maps0.Copy(newAllocator, allocator) + for k, v := range allocator { + newAllocator[k] = v + } return newData, newAllocator }, } diff --git a/fvm/evm/testutils/contract.go b/fvm/evm/testutils/contract.go index c5fdb862392..b73e5463417 100644 --- a/fvm/evm/testutils/contract.go +++ b/fvm/evm/testutils/contract.go @@ -22,7 +22,7 @@ type TestContract struct { DeployedAt types.Address } -func MakeCallData(t testing.TB, abiString string, name string, args ...any) []byte { +func MakeCallData(t testing.TB, abiString string, name string, args ...interface{}) []byte { abi, err := gethABI.JSON(strings.NewReader(abiString)) require.NoError(t, err) call, err := abi.Pack(name, args...) @@ -30,7 +30,7 @@ func MakeCallData(t testing.TB, abiString string, name string, args ...any) []by return call } -func (tc *TestContract) MakeCallData(t testing.TB, name string, args ...any) []byte { +func (tc *TestContract) MakeCallData(t testing.TB, name string, args ...interface{}) []byte { return MakeCallData(t, tc.ABI, name, args...) } diff --git a/fvm/evm/types/result_test.go b/fvm/evm/types/result_test.go index f68b46be0c7..dcdfaf71000 100644 --- a/fvm/evm/types/result_test.go +++ b/fvm/evm/types/result_test.go @@ -15,7 +15,7 @@ func TestLightReceipts(t *testing.T) { receipts := make(gethTypes.Receipts, resCount) reconstructedReceipts := make(gethTypes.Receipts, resCount) var totalGas uint64 - for i := range resCount { + for i := 0; i < resCount; i++ { res := testutils.RandomResultFixture(t) receipts[i] = res.Receipt() reconstructedReceipts[i] = res.LightReceipt().ToReceipt() diff --git a/fvm/executionParameters.go b/fvm/executionParameters.go index 84af7bf95d7..a23c8360804 100644 --- a/fvm/executionParameters.go +++ b/fvm/executionParameters.go @@ -3,7 +3,6 @@ package fvm import ( "context" "fmt" - "maps" "math" "github.com/rs/zerolog" @@ -254,7 +253,9 @@ func getExecutionWeights[KindType common.ComputationKind | common.MemoryKind]( // (or is not metered at all), the defaults can be changed and the network restarted // instead of trying to change the weights with a transaction. weights := make(map[KindType]uint64, len(defaultWeights)) - maps.Copy(weights, defaultWeights) + for k, v := range defaultWeights { + weights[k] = v + } for k, v := range weightsRaw { weights[KindType(k)] = v } diff --git a/fvm/executionParameters_test.go b/fvm/executionParameters_test.go index e36361e0212..10baf6e7147 100644 --- a/fvm/executionParameters_test.go +++ b/fvm/executionParameters_test.go @@ -2,7 +2,6 @@ package fvm_test import ( "fmt" - "maps" "testing" "github.com/stretchr/testify/mock" @@ -153,7 +152,9 @@ func runTests[T common.ComputationKind | common.MemoryKind]( expectedWeights := make(map[T]uint64) var existingWeightKey T var existingWeightValue uint64 - maps.Copy(expectedWeights, defaultWeights) + for k, v := range defaultWeights { + expectedWeights[k] = v + } // change one existing value for kind, u := range defaultWeights { existingWeightKey = kind diff --git a/fvm/fvm_bench_test.go b/fvm/fvm_bench_test.go index cedae9d7b9a..5cdfabeab08 100644 --- a/fvm/fvm_bench_test.go +++ b/fvm/fvm_bench_test.go @@ -500,7 +500,7 @@ func BenchmarkRuntimeTransaction(b *testing.B) { b.StopTimer() for i := 0; i < b.N; i++ { transactions := make([]*flow.TransactionBody, transactionsPerBlock) - for j := range transactionsPerBlock { + for j := 0; j < transactionsPerBlock; j++ { tx := txStringFunc(b, benchTransactionContext) btx := []byte(tx) @@ -739,21 +739,20 @@ func BenchmarkRuntimeTransaction(b *testing.B) { b, func(b *testing.B, context benchTransactionContext) string { coinbaseBytes := context.EvmTestAccount.Address().Bytes() - var transactionBody strings.Builder - transactionBody.WriteString(fmt.Sprintf(` + transactionBody := fmt.Sprintf(` let coinbaseBytesRaw = "%s".decodeHex() let coinbaseBytes: [UInt8; 20] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] for j, v in coinbaseBytesRaw { coinbaseBytes[j] = v } let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - `, hex.EncodeToString(coinbaseBytes))) + `, hex.EncodeToString(coinbaseBytes)) num := int64(12) gasLimit := uint64(100_000) // add 10 EVM transactions to the Flow transaction body - for i := range 100 { + for i := 0; i < 100; i++ { txBytes := context.EvmTestAccount.PrepareSignAndEncodeTx(b, context.EvmTestContract.DeployedAt.ToCommon(), context.EvmTestContract.MakeCallData(b, "store", big.NewInt(num)), @@ -762,27 +761,27 @@ func BenchmarkRuntimeTransaction(b *testing.B) { big.NewInt(0), ) if control { - transactionBody.WriteString(fmt.Sprintf(` + transactionBody += fmt.Sprintf(` let txBytes%[1]d = "%[2]s".decodeHex() EVM.run(tx: txBytes%[1]d, coinbase: coinbase) `, i, hex.EncodeToString(txBytes), - )) + ) } else { // don't run the EVM transaction but do the hex conversion - transactionBody.WriteString(fmt.Sprintf(` + transactionBody += fmt.Sprintf(` let txBytes%[1]d = "%[2]s".decodeHex() //EVM.run(tx: txBytes%[1]d, coinbase: coinbase) `, i, hex.EncodeToString(txBytes), - )) + ) } } - return templateTx(1, transactionBody.String()) + return templateTx(1, transactionBody) }, ) } @@ -864,7 +863,7 @@ func BenchRunNFTBatchTransfer(b *testing.B, setupReceiver(b, blockExecutor, &nftAccount, &batchNFTAccount, &accounts[2]) // Transfer NFTs - transferTx := fmt.Appendf(nil, TransferTxTemplate, accounts[0].Address.Hex(), accounts[1].Address.Hex()) + transferTx := []byte(fmt.Sprintf(TransferTxTemplate, accounts[0].Address.Hex(), accounts[1].Address.Hex())) encodedAddress, err := jsoncdc.Encode(cadence.Address(accounts[2].Address)) require.NoError(b, err) @@ -874,10 +873,10 @@ func BenchRunNFTBatchTransfer(b *testing.B, b.ResetTimer() // setup done, lets start measuring for i := 0; i < b.N; i++ { transactions := make([]*flow.TransactionBody, transactionsPerBlock) - for j := range transactionsPerBlock { + for j := 0; j < transactionsPerBlock; j++ { cadenceValues := make([]cadence.Value, testTokensPerTransaction) startTestToken := (i*transactionsPerBlock+j)*testTokensPerTransaction + 1 - for m := range testTokensPerTransaction { + for m := 0; m < testTokensPerTransaction; m++ { cadenceValues[m] = cadence.NewUInt64(uint64(startTestToken + m)) } @@ -931,7 +930,7 @@ func setupReceiver(b *testing.B, be TestBenchBlockExecutor, nftAccount, batchNFT } }` - setupTx := fmt.Appendf(nil, setUpReceiverTemplate, nftAccount.Address.Hex(), batchNFTAccount.Address.Hex()) + setupTx := []byte(fmt.Sprintf(setUpReceiverTemplate, nftAccount.Address.Hex(), batchNFTAccount.Address.Hex())) txBodyBuilder := flow.NewTransactionBodyBuilder(). SetScript(setupTx). @@ -969,7 +968,7 @@ func mintNFTs(b *testing.B, be TestBenchBlockExecutor, batchNFTAccount *TestBenc .batchDeposit(tokens: <-testTokens) } }` - mintScript := fmt.Appendf(nil, mintScriptTemplate, batchNFTAccount.Address.Hex(), size) + mintScript := []byte(fmt.Sprintf(mintScriptTemplate, batchNFTAccount.Address.Hex(), size)) txBodyBuilder := flow.NewTransactionBodyBuilder(). SetComputeLimit(999999). diff --git a/fvm/fvm_blockcontext_test.go b/fvm/fvm_blockcontext_test.go index 99a5b91bca7..4e320b2fe71 100644 --- a/fvm/fvm_blockcontext_test.go +++ b/fvm/fvm_blockcontext_test.go @@ -33,7 +33,7 @@ import ( func transferTokensTx(chain flow.Chain) *flow.TransactionBodyBuilder { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) return flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, + SetScript([]byte(fmt.Sprintf( ` // This transaction is a template for a transaction that // could be used by anyone to send tokens to another account @@ -75,7 +75,7 @@ func transferTokensTx(chain flow.Chain) *flow.TransactionBodyBuilder { }`, sc.FungibleToken.Address.Hex(), sc.FlowToken.Address.Hex(), - ), + )), ) } @@ -1075,7 +1075,7 @@ func TestBlockContext_ExecuteTransaction_StorageLimit(t *testing.T) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) // deposit more flow to increase capacity txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, + SetScript([]byte(fmt.Sprintf( ` import FungibleToken from %s import FlowToken from %s @@ -1097,7 +1097,7 @@ func TestBlockContext_ExecuteTransaction_StorageLimit(t *testing.T) { sc.FlowToken.Address.HexWithPrefix(), "Container", hex.EncodeToString([]byte(script)), - )). + ))). AddAuthorizer(accounts[0]). AddAuthorizer(chain.ServiceAddress()). SetProposalKey(chain.ServiceAddress(), 0, 0). @@ -1466,7 +1466,7 @@ func TestBlockContext_ExecuteScript(t *testing.T) { // Run test script - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import Test from 0x%s @@ -1475,7 +1475,7 @@ func TestBlockContext_ExecuteScript(t *testing.T) { } `, address.String(), - ) + )) _, output, err = vm.Run(ctx, fvm.Script(code), snapshotTree) require.NoError(t, err) @@ -1711,14 +1711,14 @@ func TestBlockContext_GetAccount(t *testing.T) { addressGen := chain.NewAddressGenerator() // skip the addresses of 4 reserved accounts - for range systemcontracts.LastSystemAccountIndex { + for i := 0; i < systemcontracts.LastSystemAccountIndex; i++ { _, err := addressGen.NextAddress() require.NoError(t, err) } // create a bunch of accounts accounts := make(map[flow.Address]crypto.PublicKey, count) - for range count { + for i := 0; i < count; i++ { address, key := createAccount() expectedAddress, err := addressGen.NextAddress() require.NoError(t, err) @@ -1818,7 +1818,7 @@ func TestBlockContext_Random(t *testing.T) { ` getScriptRandoms := func(t *testing.T, codeSalt int, arg int) [2]uint64 { - script := fvm.Script(fmt.Appendf(nil, scriptCode, codeSalt)). + script := fvm.Script([]byte(fmt.Sprintf(scriptCode, codeSalt))). WithArguments(jsoncdc.MustEncode(cadence.Int8(arg))) _, output, err := vm.Run(ctx, script, testutil.RootBootstrappedLedger(vm, ctx)) @@ -1912,7 +1912,7 @@ func TestBlockContext_ExecuteTransaction_FailingTransactions(t *testing.T) { ) uint64 { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import FungibleToken from 0x%s import FlowToken from 0x%s @@ -1927,7 +1927,7 @@ func TestBlockContext_ExecuteTransaction_FailingTransactions(t *testing.T) { `, sc.FungibleToken.Address.Hex(), sc.FlowToken.Address.Hex(), - ) + )) script := fvm.Script(code).WithArguments( jsoncdc.MustEncode(cadence.NewAddress(address)), ) diff --git a/fvm/fvm_signature_test.go b/fvm/fvm_signature_test.go index 62234f9ae51..8712f972279 100644 --- a/fvm/fvm_signature_test.go +++ b/fvm/fvm_signature_test.go @@ -87,8 +87,8 @@ func TestKeyListSignature(t *testing.T) { testForHash := func(signatureAlgorithm signatureAlgorithm, hashAlgorithm hashAlgorithm) { - code := - fmt.Appendf(nil, + code := []byte( + fmt.Sprintf( ` import Crypto @@ -135,7 +135,8 @@ func TestKeyListSignature(t *testing.T) { signatureAlgorithm.name, hashAlgorithm.name, tag, - ) + ), + ) t.Run(fmt.Sprintf("%s %s", signatureAlgorithm.name, hashAlgorithm.name), func(t *testing.T) { @@ -406,8 +407,9 @@ func TestBLSMultiSignature(t *testing.T) { ) { code := func(signatureAlgorithm signatureAlgorithm) []byte { - return fmt.Appendf(nil, - ` + return []byte( + fmt.Sprintf( + ` import Crypto access(all) @@ -422,7 +424,8 @@ func TestBLSMultiSignature(t *testing.T) { return p.verifyPoP(proof) } `, - signatureAlgorithm.name, + signatureAlgorithm.name, + ), ) } @@ -537,7 +540,7 @@ func TestBLSMultiSignature(t *testing.T) { sigs := make([]crypto.Signature, 0, numSigs) kmac := msig.NewBLSHasher("test tag") - for range numSigs { + for i := 0; i < numSigs; i++ { sk := randomSK(t, BLSSignatureAlgorithm) // a valid BLS signature s, err := sk.Sign(input, kmac) @@ -627,8 +630,9 @@ func TestBLSMultiSignature(t *testing.T) { ) { code := func(signatureAlgorithm signatureAlgorithm) []byte { - return fmt.Appendf(nil, - ` + return []byte( + fmt.Sprintf( + ` import Crypto access(all) fun main( @@ -644,7 +648,8 @@ func TestBLSMultiSignature(t *testing.T) { return BLS.aggregatePublicKeys(pks)!.publicKey } `, - signatureAlgorithm.name, + signatureAlgorithm.name, + ), ) } @@ -654,7 +659,7 @@ func TestBLSMultiSignature(t *testing.T) { t.Run("valid BLS keys", func(t *testing.T) { publicKeys := make([]cadence.Value, 0, pkNum) - for range pkNum { + for i := 0; i < pkNum; i++ { sk := randomSK(t, BLSSignatureAlgorithm) pk := sk.PublicKey() pks = append(pks, pk) @@ -684,7 +689,7 @@ func TestBLSMultiSignature(t *testing.T) { t.Run("non BLS keys/"+signatureAlgorithm.name, func(t *testing.T) { publicKeys := make([]cadence.Value, 0, pkNum) - for range pkNum { + for i := 0; i < pkNum; i++ { sk := randomSK(t, signatureAlgorithm) pk := sk.PublicKey() pks = append(pks, pk) @@ -771,7 +776,7 @@ func TestBLSMultiSignature(t *testing.T) { signatures := make([]cadence.Value, 0, num) kmac := msig.NewBLSHasher(string(tag)) - for range num { + for i := 0; i < num; i++ { sk := randomSK(t, BLSSignatureAlgorithm) pk := sk.PublicKey() publicKeys = append( diff --git a/fvm/fvm_test.go b/fvm/fvm_test.go index 18bae5aba16..a4e0a2f1bf7 100644 --- a/fvm/fvm_test.go +++ b/fvm/fvm_test.go @@ -6,7 +6,6 @@ import ( "encoding/binary" "encoding/hex" "fmt" - "maps" "math" "strconv" "strings" @@ -194,7 +193,7 @@ func TestHashing(t *testing.T) { snapshotTree := testutil.RootBootstrappedLedger(vm, ctx) hashScript := func(hashName string) []byte { - return fmt.Appendf(nil, + return []byte(fmt.Sprintf( ` import Crypto @@ -202,17 +201,17 @@ func TestHashing(t *testing.T) { fun main(data: [UInt8]): [UInt8] { return Crypto.hash(data, algorithm: HashAlgorithm.%s) } - `, hashName) + `, hashName)) } hashWithTagScript := func(hashName string) []byte { - return fmt.Appendf(nil, + return []byte(fmt.Sprintf( ` import Crypto access(all) fun main(data: [UInt8], tag: String): [UInt8] { return Crypto.hashWithTag(data, tag: tag, algorithm: HashAlgorithm.%s) } - `, hashName) + `, hashName)) } data := []byte("some random message") @@ -527,7 +526,7 @@ func TestEventLimits(t *testing.T) { fvm.WithEventCollectionSizeLimit(2)) txBody, err := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, deployingContractScriptTemplate, hex.EncodeToString([]byte(testContract)))). + SetScript([]byte(fmt.Sprintf(deployingContractScriptTemplate, hex.EncodeToString([]byte(testContract))))). SetPayer(chain.ServiceAddress()). AddAuthorizer(chain.ServiceAddress()). Build() @@ -543,14 +542,14 @@ func TestEventLimits(t *testing.T) { snapshotTree = snapshotTree.Append(executionSnapshot) txBody, err = flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` import TestContract from 0x%s transaction { prepare(acct: &Account) {} execute { TestContract.EmitEvent() } - }`, chain.ServiceAddress())). + }`, chain.ServiceAddress()))). SetPayer(chain.ServiceAddress()). AddAuthorizer(chain.ServiceAddress()). Build() @@ -636,7 +635,7 @@ func TestTransactionFeeDeduction(t *testing.T) { getBalance := func(vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree, address flow.Address) uint64 { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := fmt.Appendf(nil, + code := []byte(fmt.Sprintf( ` import FungibleToken from 0x%s import FlowToken from 0x%s @@ -651,7 +650,7 @@ func TestTransactionFeeDeduction(t *testing.T) { `, sc.FungibleToken.Address.Hex(), sc.FlowToken.Address.Hex(), - ) + )) script := fvm.Script(code).WithArguments( jsoncdc.MustEncode(cadence.NewAddress(address)), ) @@ -1168,7 +1167,9 @@ func TestSettingExecutionWeights(t *testing.T) { )) memoryWeights := make(map[common.MemoryKind]uint64) - maps.Copy(memoryWeights, meter.DefaultMemoryWeights) + for k, v := range meter.DefaultMemoryWeights { + memoryWeights[k] = v + } const highWeight = 20_000_000_000 memoryWeights[common.MemoryKindIntegerExpression] = highWeight @@ -1276,7 +1277,9 @@ func TestSettingExecutionWeights(t *testing.T) { )) memoryWeights = make(map[common.MemoryKind]uint64) - maps.Copy(memoryWeights, meter.DefaultMemoryWeights) + for k, v := range meter.DefaultMemoryWeights { + memoryWeights[k] = v + } memoryWeights[common.MemoryKindBreakStatement] = 1_000_000 t.Run("transaction should fail with low memory limit (set in the state)", newVMTest(). withChain(chain). @@ -1506,9 +1509,9 @@ func TestSettingExecutionWeights(t *testing.T) { executionEffortNeededToCheckStorage := uint64(1) maxExecutionEffort := uint64(997) txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` transaction() {prepare(signer: &Account){var i=0; while i < %d {i = i +1 } } execute{}} - `, loops)). + `, loops))). SetProposalKey(chain.ServiceAddress(), 0, 0). AddAuthorizer(chain.ServiceAddress()). SetPayer(chain.ServiceAddress()). @@ -1535,9 +1538,9 @@ func TestSettingExecutionWeights(t *testing.T) { // increasing the number of loops should fail the transaction. loops = loops + 1 txBodyBuilder = flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` transaction() {prepare(signer: &Account){var i=0; while i < %d {i = i +1 } } execute{}} - `, loops)). + `, loops))). SetProposalKey(chain.ServiceAddress(), 0, 1). AddAuthorizer(chain.ServiceAddress()). SetPayer(chain.ServiceAddress()). @@ -1621,7 +1624,7 @@ func TestSettingExecutionWeights(t *testing.T) { // create a transaction without loops so only the looping in the storage check is counted. txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` import FungibleToken from 0x%s import FlowToken from 0x%s @@ -1669,7 +1672,7 @@ func TestSettingExecutionWeights(t *testing.T) { accounts[2].HexWithPrefix(), accounts[3].HexWithPrefix(), accounts[4].HexWithPrefix(), - )). + ))). SetProposalKey(chain.ServiceAddress(), 0, 0). AddAuthorizer(chain.ServiceAddress()). SetPayer(chain.ServiceAddress()) @@ -1822,8 +1825,8 @@ func TestEnforcingComputationLimit(t *testing.T) { t.Run(test.name, func(t *testing.T) { ctx := fvm.NewContext(chain, fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false)) - script := - fmt.Appendf(nil, + script := []byte( + fmt.Sprintf( ` transaction { prepare() { @@ -1832,7 +1835,8 @@ func TestEnforcingComputationLimit(t *testing.T) { } `, test.code, - ) + ), + ) txBodyBuilder := flow.NewTransactionBodyBuilder(). SetScript(script). @@ -1937,7 +1941,7 @@ func TestStorageCapacity(t *testing.T) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) txBody, err := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, + SetScript([]byte(fmt.Sprintf( ` import FungibleToken from 0x%s import FlowToken from 0x%s @@ -1963,7 +1967,7 @@ func TestStorageCapacity(t *testing.T) { }`, sc.FungibleToken.Address.Hex(), sc.FlowToken.Address.Hex(), - )). + ))). SetPayer(signer). AddArgument(jsoncdc.MustEncode(cadence.NewAddress(target))). AddAuthorizer(signer). @@ -2008,11 +2012,12 @@ func TestScriptContractMutationsFailure(t *testing.T) { contract := "access(all) contract Foo {}" - script := fvm.Script(fmt.Appendf(nil, ` + script := fvm.Script([]byte(fmt.Sprintf(` access(all) fun main(account: Address) { let acc = getAuthAccount(account) acc.contracts.add(name: "Foo", code: "%s".decodeHex()) - }`, hex.EncodeToString([]byte(contract)))).WithArguments( + }`, hex.EncodeToString([]byte(contract))), + )).WithArguments( jsoncdc.MustEncode(address), ) @@ -2049,13 +2054,13 @@ func TestScriptContractMutationsFailure(t *testing.T) { contract := "access(all) contract Foo {}" - txBodyBuilder := flow.NewTransactionBodyBuilder().SetScript(fmt.Appendf(nil, ` + txBodyBuilder := flow.NewTransactionBodyBuilder().SetScript([]byte(fmt.Sprintf(` transaction { prepare(signer: auth(AddContract) &Account, service: &Account) { signer.contracts.add(name: "Foo", code: "%s".decodeHex()) } } - `, hex.EncodeToString([]byte(contract)))). + `, hex.EncodeToString([]byte(contract))))). AddAuthorizer(account). AddAuthorizer(chain.ServiceAddress()). SetPayer(chain.ServiceAddress()). @@ -2122,13 +2127,13 @@ func TestScriptContractMutationsFailure(t *testing.T) { contract := "access(all) contract Foo {}" - txBodyBuilder := flow.NewTransactionBodyBuilder().SetScript(fmt.Appendf(nil, ` + txBodyBuilder := flow.NewTransactionBodyBuilder().SetScript([]byte(fmt.Sprintf(` transaction { prepare(signer: auth(AddContract) &Account, service: &Account) { signer.contracts.add(name: "Foo", code: "%s".decodeHex()) } } - `, hex.EncodeToString([]byte(contract)))). + `, hex.EncodeToString([]byte(contract))))). AddAuthorizer(account). AddAuthorizer(chain.ServiceAddress()). SetPayer(chain.ServiceAddress()). @@ -2152,12 +2157,12 @@ func TestScriptContractMutationsFailure(t *testing.T) { snapshotTree = snapshotTree.Append(executionSnapshot) - script := fvm.Script(fmt.Appendf(nil, ` + script := fvm.Script([]byte(fmt.Sprintf(` access(all) fun main(account: Address) { let acc = getAuthAccount(account) let n = acc.contracts.names[0] acc.contracts.update(name: n, code: "%s".decodeHex()) - }`, hex.EncodeToString([]byte(contract)))).WithArguments( + }`, hex.EncodeToString([]byte(contract))))).WithArguments( jsoncdc.MustEncode(address), ) @@ -2768,7 +2773,7 @@ func TestStorageIterationWithBrokenValues(t *testing.T) { )) // Store values - runTransaction(fmt.Appendf(nil, + runTransaction([]byte(fmt.Sprintf( ` import D from %s import C from %s @@ -2801,7 +2806,7 @@ func TestStorageIterationWithBrokenValues(t *testing.T) { accounts[0].HexWithPrefix(), accounts[0].HexWithPrefix(), accounts[0].HexWithPrefix(), - )) + ))) // Update `A`, such that `B`, `C` and `D` are now broken. runTransaction(runtime_utils.UpdateTransaction( @@ -3001,7 +3006,7 @@ func TestFlowCallbackScheduler(t *testing.T) { require.NoError(t, err) // Verify that the capability was stored in the executor account - script := fvm.Script(fmt.Appendf(nil, ` + script := fvm.Script([]byte(fmt.Sprintf(` import FlowTransactionScheduler from %s access(all) fun main(executorAddress: Address): Bool { @@ -3010,7 +3015,7 @@ func TestFlowCallbackScheduler(t *testing.T) { from: /storage/executeScheduledTransactionsCapability ) } - `, sc.FlowTransactionScheduler.Address.HexWithPrefix())) + `, sc.FlowTransactionScheduler.Address.HexWithPrefix()))) executorAddressArg, err := jsoncdc.Encode(cadence.Address(sc.ScheduledTransactionExecutor.Address)) require.NoError(t, err) @@ -3020,12 +3025,12 @@ func TestFlowCallbackScheduler(t *testing.T) { require.NoError(t, output.Err) require.Equal(t, cadence.Bool(true), output.Value) - script = fvm.Script(fmt.Appendf(nil, ` + script = fvm.Script([]byte(fmt.Sprintf(` import FlowTransactionScheduler from %s access(all) fun main(): FlowTransactionScheduler.Status? { return FlowTransactionScheduler.getStatus(id: 1) } - `, sc.FlowTransactionScheduler.Address.HexWithPrefix())) + `, sc.FlowTransactionScheduler.Address.HexWithPrefix()))) _, output, err = vm.Run(ctx, script, snapshotTree) require.NoError(t, err) @@ -3033,12 +3038,12 @@ func TestFlowCallbackScheduler(t *testing.T) { require.NotNil(t, output.Value) require.Equal(t, output.Value, cadence.NewOptional(nil)) - script = fvm.Script(fmt.Appendf(nil, ` + script = fvm.Script([]byte(fmt.Sprintf(` import FlowTransactionScheduler from %s access(all) fun main(): UInt64 { return FlowTransactionScheduler.getSlotAvailableEffort(timestamp: 1.0, priority: FlowTransactionScheduler.Priority.High) } - `, sc.FlowTransactionScheduler.Address.HexWithPrefix())) + `, sc.FlowTransactionScheduler.Address.HexWithPrefix()))) const maxEffortAvailable = 15_000 // FLIP 330 _, output, err = vm.Run(ctx, script, snapshotTree) @@ -3091,7 +3096,7 @@ func TestEVM(t *testing.T) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` import EVM from %s transaction(bytes: [UInt8; 20]) { @@ -3100,7 +3105,7 @@ func TestEVM(t *testing.T) { log(addr) } } - `, sc.EVMContract.Address.HexWithPrefix())). + `, sc.EVMContract.Address.HexWithPrefix()))). SetProposalKey(chain.ServiceAddress(), 0, 0). SetPayer(chain.ServiceAddress()). AddArgument(encodedArg) @@ -3142,7 +3147,7 @@ func TestEVM(t *testing.T) { snapshotTree snapshot.SnapshotTree, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - script := fvm.Script(fmt.Appendf(nil, ` + script := fvm.Script([]byte(fmt.Sprintf(` import EVM from %s access(all) fun main() { @@ -3153,7 +3158,7 @@ func TestEVM(t *testing.T) { destroy acc.withdraw(balance: bal) destroy acc } - `, sc.EVMContract.Address.HexWithPrefix())) + `, sc.EVMContract.Address.HexWithPrefix()))) _, output, err := vm.Run(ctx, script, snapshotTree) @@ -3208,14 +3213,14 @@ func TestEVM(t *testing.T) { return snapshotTree.Get(id) }) - script := fvm.Script(fmt.Appendf(nil, ` + script := fvm.Script([]byte(fmt.Sprintf(` import EVM from %s access(all) fun main() { destroy <- EVM.createCadenceOwnedAccount() } - `, sc.EVMContract.Address.HexWithPrefix())) + `, sc.EVMContract.Address.HexWithPrefix()))) _, output, err := vm.Run(ctx, script, errStorage) @@ -3243,7 +3248,7 @@ func TestEVM(t *testing.T) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` import FungibleToken from %s import FlowToken from %s import EVM from %s @@ -3270,7 +3275,7 @@ func TestEVM(t *testing.T) { sc.FungibleToken.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), sc.FlowServiceAccount.Address.HexWithPrefix(), // TODO this should be sc.EVM.Address not found there??? - )). + ))). SetProposalKey(chain.ServiceAddress(), 0, 0). AddAuthorizer(chain.ServiceAddress()). SetPayer(chain.ServiceAddress()) @@ -3752,7 +3757,7 @@ func TestVMBridge(t *testing.T) { // Mint an NFT txBodyBuilder = flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, + SetScript([]byte(fmt.Sprintf( ` import NonFungibleToken from 0x%s import ExampleNFT from 0x%s @@ -3799,7 +3804,7 @@ func TestVMBridge(t *testing.T) { } `, env.NonFungibleTokenAddress, accounts[0].String(), env.NonFungibleTokenAddress, env.FungibleTokenAddress, accounts[0].String(), - )).AddAuthorizer(accounts[0]) + ))).AddAuthorizer(accounts[0]) err = testutil.SignTransaction(txBodyBuilder, accounts[0], privateKey, 3) require.NoError(t, err) @@ -4070,7 +4075,7 @@ func TestCrypto(t *testing.T) { fvm.WithCadenceLogging(true), ) - script := fmt.Appendf(nil, + script := []byte(fmt.Sprintf( ` %s @@ -4125,7 +4130,7 @@ func TestCrypto(t *testing.T) { } `, importDecl, - ) + )) accountKeys := test.AccountKeyGenerator() @@ -4588,7 +4593,7 @@ func TestFlowTokenChangesInspector(t *testing.T) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, ` + SetScript([]byte(fmt.Sprintf(` import FungibleToken from %s import FlowToken from %s import EVM from %s @@ -4614,7 +4619,7 @@ func TestFlowTokenChangesInspector(t *testing.T) { sc.FungibleToken.Address.HexWithPrefix(), sc.FlowToken.Address.HexWithPrefix(), sc.FlowServiceAccount.Address.HexWithPrefix(), - )). + ))). SetProposalKey(chain.ServiceAddress(), 0, 0). AddAuthorizer(chain.ServiceAddress()). SetPayer(chain.ServiceAddress()) diff --git a/fvm/inspection/token_changes.go b/fvm/inspection/token_changes.go index 44cf0e492c5..78112db40aa 100644 --- a/fvm/inspection/token_changes.go +++ b/fvm/inspection/token_changes.go @@ -2,7 +2,6 @@ package inspection import ( "fmt" - "maps" "math" "runtime/debug" "sync" @@ -56,7 +55,9 @@ func (td *TokenChanges) Name() string { func (td *TokenChanges) SetSearchedTokens(searchedTokens TokenChangesSearchTokens) { // copy the map in case the user tries to modify the map st := make(map[string]SearchToken, len(searchedTokens)) - maps.Copy(st, searchedTokens) + for k, v := range searchedTokens { + st[k] = v + } td.searchedTokensMu.Lock() defer td.searchedTokensMu.Unlock() td.searchedTokens = st @@ -162,7 +163,9 @@ func (td *TokenChanges) getTokenDiff( for a := range addresses { // Copy beforeTokens before calling diffAccountTokens, which mutates the before map beforeTokens := make(accountTokens, len(before[a])) - maps.Copy(beforeTokens, before[a]) + for k, v := range before[a] { + beforeTokens[k] = v + } afterTokens := after[a] diff := diffAccountTokens(before[a], after[a]) if len(diff) == 0 { diff --git a/fvm/storage/derived/table.go b/fvm/storage/derived/table.go index 74254eaea91..2c9a70631ea 100644 --- a/fvm/storage/derived/table.go +++ b/fvm/storage/derived/table.go @@ -2,7 +2,6 @@ package derived import ( "fmt" - "maps" "sync" "github.com/hashicorp/go-multierror" @@ -142,7 +141,9 @@ func (table *DerivedDataTable[TKey, TVal]) EntriesForTestingOnly() map[TKey]*inv entries := make( map[TKey]*invalidatableEntry[TVal], len(table.items)) - maps.Copy(entries, table.items) + for key, entry := range table.items { + entries[key] = entry + } return entries } diff --git a/fvm/storage/derived/table_test.go b/fvm/storage/derived/table_test.go index ae78e32eba8..1089a03f4ad 100644 --- a/fvm/storage/derived/table_test.go +++ b/fvm/storage/derived/table_test.go @@ -736,7 +736,7 @@ func TestDerivedDataTableCommitSnapshotReadDontAdvanceTime(t *testing.T) { err = testSetupTxn.Commit() require.NoError(t, err) - for range 10 { + for i := 0; i < 10; i++ { txn := block.NewSnapshotReadTableTransaction() err = txn.Commit() diff --git a/fvm/storage/snapshot/snapshot_tree.go b/fvm/storage/snapshot/snapshot_tree.go index 25ed4ecaa0b..cc57843b3ae 100644 --- a/fvm/storage/snapshot/snapshot_tree.go +++ b/fvm/storage/snapshot/snapshot_tree.go @@ -1,8 +1,6 @@ package snapshot import ( - "maps" - "github.com/onflow/flow-go/model/flow" ) @@ -45,7 +43,9 @@ func (tree SnapshotTree) Append( mergedSet := make(map[flow.RegisterID]flow.RegisterValue, size) for _, set := range compactedLog { - maps.Copy(mergedSet, set) + for id, value := range set { + mergedSet[id] = value + } } compactedLog = UpdateLog{mergedSet} diff --git a/fvm/storage/snapshot/snapshot_tree_test.go b/fvm/storage/snapshot/snapshot_tree_test.go index 17c3120e76d..4a8479405a9 100644 --- a/fvm/storage/snapshot/snapshot_tree_test.go +++ b/fvm/storage/snapshot/snapshot_tree_test.go @@ -91,7 +91,7 @@ func TestSnapshotTree(t *testing.T) { compactedTree := tree3 numExtraUpdates := 2*compactThreshold + 1 for i := range numExtraUpdates { - value := fmt.Appendf(nil, "compacted %d", i) + value := []byte(fmt.Sprintf("compacted %d", i)) expectedCompacted[id3] = value compactedTree = compactedTree.Append( &ExecutionSnapshot{ diff --git a/fvm/storage/state/spock_state_test.go b/fvm/storage/state/spock_state_test.go index d142f42ad2c..bbf9b6ccb07 100644 --- a/fvm/storage/state/spock_state_test.go +++ b/fvm/storage/state/spock_state_test.go @@ -325,7 +325,7 @@ func TestSpockStateRandomOps(t *testing.T) { nil, // control experiment } - for range 500 { + for i := 0; i < 500; i++ { roll, err := rand.Uintn(4) require.NoError(t, err) @@ -357,7 +357,7 @@ func TestSpockStateRandomOps(t *testing.T) { func(t *testing.T, state *spockState) { err := state.Set( flow.NewRegisterID(flow.EmptyAddress, fmt.Sprintf("%d", id)), - fmt.Appendf(nil, "%d", value)) + []byte(fmt.Sprintf("%d", value))) require.NoError(t, err) })) case uint(2): @@ -371,7 +371,7 @@ func TestSpockStateRandomOps(t *testing.T) { func(t *testing.T, state *spockState) { err := state.Merge( &snapshot.ExecutionSnapshot{ - SpockSecret: fmt.Appendf(nil, "%d", spock), + SpockSecret: []byte(fmt.Sprintf("%d", spock)), }) require.NoError(t, err) })) diff --git a/fvm/storage/state/storage_state.go b/fvm/storage/state/storage_state.go index cc8a70ac181..da5ad4a9b08 100644 --- a/fvm/storage/state/storage_state.go +++ b/fvm/storage/state/storage_state.go @@ -2,7 +2,6 @@ package state import ( "fmt" - "maps" "github.com/onflow/flow-go/fvm/storage/snapshot" "github.com/onflow/flow-go/model/flow" @@ -45,7 +44,9 @@ func (state *storageState) Merge(snapshot *snapshot.ExecutionSnapshot) error { state.readSet[id] = struct{}{} } - maps.Copy(state.writeSet, snapshot.WriteSet) + for id, value := range snapshot.WriteSet { + state.writeSet[id] = value + } return nil } diff --git a/fvm/storage/state/transaction_state_test.go b/fvm/storage/state/transaction_state_test.go index ad7a4fba44b..f8b18b5d186 100644 --- a/fvm/storage/state/transaction_state_test.go +++ b/fvm/storage/state/transaction_state_test.go @@ -288,7 +288,7 @@ func TestRestartNestedTransaction(t *testing.T) { key := flow.NewRegisterID(unittest.RandomAddressFixture(), "key") val := createByteArray(2) - for range 10 { + for i := 0; i < 10; i++ { _, err := txn.BeginNestedTransaction() require.NoError(t, err) @@ -301,7 +301,7 @@ func TestRestartNestedTransaction(t *testing.T) { Name: "loc", } - for range 5 { + for i := 0; i < 5; i++ { _, err := txn.BeginParseRestrictedNestedTransaction(loc) require.NoError(t, err) @@ -344,7 +344,7 @@ func TestRestartNestedTransactionWithInvalidId(t *testing.T) { require.NoError(t, err) var otherId state.NestedTransactionId - for range 10 { + for i := 0; i < 10; i++ { otherId, err = txn.BeginNestedTransaction() require.NoError(t, err) diff --git a/fvm/systemcontracts/system_contracts_test.go b/fvm/systemcontracts/system_contracts_test.go index 34ed9e78040..82333577b9c 100644 --- a/fvm/systemcontracts/system_contracts_test.go +++ b/fvm/systemcontracts/system_contracts_test.go @@ -45,7 +45,7 @@ func TestServiceEvents(t *testing.T) { func TestServiceEventAll_Consistency(t *testing.T) { chains := flow.AllChainIDs() - fields := reflect.TypeFor[ServiceEvents]().NumField() + fields := reflect.TypeOf(ServiceEvents{}).NumField() for _, chain := range chains { events := ServiceEventsForChain(chain) diff --git a/fvm/transactionVerifier.go b/fvm/transactionVerifier.go index 47b39877466..897efa615cc 100644 --- a/fvm/transactionVerifier.go +++ b/fvm/transactionVerifier.go @@ -333,7 +333,10 @@ func (v *TransactionVerifier) verifySignatures( toVerifyChan := make(chan *signatureContinuation, len(signatures)) verifiedChan := make(chan *signatureContinuation, len(signatures)) - verificationConcurrency := min(len(signatures), v.VerificationConcurrency) + verificationConcurrency := v.VerificationConcurrency + if len(signatures) < verificationConcurrency { + verificationConcurrency = len(signatures) + } ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -341,7 +344,7 @@ func (v *TransactionVerifier) verifySignatures( wg := sync.WaitGroup{} wg.Add(verificationConcurrency) - for range verificationConcurrency { + for i := 0; i < verificationConcurrency; i++ { go func() { defer wg.Done() diff --git a/go.mod b/go.mod index 65671b75265..eaeb5c05cc5 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/onflow/flow-go -go 1.26.0 +go 1.25.1 require ( cloud.google.com/go/compute/metadata v0.9.0 @@ -48,7 +48,7 @@ require ( github.com/multiformats/go-multihash v0.2.3 github.com/onflow/atree v0.16.0 github.com/onflow/cadence v1.10.3 - github.com/onflow/crypto v0.26.0 + github.com/onflow/crypto v0.25.4 github.com/onflow/flow v0.4.20-0.20260303141511-b7c99b4fb01b github.com/onflow/flow-core-contracts/lib/go/contracts v1.10.3 github.com/onflow/flow-core-contracts/lib/go/templates v1.10.3 @@ -173,7 +173,7 @@ require ( github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect github.com/cockroachdb/redact v1.1.5 // indirect - github.com/cockroachdb/swiss v0.0.0-20251224182025-b0f6560f979b // indirect + github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 // indirect github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect github.com/consensys/gnark-crypto v0.18.1 // indirect github.com/containerd/cgroups v1.1.0 // indirect diff --git a/go.sum b/go.sum index babfe56427c..cfb8df9ec3b 100644 --- a/go.sum +++ b/go.sum @@ -256,8 +256,8 @@ github.com/cockroachdb/pebble/v2 v2.0.6 h1:eL54kX2AKp1ePJ/8vq4IO3xIEPpvVjlSP12dl github.com/cockroachdb/pebble/v2 v2.0.6/go.mod h1:un1DXG73PKw3F7Ndd30YactyvsFviI9Fuhe0tENdnyA= github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= -github.com/cockroachdb/swiss v0.0.0-20251224182025-b0f6560f979b h1:VXvSNzmr8hMj8XTuY0PT9Ane9qZGul/p67vGYwl9BFI= -github.com/cockroachdb/swiss v0.0.0-20251224182025-b0f6560f979b/go.mod h1:yBRu/cnL4ks9bgy4vAASdjIW+/xMlFwuHKqtmh3GZQg= +github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 h1:Nua446ru3juLHLZd4AwKNzClZgL1co3pUPGv3o8FlcA= +github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961/go.mod h1:yBRu/cnL4ks9bgy4vAASdjIW+/xMlFwuHKqtmh3GZQg= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= @@ -944,8 +944,8 @@ github.com/onflow/boxo v0.0.0-20240201202436-f2477b92f483 h1:LpiQhTAfM9CAmNVEs0n github.com/onflow/boxo v0.0.0-20240201202436-f2477b92f483/go.mod h1:pIZgTWdm3k3pLF9Uq6MB8JEcW07UDwNJjlXW1HELW80= github.com/onflow/cadence v1.10.3 h1:PJIIYKbaOT2DcZBnSO4O8ZF/Xc/fKV9vvOFLChgy85c= github.com/onflow/cadence v1.10.3/go.mod h1:tyUNaYlAgeQVgfR2C38MI1dtFFjKay+yGGPMrCRc068= -github.com/onflow/crypto v0.26.0 h1:eXPnaxjMs91jYXgNU93OO1oACkQfzkB0Ce+hbJgaRFU= -github.com/onflow/crypto v0.26.0/go.mod h1:nJgNMueICFD7F7fc2B7uX+Krpq9HQweWcU2GUmQrrM8= +github.com/onflow/crypto v0.25.4 h1:R615PWPdSoA5RATNb/j3cYaloBIZlSXVNgS7BjwHiwM= +github.com/onflow/crypto v0.25.4/go.mod h1:DlkW/1SPUvLHYvUcjWa9PkLIRgSBKR4EDc3i+ATQKW4= github.com/onflow/fixed-point v0.1.1 h1:j0jYZVO8VGyk1476alGudEg7XqCkeTVxb5ElRJRKS90= github.com/onflow/fixed-point v0.1.1/go.mod h1:gJdoHqKtToKdOZbvryJvDZfcpzC7d2fyWuo3ZmLtcGY= github.com/onflow/flow v0.4.20-0.20260303141511-b7c99b4fb01b h1:Pr+Vxdr/J0V+1mOKfOvC3+Ik6I9ogJGXDYkW0FIYS/g= diff --git a/insecure/go.mod b/insecure/go.mod index c2d2656dc75..666e1f6c9e2 100644 --- a/insecure/go.mod +++ b/insecure/go.mod @@ -1,6 +1,6 @@ module github.com/onflow/flow-go/insecure -go 1.26.0 +go 1.25.1 require ( github.com/btcsuite/btcd/chaincfg/chainhash v1.0.2 @@ -10,7 +10,7 @@ require ( github.com/libp2p/go-libp2p v0.38.2 github.com/libp2p/go-libp2p-pubsub v0.13.0 github.com/multiformats/go-multiaddr-dns v0.4.1 - github.com/onflow/crypto v0.26.0 + github.com/onflow/crypto v0.25.4 github.com/onflow/flow-go v0.36.2-0.20240717162253-d5d2e606ef53 github.com/rs/zerolog v1.29.0 github.com/spf13/pflag v1.0.6 @@ -70,7 +70,7 @@ require ( github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect github.com/cockroachdb/pebble/v2 v2.0.6 // indirect github.com/cockroachdb/redact v1.1.5 // indirect - github.com/cockroachdb/swiss v0.0.0-20251224182025-b0f6560f979b // indirect + github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 // indirect github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect github.com/consensys/gnark-crypto v0.18.1 // indirect github.com/containerd/cgroups v1.1.0 // indirect diff --git a/insecure/go.sum b/insecure/go.sum index 493070ece41..9dbe84f8391 100644 --- a/insecure/go.sum +++ b/insecure/go.sum @@ -231,8 +231,8 @@ github.com/cockroachdb/pebble/v2 v2.0.6 h1:eL54kX2AKp1ePJ/8vq4IO3xIEPpvVjlSP12dl github.com/cockroachdb/pebble/v2 v2.0.6/go.mod h1:un1DXG73PKw3F7Ndd30YactyvsFviI9Fuhe0tENdnyA= github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= -github.com/cockroachdb/swiss v0.0.0-20251224182025-b0f6560f979b h1:VXvSNzmr8hMj8XTuY0PT9Ane9qZGul/p67vGYwl9BFI= -github.com/cockroachdb/swiss v0.0.0-20251224182025-b0f6560f979b/go.mod h1:yBRu/cnL4ks9bgy4vAASdjIW+/xMlFwuHKqtmh3GZQg= +github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 h1:Nua446ru3juLHLZd4AwKNzClZgL1co3pUPGv3o8FlcA= +github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961/go.mod h1:yBRu/cnL4ks9bgy4vAASdjIW+/xMlFwuHKqtmh3GZQg= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= @@ -894,8 +894,8 @@ github.com/onflow/boxo v0.0.0-20240201202436-f2477b92f483 h1:LpiQhTAfM9CAmNVEs0n github.com/onflow/boxo v0.0.0-20240201202436-f2477b92f483/go.mod h1:pIZgTWdm3k3pLF9Uq6MB8JEcW07UDwNJjlXW1HELW80= github.com/onflow/cadence v1.10.3 h1:PJIIYKbaOT2DcZBnSO4O8ZF/Xc/fKV9vvOFLChgy85c= github.com/onflow/cadence v1.10.3/go.mod h1:tyUNaYlAgeQVgfR2C38MI1dtFFjKay+yGGPMrCRc068= -github.com/onflow/crypto v0.26.0 h1:eXPnaxjMs91jYXgNU93OO1oACkQfzkB0Ce+hbJgaRFU= -github.com/onflow/crypto v0.26.0/go.mod h1:nJgNMueICFD7F7fc2B7uX+Krpq9HQweWcU2GUmQrrM8= +github.com/onflow/crypto v0.25.4 h1:R615PWPdSoA5RATNb/j3cYaloBIZlSXVNgS7BjwHiwM= +github.com/onflow/crypto v0.25.4/go.mod h1:DlkW/1SPUvLHYvUcjWa9PkLIRgSBKR4EDc3i+ATQKW4= github.com/onflow/fixed-point v0.1.1 h1:j0jYZVO8VGyk1476alGudEg7XqCkeTVxb5ElRJRKS90= github.com/onflow/fixed-point v0.1.1/go.mod h1:gJdoHqKtToKdOZbvryJvDZfcpzC7d2fyWuo3ZmLtcGY= github.com/onflow/flow-core-contracts/lib/go/contracts v1.10.3 h1:OTJo6PzE8F0EtvBsBvXKVqSA8eCm1uzN+aWwV5gtjPs= diff --git a/integration/benchmark/cmd/manual/Dockerfile b/integration/benchmark/cmd/manual/Dockerfile index 6729d092d3c..094f93a7882 100644 --- a/integration/benchmark/cmd/manual/Dockerfile +++ b/integration/benchmark/cmd/manual/Dockerfile @@ -1,7 +1,7 @@ # syntax = docker/dockerfile:experimental # NOTE: Must be run in the context of the repo's root directory -FROM golang:1.26-bookworm AS build-setup +FROM golang:1.25-bookworm AS build-setup RUN apt-get update RUN apt-get -y install zip diff --git a/integration/go.mod b/integration/go.mod index cf340a545f9..802f8bebdbb 100644 --- a/integration/go.mod +++ b/integration/go.mod @@ -1,6 +1,6 @@ module github.com/onflow/flow-go/integration -go 1.26.0 +go 1.25.1 require ( cloud.google.com/go/bigquery v1.72.0 @@ -21,7 +21,7 @@ require ( github.com/ipfs/go-ds-pebble v0.5.0 github.com/libp2p/go-libp2p v0.38.2 github.com/onflow/cadence v1.10.3 - github.com/onflow/crypto v0.26.0 + github.com/onflow/crypto v0.25.4 github.com/onflow/flow v0.4.20-0.20260303141511-b7c99b4fb01b github.com/onflow/flow-core-contracts/lib/go/contracts v1.10.3 github.com/onflow/flow-core-contracts/lib/go/templates v1.10.3 @@ -103,7 +103,7 @@ require ( github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect github.com/cockroachdb/redact v1.1.5 // indirect - github.com/cockroachdb/swiss v0.0.0-20251224182025-b0f6560f979b // indirect + github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 // indirect github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect github.com/consensys/gnark-crypto v0.18.1 // indirect github.com/containerd/cgroups v1.1.0 // indirect diff --git a/integration/go.sum b/integration/go.sum index 74096692d66..0fbc76cbb98 100644 --- a/integration/go.sum +++ b/integration/go.sum @@ -184,8 +184,8 @@ github.com/cockroachdb/pebble/v2 v2.0.6 h1:eL54kX2AKp1ePJ/8vq4IO3xIEPpvVjlSP12dl github.com/cockroachdb/pebble/v2 v2.0.6/go.mod h1:un1DXG73PKw3F7Ndd30YactyvsFviI9Fuhe0tENdnyA= github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= -github.com/cockroachdb/swiss v0.0.0-20251224182025-b0f6560f979b h1:VXvSNzmr8hMj8XTuY0PT9Ane9qZGul/p67vGYwl9BFI= -github.com/cockroachdb/swiss v0.0.0-20251224182025-b0f6560f979b/go.mod h1:yBRu/cnL4ks9bgy4vAASdjIW+/xMlFwuHKqtmh3GZQg= +github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 h1:Nua446ru3juLHLZd4AwKNzClZgL1co3pUPGv3o8FlcA= +github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961/go.mod h1:yBRu/cnL4ks9bgy4vAASdjIW+/xMlFwuHKqtmh3GZQg= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= github.com/consensys/gnark-crypto v0.18.1 h1:RyLV6UhPRoYYzaFnPQA4qK3DyuDgkTgskDdoGqFt3fI= @@ -754,8 +754,8 @@ github.com/onflow/boxo v0.0.0-20240201202436-f2477b92f483 h1:LpiQhTAfM9CAmNVEs0n github.com/onflow/boxo v0.0.0-20240201202436-f2477b92f483/go.mod h1:pIZgTWdm3k3pLF9Uq6MB8JEcW07UDwNJjlXW1HELW80= github.com/onflow/cadence v1.10.3 h1:PJIIYKbaOT2DcZBnSO4O8ZF/Xc/fKV9vvOFLChgy85c= github.com/onflow/cadence v1.10.3/go.mod h1:tyUNaYlAgeQVgfR2C38MI1dtFFjKay+yGGPMrCRc068= -github.com/onflow/crypto v0.26.0 h1:eXPnaxjMs91jYXgNU93OO1oACkQfzkB0Ce+hbJgaRFU= -github.com/onflow/crypto v0.26.0/go.mod h1:nJgNMueICFD7F7fc2B7uX+Krpq9HQweWcU2GUmQrrM8= +github.com/onflow/crypto v0.25.4 h1:R615PWPdSoA5RATNb/j3cYaloBIZlSXVNgS7BjwHiwM= +github.com/onflow/crypto v0.25.4/go.mod h1:DlkW/1SPUvLHYvUcjWa9PkLIRgSBKR4EDc3i+ATQKW4= github.com/onflow/fixed-point v0.1.1 h1:j0jYZVO8VGyk1476alGudEg7XqCkeTVxb5ElRJRKS90= github.com/onflow/fixed-point v0.1.1/go.mod h1:gJdoHqKtToKdOZbvryJvDZfcpzC7d2fyWuo3ZmLtcGY= github.com/onflow/flow v0.4.20-0.20260303141511-b7c99b4fb01b h1:Pr+Vxdr/J0V+1mOKfOvC3+Ik6I9ogJGXDYkW0FIYS/g= diff --git a/integration/localnet/client/Dockerfile b/integration/localnet/client/Dockerfile index 21f23564e48..f80ab6c59d4 100644 --- a/integration/localnet/client/Dockerfile +++ b/integration/localnet/client/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.26 +FROM golang:1.25 COPY flow-localnet.json /go diff --git a/ledger/common/hash/hash_test.go b/ledger/common/hash/hash_test.go index 6f2afcb285b..b5b8227208a 100644 --- a/ledger/common/hash/hash_test.go +++ b/ledger/common/hash/hash_test.go @@ -2,12 +2,11 @@ package hash_test import ( "crypto/rand" - sha30 "crypto/sha3" - hash0 "hash" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "golang.org/x/crypto/sha3" cryhash "github.com/onflow/crypto/hash" @@ -31,7 +30,7 @@ func TestHash(t *testing.T) { require.NoError(t, err) h := hash.HashLeaf(path, value) - hasher := hash0.Hash(sha30.New256()) + hasher := sha3.New256() _, _ = hasher.Write(path[:]) _, _ = hasher.Write(value) expected := hasher.Sum(nil) @@ -49,7 +48,7 @@ func TestHash(t *testing.T) { require.NoError(t, err) h := hash.HashInterNode(h1, h2) - hasher := hash0.Hash(sha30.New256()) + hasher := sha3.New256() _, _ = hasher.Write(h1[:]) _, _ = hasher.Write(h2[:]) expected := hasher.Sum(nil) diff --git a/ledger/complete/compactor.go b/ledger/complete/compactor.go index cc56e3758db..0db6dbef7c0 100644 --- a/ledger/complete/compactor.go +++ b/ledger/complete/compactor.go @@ -193,7 +193,10 @@ func (c *Compactor) run() { // Compute next checkpoint number. // nextCheckpointNum is updated when checkpointing starts, fails to start, or fails. // NOTE: next checkpoint number must >= active segment num. - nextCheckpointNum := max(activeSegmentNum, lastCheckpointNum+int(c.checkpointDistance)) + nextCheckpointNum := lastCheckpointNum + int(c.checkpointDistance) + if activeSegmentNum > nextCheckpointNum { + nextCheckpointNum = activeSegmentNum + } ctx, cancel := context.WithCancel(context.Background()) diff --git a/ledger/complete/compactor_test.go b/ledger/complete/compactor_test.go index adcdb9faf07..15cf89a446f 100644 --- a/ledger/complete/compactor_test.go +++ b/ledger/complete/compactor_test.go @@ -37,7 +37,7 @@ type CompactorObserver struct { done chan struct{} } -func (co *CompactorObserver) OnNext(val any) { +func (co *CompactorObserver) OnNext(val interface{}) { res, ok := val.(int) if ok { newCheckpoint := res @@ -107,7 +107,7 @@ func TestCompactorCreation(t *testing.T) { // update the ledger size (10) times, since each update will trigger a segment file creation // and checkpointDistance is 3, then, 10 segment files should trigger generating checkpoint: // 2, 5, 8, that's why the fromBound is 8 - for i := range size { + for i := 0; i < size; i++ { // slow down updating the ledger, because running too fast would cause the previous checkpoint // to not finish and get delayed time.Sleep(LedgerUpdateDelay) @@ -328,7 +328,7 @@ func TestCompactorSkipCheckpointing(t *testing.T) { rootState := l.InitialState() // Generate the tree and create WAL - for i := range size { + for i := 0; i < size; i++ { // slow down updating the ledger, because running too fast would cause the previous checkpoint // to not finish and get delayed @@ -434,7 +434,7 @@ func TestCompactorAccuracy(t *testing.T) { rootHash := trie.EmptyTrieRootHash() // Create DiskWAL and Ledger repeatedly to test rebuilding ledger state at restart. - for i := range 3 { + for i := 0; i < 3; i++ { wal, err := realWAL.NewDiskWAL(unittest.Logger(), nil, metrics.NewNoopCollector(), dir, forestCapacity, pathByteSize, 32*1024) require.NoError(t, err) @@ -455,7 +455,7 @@ func TestCompactorAccuracy(t *testing.T) { // Generate the tree and create WAL // size+2 is used to ensure that size/2 segments are finalized. - for range size + 2 { + for i := 0; i < size+2; i++ { // slow down updating the ledger, because running too fast would cause the previous checkpoint // to not finish and get delayed time.Sleep(LedgerUpdateDelay) @@ -570,7 +570,7 @@ func TestCompactorTriggeredByAdminTool(t *testing.T) { fmt.Println("generate the tree and create WAL") fmt.Println("2 trie updates will fill a segment file, and 12 trie updates will fill 6 segment files") fmt.Println("13 trie updates in total will trigger segment 5 to be finished, which should trigger checkpoint 5") - for range 13 { + for i := 0; i < 13; i++ { // slow down updating the ledger, because running too fast would cause the previous checkpoint // to not finish and get delayed time.Sleep(LedgerUpdateDelay) @@ -671,12 +671,12 @@ func TestCompactorConcurrency(t *testing.T) { wg.Add(numGoroutine) // Run 4 goroutines and each goroutine updates size+1 tries. - for range numGoroutine { + for j := 0; j < numGoroutine; j++ { go func(parentState ledger.State) { defer wg.Done() // size+1 is used to ensure that size/2*numGoroutine segments are finalized. - for range size + 1 { + for i := 0; i < size+1; i++ { // slow down updating the ledger, because running too fast would cause the previous checkpoint // to not finish and get delayed time.Sleep(LedgerUpdateDelay) @@ -751,7 +751,7 @@ func testCheckpointedTriesMatchReplayedTriesFromSegments( if inSequence { // Test that checkpointed tries match replayed tries in content and sequence (insertion order). require.Equal(t, len(triesFromReplayingSegments), len(triesFromLoadingCheckpoint)) - for i := range triesFromReplayingSegments { + for i := 0; i < len(triesFromReplayingSegments); i++ { require.Equal(t, triesFromReplayingSegments[i].RootHash(), triesFromLoadingCheckpoint[i].RootHash()) } return diff --git a/ledger/complete/ledger_benchmark_test.go b/ledger/complete/ledger_benchmark_test.go index 00edc890f91..a97257ac2a6 100644 --- a/ledger/complete/ledger_benchmark_test.go +++ b/ledger/complete/ledger_benchmark_test.go @@ -65,7 +65,7 @@ func benchmarkStorage(steps int, b *testing.B) { totalPTrieConstTimeMS := 0 state := led.InitialState() - for range steps { + for i := 0; i < steps; i++ { keys := testutils.RandomUniqueKeys(numInsPerStep, keyNumberOfParts, keyPartMinByteSize, keyPartMaxByteSize) values := testutils.RandomValues(numInsPerStep, 1, valueMaxByteSize) diff --git a/ledger/complete/ledger_test.go b/ledger/complete/ledger_test.go index 71738ba8045..cbe0be529d6 100644 --- a/ledger/complete/ledger_test.go +++ b/ledger/complete/ledger_test.go @@ -523,7 +523,7 @@ func Test_WAL(t *testing.T) { //saved data after updates savedData := make(map[string]map[string]ledger.Value) - for range size { + for i := 0; i < size; i++ { keys := testutils.RandomUniqueKeys(numInsPerStep, keyNumberOfParts, keyPartMinByteSize, keyPartMaxByteSize) values := testutils.RandomValues(numInsPerStep, 1, valueMaxByteSize) @@ -595,7 +595,7 @@ func TestLedgerFunctionality(t *testing.T) { metricsCollector := &metrics.NoopCollector{} logger := zerolog.Logger{} - for range experimentRep { + for e := 0; e < experimentRep; e++ { numInsPerStep := 100 numHistLookupPerStep := 10 keyNumberOfParts := 10 @@ -617,7 +617,7 @@ func TestLedgerFunctionality(t *testing.T) { <-compactor.Ready() state := led.InitialState() - for range steps { + for i := 0; i < steps; i++ { // add new keys // TODO update some of the existing keys and shuffle them keys := testutils.RandomUniqueKeys(numInsPerStep, keyNumberOfParts, keyPartMinByteSize, keyPartMaxByteSize) @@ -886,7 +886,7 @@ func TestLedger_StateByIndex(t *testing.T) { values := testutils.RandomValues(3, 1, 32) // Create multiple updates - for i := range 3 { + for i := 0; i < 3; i++ { update, err := ledger.NewUpdate(state, keys[i:i+1], values[i:i+1]) require.NoError(t, err) newState, _, err := l.Set(update) diff --git a/ledger/complete/mtrie/forest_test.go b/ledger/complete/mtrie/forest_test.go index 35d5405f8cc..36f29c9d2c6 100644 --- a/ledger/complete/mtrie/forest_test.go +++ b/ledger/complete/mtrie/forest_test.go @@ -792,7 +792,7 @@ func TestRandomUpdateReadProofValueSizes(t *testing.T) { require.NoError(t, err) latestPayloadByPath := make(map[ledger.Path]*ledger.Payload) // map store - for range rep { + for e := 0; e < rep; e++ { paths := testutils.RandomPathsRandLen(maxNumPathsPerStep) payloads := testutils.RandomPayloads(len(paths), minPayloadByteSize, maxPayloadByteSize) diff --git a/ledger/complete/mtrie/trie/trie_test.go b/ledger/complete/mtrie/trie/trie_test.go index d43252d345f..ca62da06de2 100644 --- a/ledger/complete/mtrie/trie/trie_test.go +++ b/ledger/complete/mtrie/trie/trie_test.go @@ -59,7 +59,7 @@ func Test_TrieWithRightRegister(t *testing.T) { emptyTrie := trie.NewEmptyMTrie() // build a path with all 1s var path ledger.Path - for i := range len(path) { + for i := 0; i < len(path); i++ { path[i] = uint8(255) } payload := testutils.LightPayload(12346, 54321) @@ -125,7 +125,7 @@ func Test_FullTrie(t *testing.T) { paths := make([]ledger.Path, 0, numberRegisters) payloads := make([]ledger.Payload, 0, numberRegisters) var totalPayloadSize uint64 - for i := range numberRegisters { + for i := 0; i < numberRegisters; i++ { paths = append(paths, testutils.PathByUint16LeftPadded(uint16(i))) temp := rng.next() payload := testutils.LightPayload(temp, temp) @@ -187,7 +187,7 @@ func Test_UpdateTrie(t *testing.T) { var payloads []ledger.Payload parentTrieRegCount := updatedTrie.AllocatedRegCount() parentTrieRegSize := updatedTrie.AllocatedRegSize() - for r := range 20 { + for r := 0; r < 20; r++ { paths, payloads = deduplicateWrites(sampleRandomRegisterWrites(rng, r*100)) var totalPayloadSize uint64 for _, p := range payloads { @@ -288,7 +288,7 @@ func (rng *LinearCongruentialGenerator) next() uint16 { func sampleRandomRegisterWrites(rng *LinearCongruentialGenerator, number int) ([]ledger.Path, []ledger.Payload) { paths := make([]ledger.Path, 0, number) payloads := make([]ledger.Payload, 0, number) - for range number { + for i := 0; i < number; i++ { path := testutils.PathByUint16LeftPadded(rng.next()) paths = append(paths, path) t := rng.next() @@ -311,7 +311,7 @@ func sampleRandomRegisterWritesWithPrefix(rng *LinearCongruentialGenerator, numb payloads := make([]ledger.Payload, 0, number) nextRandomBytes := make([]byte, 2) nextRandomByteIndex := 2 // index of next unused byte in nextRandomBytes; if value is >= 2, we need to generate new random bytes - for range number { + for i := 0; i < number; i++ { var p ledger.Path copy(p[:prefixLen], prefix) for b := prefixLen; b < hash.HashLen; b++ { @@ -361,13 +361,13 @@ func TestSplitByPath(t *testing.T) { // create path slice with redundant paths paths := make([]ledger.Path, 0, pathsNumber) - for range pathsNumber - redundantPaths { + for i := 0; i < pathsNumber-redundantPaths; i++ { var p ledger.Path _, err := rand.Read(p[:]) require.NoError(t, err) paths = append(paths, p) } - for i := range redundantPaths { + for i := 0; i < redundantPaths; i++ { paths = append(paths, paths[i]) } @@ -382,7 +382,7 @@ func TestSplitByPath(t *testing.T) { index := trie.SplitPaths(paths, randomIndex) // check correctness - for i := range index { + for i := 0; i < index; i++ { assert.Equal(t, bitutils.ReadBit(paths[i][:], randomIndex), 0) } for i := index; i < len(paths); i++ { @@ -643,7 +643,7 @@ func Test_Pruning(t *testing.T) { var maxDepthTouched, maxDepthTouchedWithPruning uint16 var parentTrieRegCount, parentTrieRegSize uint64 - for range numberOfSteps { + for step := 0; step < numberOfSteps; step++ { updatePaths := make([]ledger.Path, 0) updatePayloads := make([]ledger.Payload, 0) @@ -681,7 +681,7 @@ func Test_Pruning(t *testing.T) { } // only set it for the updates - for i := range numberOfUpdates { + for i := 0; i < numberOfUpdates; i++ { allPaths[updatePaths[i]] = updatePayloads[i] } @@ -795,7 +795,7 @@ func TestValueSizes(t *testing.T) { // Populate pathsToGetValueSize with all possible paths for the first 4 bits. pathsToGetValueSize := make([]ledger.Path, 16) - for i := range 16 { + for i := 0; i < 16; i++ { pathsToGetValueSize[i] = testutils.PathByUint16(uint16(i << 12)) } @@ -886,7 +886,7 @@ func TestTrieAllocatedRegCountRegSize(t *testing.T) { paths := make([]ledger.Path, numberRegisters) payloads := make([]ledger.Payload, numberRegisters) var totalPayloadSize uint64 - for i := range numberRegisters { + for i := 0; i < numberRegisters; i++ { var p ledger.Path p[0] = byte(i) @@ -926,7 +926,7 @@ func TestTrieAllocatedRegCountRegSize(t *testing.T) { // to test reg count and size with new empty registers. newPaths := []ledger.Path{} newPayloads := []ledger.Payload{} - for i := range paths { + for i := 0; i < len(paths); i++ { oldPath := paths[i] path1, _ := ledger.ToPath(oldPath[:]) @@ -959,7 +959,7 @@ func TestTrieAllocatedRegCountRegSize(t *testing.T) { // Remove register one by one to test reg count and size with empty registers // (old payload size > 0 and new payload size == 0) - for i := range paths { + for i := 0; i < len(paths); i++ { newPaths := []ledger.Path{paths[i]} newPayloads := []ledger.Payload{*ledger.EmptyPayload()} @@ -987,7 +987,7 @@ func TestTrieAllocatedRegCountRegSize(t *testing.T) { // Remove register one by one to test reg count and size with empty registers // (old payload size > 0 and new payload size == 0) - for i := range paths { + for i := 0; i < len(paths); i++ { newPaths := []ledger.Path{paths[i]} newPayloads := []ledger.Payload{*ledger.EmptyPayload()} @@ -1009,7 +1009,7 @@ func TestTrieAllocatedRegCountRegSize(t *testing.T) { // Update with removed paths and empty payloads // (old payload size == 0 and new payload size == 0) newPayloads := make([]ledger.Payload, len(paths)) - for i := range paths { + for i := 0; i < len(paths); i++ { newPayloads[i] = *ledger.EmptyPayload() } @@ -1047,7 +1047,7 @@ func TestTrieAllocatedRegCountRegSizeWithMixedPruneFlag(t *testing.T) { paths := make([]ledger.Path, numberRegisters) payloads := make([]ledger.Payload, numberRegisters) var totalPayloadSize uint64 - for i := range numberRegisters { + for i := 0; i < numberRegisters; i++ { var p ledger.Path p[0] = byte(i) @@ -1181,7 +1181,7 @@ func TestReadSinglePayload(t *testing.T) { // // Test reading payload for all possible paths for the first 4 bits. - for i := range 16 { + for i := 0; i < 16; i++ { path := testutils.PathByUint16(uint16(i << 12)) retPayload := newTrie.ReadSinglePayload(path) diff --git a/ledger/complete/mtrie/trieCache_test.go b/ledger/complete/mtrie/trieCache_test.go index 86ad915b627..dbb8caecc8e 100644 --- a/ledger/complete/mtrie/trieCache_test.go +++ b/ledger/complete/mtrie/trieCache_test.go @@ -33,7 +33,7 @@ func TestTrieCache(t *testing.T) { var savedTries []*trie.MTrie // Push tries to queue to fill out capacity - for range capacity { + for i := 0; i < capacity; i++ { trie, err := randomMTrie() require.NoError(t, err) @@ -56,7 +56,7 @@ func TestTrieCache(t *testing.T) { } // Push more tries to queue to overwrite older elements - for range capacity { + for i := 0; i < capacity; i++ { trie, err := randomMTrie() require.NoError(t, err) diff --git a/ledger/complete/wal/checkpoint_v6_reader.go b/ledger/complete/wal/checkpoint_v6_reader.go index b91d9c91f40..88b8df09c18 100644 --- a/ledger/complete/wal/checkpoint_v6_reader.go +++ b/ledger/complete/wal/checkpoint_v6_reader.go @@ -135,7 +135,7 @@ func ReadCheckpointFileSize(dir string, fileName string) (uint64, error) { func allFilePaths(dir string, fileName string) []string { paths := make([]string, 0, 1+subtrieCount+1) paths = append(paths, filePathCheckpointHeader(dir, fileName)) - for i := range subtrieCount { + for i := 0; i < subtrieCount; i++ { subTriePath, _, _ := filePathSubTries(dir, fileName, i) paths = append(paths, subTriePath) } @@ -205,7 +205,7 @@ func readCheckpointHeader(filepath string, logger zerolog.Logger) ( } subtrieChecksums := make([]uint32, subtrieCount) - for i := range subtrieCount { + for i := uint16(0); i < subtrieCount; i++ { sum, err := readCRC32Sum(reader) if err != nil { return nil, 0, fmt.Errorf("could not read %v-th subtrie checksum from checkpoint header: %w", i, err) @@ -287,7 +287,7 @@ func findCheckpointPartFiles(dir string, fileName string) ([]string, error) { } // check all subtrie parts - for i := range subtrieCount { + for i := 0; i < subtrieCount; i++ { subtriePath, _, err := filePathSubTries(dir, fileName, i) if err != nil { return nil, err @@ -342,7 +342,7 @@ func readSubTriesConcurrently(dir string, fileName string, subtrieChecksums []ui // TODO: make nWorker configable nWorker := numOfSubTries // use as many worker as the jobs to read subtries concurrently - for range nWorker { + for i := 0; i < nWorker; i++ { go func() { for job := range jobs { nodes, err := readCheckpointSubTrie(dir, fileName, job.Index, job.Checksum, logger) @@ -614,7 +614,7 @@ func readTopLevelTries(dir string, fileName string, subtrieNodes [][]*node.Node, } // read the trie root nodes - for i := range triesCount { + for i := uint16(0); i < triesCount; i++ { trie, err := flattener.ReadTrie(reader, scratch, func(nodeIndex uint64) (*node.Node, error) { return getNodeByIndex(subtrieNodes, totalSubTrieNodeCount, topLevelNodes, nodeIndex) }) diff --git a/ledger/complete/wal/checkpoint_v6_test.go b/ledger/complete/wal/checkpoint_v6_test.go index a1c8c5d3cb9..1e036d3adf6 100644 --- a/ledger/complete/wal/checkpoint_v6_test.go +++ b/ledger/complete/wal/checkpoint_v6_test.go @@ -99,7 +99,7 @@ func randPathPayload() (ledger.Path, ledger.Payload) { func randNPathPayloads(n int) ([]ledger.Path, []ledger.Payload) { paths := make([]ledger.Path, n) payloads := make([]ledger.Payload, n) - for i := range n { + for i := 0; i < n; i++ { path, payload := randPathPayload() paths[i] = path payloads[i] = payload @@ -113,7 +113,7 @@ func createMultipleRandomTries(t *testing.T) []*trie.MTrie { var err error // add tries with no shared paths - for range 100 { + for i := 0; i < 100; i++ { paths, payloads := randNPathPayloads(100) activeTrie, _, err = trie.NewTrieWithUpdatedRegisters(activeTrie, paths, payloads, false) require.NoError(t, err, "update registers") @@ -159,7 +159,7 @@ func createMultipleRandomTriesMini(t *testing.T) ([]*trie.MTrie, *trie.MTrie) { var err error // add tries with no shared paths - for range 5 { + for i := 0; i < 5; i++ { paths, payloads := randNPathPayloads(20) activeTrie, _, err = trie.NewTrieWithUpdatedRegisters(activeTrie, paths, payloads, false) require.NoError(t, err, "update registers") @@ -265,7 +265,7 @@ func randomNode() *node.Node { func TestGetNodesByIndex(t *testing.T) { n := 10 ns := make([]*node.Node, n) - for i := range n { + for i := 0; i < n; i++ { ns[i] = randomNode() } subtrieNodes := [][]*node.Node{ @@ -553,7 +553,7 @@ func TestCleanupOnErrorIfNotExist(t *testing.T) { // verify that if a part file is missing then os.ErrNotExist should return func TestAllPartFileExist(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { - for i := range 17 { + for i := 0; i < 17; i++ { tries := createSimpleTrie(t) fileName := fmt.Sprintf("checkpoint_missing_part_file_%v", i) var fileToDelete string @@ -581,7 +581,7 @@ func TestAllPartFileExist(t *testing.T) { // verify that if a part file is missing then os.ErrNotExist should return func TestAllPartFileExistLeafReader(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { - for i := range 17 { + for i := 0; i < 17; i++ { tries := createSimpleTrie(t) fileName := fmt.Sprintf("checkpoint_missing_part_file_%v", i) var fileToDelete string @@ -626,7 +626,7 @@ func filePaths(dir string, fileName string, subtrieLevel uint16) []string { paths = append(paths, filePathCheckpointHeader(dir, fileName)) subtrieCount := subtrieCountByLevel(subtrieLevel) - for i := range subtrieCount { + for i := 0; i < subtrieCount; i++ { partFile := partFileName(fileName, i) paths = append(paths, path.Join(dir, partFile)) } diff --git a/ledger/complete/wal/checkpoint_v6_writer.go b/ledger/complete/wal/checkpoint_v6_writer.go index ce654cc3ba1..b72eff4392e 100644 --- a/ledger/complete/wal/checkpoint_v6_writer.go +++ b/ledger/complete/wal/checkpoint_v6_writer.go @@ -272,7 +272,7 @@ func storeTopLevelNodesAndTrieRoots( func createSubTrieRoots(tries []*trie.MTrie) [subtrieCount][]*node.Node { var subtrieRoots [subtrieCount][]*node.Node - for i := range len(subtrieRoots) { + for i := 0; i < len(subtrieRoots); i++ { subtrieRoots[i] = make([]*node.Node, len(tries)) } diff --git a/ledger/complete/wal/checkpointer.go b/ledger/complete/wal/checkpointer.go index c0f1eaf21a6..2c1aeead713 100644 --- a/ledger/complete/wal/checkpointer.go +++ b/ledger/complete/wal/checkpointer.go @@ -398,7 +398,7 @@ func StoreCheckpointV5(dir string, fileName string, logger zerolog.Logger, tries // - subtrieRoots[subtrieCount-1] is a list of all subtrie roots at path [1,1,1,1] // subtrie roots in subtrieRoots[0] have the same path, therefore might have shared child nodes. var subtrieRoots [subtrieCount][]*node.Node - for i := range len(subtrieRoots) { + for i := 0; i < len(subtrieRoots); i++ { subtrieRoots[i] = make([]*node.Node, len(tries)) } @@ -756,7 +756,7 @@ func readCheckpointV3AndEarlier(f *os.File, version uint16) ([]*trie.MTrie, erro nodes[i].regSize = regSize } - for i := range triesCount { + for i := uint16(0); i < triesCount; i++ { trie, err := flattener.ReadTrieFromCheckpointV3AndEarlier(reader, func(nodeIndex uint64) (*node.Node, uint64, uint64, error) { if nodeIndex >= uint64(len(nodes)) { return nil, 0, 0, fmt.Errorf("sequence of stored nodes doesn't contain node") @@ -863,7 +863,7 @@ func readCheckpointV4(f *os.File) ([]*trie.MTrie, error) { nodes[i].regSize = regSize } - for i := range triesCount { + for i := uint16(0); i < triesCount; i++ { trie, err := flattener.ReadTrieFromCheckpointV4(reader, scratch, func(nodeIndex uint64) (*node.Node, uint64, uint64, error) { if nodeIndex >= uint64(len(nodes)) { return nil, 0, 0, fmt.Errorf("sequence of stored nodes doesn't contain node") @@ -977,7 +977,7 @@ func readCheckpointV5(f *os.File, logger zerolog.Logger) ([]*trie.MTrie, error) logger.Info().Msgf("finished loading %v trie nodes, start loading %v tries", nodesCount, triesCount) - for i := range triesCount { + for i := uint16(0); i < triesCount; i++ { trie, err := flattener.ReadTrie(reader, scratch, func(nodeIndex uint64) (*node.Node, error) { if nodeIndex >= uint64(len(nodes)) { return nil, fmt.Errorf("sequence of stored nodes doesn't contain node") diff --git a/ledger/complete/wal/checkpointer_serialization_test.go b/ledger/complete/wal/checkpointer_serialization_test.go index 9481b8c5bdc..f90992a01ad 100644 --- a/ledger/complete/wal/checkpointer_serialization_test.go +++ b/ledger/complete/wal/checkpointer_serialization_test.go @@ -17,7 +17,7 @@ func TestGetNodesAtLevel(t *testing.T) { t.Run("nil node", func(t *testing.T) { n := (*node.Node)(nil) - for level := range uint(6) { + for level := uint(0); level < 6; level++ { nodes := getNodesAtLevel(n, level) assert.Equal(t, 1< maxReceiptCount { + count = maxReceiptCount + } filteredReceipts := make([]*flow.ExecutionReceiptStub, 0, count) - for i := range count { + for i := uint(0); i < count; i++ { receipt := receipts[i] meta := receipt.Stub() resultID := meta.ResultID diff --git a/module/builder/consensus/builder_test.go b/module/builder/consensus/builder_test.go index bd22a0f1ae8..129191918d4 100644 --- a/module/builder/consensus/builder_test.go +++ b/module/builder/consensus/builder_test.go @@ -225,7 +225,7 @@ func (bs *BuilderSuite) SetupTest() { // Construct finalized blocks [F0] ... [F4] previous := first - for n := range numFinalizedBlocks { + for n := 0; n < numFinalizedBlocks; n++ { finalized := bs.createAndRecordBlock(previous, n > 0) // Do not construct candidate seal for [first], as it is already sealed bs.finalizedBlockIDs = append(bs.finalizedBlockIDs, finalized.ID()) previous = finalized @@ -237,7 +237,7 @@ func (bs *BuilderSuite) SetupTest() { // Construct the pending (i.e. unfinalized) ancestors [A0], ..., [A3] previous = final - for range numPendingBlocks { + for n := 0; n < numPendingBlocks; n++ { pending := bs.createAndRecordBlock(previous, true) bs.pendingBlockIDs = append(bs.pendingBlockIDs, pending.ID()) previous = pending @@ -636,7 +636,7 @@ func (bs *BuilderSuite) TestPayloadSeals_OnlyFork() { // * [F0] ... [F4] and [final] are finalized, unsealed blocks with candidate seals are included in mempool // * [A0] ... [A2] are non-finalized, unsealed blocks with candidate seals are included in mempool forkHead := bs.blocks[bs.finalID] - for i := range 8 { + for i := 0; i < 8; i++ { // Usually, the blocks [B6] and [B7] will not have candidate seal for the following reason: // For the verifiers to start checking a result R, they need a source of randomness for the block _incorporating_ // result R. The result for block [B6] is incorporated in [B7], which does _not_ have a child yet. @@ -1107,7 +1107,7 @@ func (bs *BuilderSuite) TestPayloadReceipts_BlockLimit() { metas := []*flow.ExecutionReceiptStub{} expectedResults := []*flow.ExecutionResult{} var i uint64 - for i = range 5 { + for i = 0; i < 5; i++ { blockOnFork := bs.blocks[bs.irsList[i].Seal.BlockID] pendingReceipt := unittest.ReceiptForBlockFixture(blockOnFork) receipts = append(receipts, pendingReceipt) @@ -1133,7 +1133,7 @@ func (bs *BuilderSuite) TestPayloadReceipts_AsProvidedByReceiptForest() { var expectedReceipts []*flow.ExecutionReceipt var expectedMetas []*flow.ExecutionReceiptStub var expectedResults []*flow.ExecutionResult - for i := range 10 { + for i := 0; i < 10; i++ { expectedReceipts = append(expectedReceipts, unittest.ExecutionReceiptFixture()) expectedMetas = append(expectedMetas, expectedReceipts[i].Stub()) expectedResults = append(expectedResults, &expectedReceipts[i].ExecutionResult) diff --git a/module/chainsync/core.go b/module/chainsync/core.go index 538a3fb2fd5..c493df79cb9 100644 --- a/module/chainsync/core.go +++ b/module/chainsync/core.go @@ -2,7 +2,7 @@ package chainsync import ( "fmt" - "slices" + "sort" "sync" "time" @@ -421,7 +421,9 @@ func (c *Core) BatchRequested(batch chainsync.Batch) { func (c *Core) getRanges(heights []uint64) []chainsync.Range { // sort the heights so we can build contiguous ranges more easily - slices.Sort(heights) + sort.Slice(heights, func(i int, j int) bool { + return heights[i] < heights[j] + }) // build contiguous height ranges with maximum batch size start := uint64(0) @@ -479,7 +481,10 @@ func (c *Core) getBatches(blockIDs []flow.Identifier) []chainsync.Batch { for from := 0; from < len(blockIDs); from += int(c.Config.MaxSize) { // make sure last range is not out of bounds - to := min(from+int(c.Config.MaxSize), len(blockIDs)) + to := from + int(c.Config.MaxSize) + if to > len(blockIDs) { + to = len(blockIDs) + } // create the block IDs slice requestIDs := blockIDs[from:to] diff --git a/module/chainsync/core_test.go b/module/chainsync/core_test.go index ee366b69194..0fbd306e553 100644 --- a/module/chainsync/core_test.go +++ b/module/chainsync/core_test.go @@ -63,7 +63,7 @@ func (ss *SyncSuite) TestQueueByHeight() { // generate a number of heights var heights []uint64 - for range 100 { + for n := 0; n < 100; n++ { heights = append(heights, rand.Uint64()) } @@ -94,7 +94,7 @@ func (ss *SyncSuite) TestQueueByBlockID() { // generate a number of block IDs var blockIDs []flow.Identifier - for range 100 { + for n := 0; n < 100; n++ { blockIDs = append(blockIDs, unittest.IdentifierFixture()) } @@ -400,7 +400,7 @@ func (ss *SyncSuite) TestPrune() { ) // add some finalized blocks by height - for i := range 3 { + for i := 0; i < 3; i++ { block := unittest.BlockFixture( unittest.Block.WithHeight(uint64(i + 1)), ) @@ -408,7 +408,7 @@ func (ss *SyncSuite) TestPrune() { prunableHeights = append(prunableHeights, block) } // add some un-finalized blocks by height - for i := range 3 { + for i := 0; i < 3; i++ { block := unittest.BlockFixture( unittest.Block.WithHeight(final.Height + uint64(i+1)), ) @@ -417,7 +417,7 @@ func (ss *SyncSuite) TestPrune() { } // add some finalized blocks by block ID - for i := range 3 { + for i := 0; i < 3; i++ { block := unittest.BlockFixture( unittest.Block.WithHeight(uint64(i + 1)), ) @@ -425,7 +425,7 @@ func (ss *SyncSuite) TestPrune() { prunableBlockIDs = append(prunableBlockIDs, block) } // add some un-finalized, received blocks by block ID - for i := range 3 { + for i := 0; i < 3; i++ { block := unittest.BlockFixture( unittest.Block.WithHeight(100 + uint64(i+1)), ) diff --git a/module/chunks/chunkVerifier_test.go b/module/chunks/chunkVerifier_test.go index 9717c176805..4dfea123dae 100644 --- a/module/chunks/chunkVerifier_test.go +++ b/module/chunks/chunkVerifier_test.go @@ -671,6 +671,7 @@ func generateEvents(t *testing.T, collection *flow.Collection, includeServiceEve // service events are also included as regular events if includeServiceEvent { for _, e := range serviceEventsList { + e := e event, err := convert.ServiceEvent(testChainID, e) require.NoError(t, err) diff --git a/module/chunks/chunk_assigner_test.go b/module/chunks/chunk_assigner_test.go index 34a37b8da2a..80bf01a5a5d 100644 --- a/module/chunks/chunk_assigner_test.go +++ b/module/chunks/chunk_assigner_test.go @@ -58,7 +58,7 @@ func (a *PublicAssignmentTestSuite) TestByNodeID() { // evaluating the chunk assignment // each verifier should have two certain chunks based on the assignment - for i := range size { + for i := 0; i < size; i++ { assignedChunks := assignment.ByNodeID(ids[i].NodeID) require.Len(a.T(), assignedChunks, 2) c, ok := chunks.ByIndex(uint64(i)) @@ -314,7 +314,7 @@ func (a *PublicAssignmentTestSuite) TestCacheAssignment() { // chunks to make them distinct from each other. func (a *PublicAssignmentTestSuite) CreateChunks(num int, t *testing.T) flow.ChunkList { list := flow.ChunkList{} - for i := range num { + for i := 0; i < num; i++ { // creates random state for each chunk // to provide random ordering after sorting var state flow.StateCommitment diff --git a/module/component/component_manager_test.go b/module/component/component_manager_test.go index 09c2df58ef2..1431abdd4c0 100644 --- a/module/component/component_manager_test.go +++ b/module/component/component_manager_test.go @@ -3,7 +3,6 @@ package component_test import ( "context" "fmt" - "slices" "testing" "time" @@ -64,7 +63,12 @@ func (s WorkerState) String() string { type WorkerStateList []WorkerState func (wsl WorkerStateList) Contains(ws WorkerState) bool { - return slices.Contains(wsl, ws) + for _, s := range wsl { + if s == ws { + return true + } + } + return false } type WorkerStateTransition int @@ -381,9 +385,9 @@ type ComponentManagerMachine struct { workerStates []WorkerState resetChannelReadTimeout func() - assertClosed func(t *rapid.T, ch <-chan struct{}, msgAndArgs ...any) - assertNotClosed func(t *rapid.T, ch <-chan struct{}, msgAndArgs ...any) - assertErrorThrownMatches func(t *rapid.T, err error, msgAndArgs ...any) + assertClosed func(t *rapid.T, ch <-chan struct{}, msgAndArgs ...interface{}) + assertNotClosed func(t *rapid.T, ch <-chan struct{}, msgAndArgs ...interface{}) + assertErrorThrownMatches func(t *rapid.T, err error, msgAndArgs ...interface{}) assertErrorNotThrown func(t *rapid.T) cancelGenerator *rapid.Generator[bool] @@ -430,7 +434,7 @@ func (c *ComponentManagerMachine) init(t *rapid.T) { channelReadTimeout = ctx.Done() } - c.assertClosed = func(t *rapid.T, ch <-chan struct{}, msgAndArgs ...any) { + c.assertClosed = func(t *rapid.T, ch <-chan struct{}, msgAndArgs ...interface{}) { select { case <-ch: default: @@ -442,7 +446,7 @@ func (c *ComponentManagerMachine) init(t *rapid.T) { } } - c.assertNotClosed = func(t *rapid.T, ch <-chan struct{}, msgAndArgs ...any) { + c.assertNotClosed = func(t *rapid.T, ch <-chan struct{}, msgAndArgs ...interface{}) { select { case <-ch: assert.Fail(t, "channel is closed", msgAndArgs...) @@ -455,7 +459,7 @@ func (c *ComponentManagerMachine) init(t *rapid.T) { } } - c.assertErrorThrownMatches = func(t *rapid.T, err error, msgAndArgs ...any) { + c.assertErrorThrownMatches = func(t *rapid.T, err error, msgAndArgs ...interface{}) { if signalerErr == nil { select { case signalerErr = <-errChan: @@ -493,7 +497,7 @@ func (c *ComponentManagerMachine) init(t *rapid.T) { cmb := component.NewComponentManagerBuilder() - for i := range numWorkers { + for i := 0; i < numWorkers; i++ { wtc, wtp := MakeWorkerTransitionFuncs() c.workerTransitionConsumers[i] = wtc cmb.AddWorker(ComponentWorker(t, i, wtp)) @@ -502,7 +506,7 @@ func (c *ComponentManagerMachine) init(t *rapid.T) { c.cm = cmb.Build() c.cm.Start(signalerCtx) - for i := range numWorkers { + for i := 0; i < numWorkers; i++ { c.workerStates[i] = WorkerStartingUp } } @@ -527,6 +531,8 @@ func (c *ComponentManagerMachine) ExecuteStateTransition(t *rapid.T) { } for i, workerId := range st.workerIDs { + i := i + workerId := workerId addTransition(func() { wst := st.workerTransitions[i] t.Logf("executing worker %v transition: %v\n", workerId, wst) @@ -648,7 +654,7 @@ func TestComponentManagerShutdown(t *testing.T) { // run the test many times to reproduce consistently func TestComponentManagerShutdown_100(t *testing.T) { - for range 100 { + for i := 0; i < 100; i++ { TestComponentManagerShutdown(t) } } diff --git a/module/component/run_component_test.go b/module/component/run_component_test.go index f313ad706ff..c26e180d9bd 100644 --- a/module/component/run_component_test.go +++ b/module/component/run_component_test.go @@ -177,7 +177,7 @@ func (c *ConcurrentErroringComponent) Start(ctx irrecoverable.SignalerContext) { c.ready.Add(2) c.done.Add(2) - for range 2 { + for i := 0; i < 2; i++ { go func() { c.ready.Done() defer c.done.Done() @@ -298,7 +298,8 @@ func TestRunComponentShutdownError(t *testing.T) { } func TestRunComponentConcurrentError(t *testing.T) { - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() componentFactory := func() (component.Component, error) { return NewConcurrentErroringComponent(100 * time.Millisecond), nil @@ -321,7 +322,8 @@ func TestRunComponentConcurrentError(t *testing.T) { } func TestRunComponentNoError(t *testing.T) { - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() componentFactory := func() (component.Component, error) { return NewNonErroringComponent(100 * time.Millisecond), nil @@ -363,7 +365,8 @@ func TestRunComponentFactoryError(t *testing.T) { return component.ErrorHandlingStop } - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() err := component.RunComponent(ctx, componentFactory, onError) require.ErrorIs(t, err, ErrCouldNotCreateComponent) diff --git a/module/dkg/broker_test.go b/module/dkg/broker_test.go index 4b5885c93a2..566fcb5ca23 100644 --- a/module/dkg/broker_test.go +++ b/module/dkg/broker_test.go @@ -282,8 +282,8 @@ func TestPoll(t *testing.T) { blockID := unittest.IdentifierFixture() bcastMsgs := []msg.BroadcastDKGMessage{} - for i := range 3 { - bmsg, err := sender.prepareBroadcastMessage(fmt.Appendf(nil, "msg%d", i)) + for i := 0; i < 3; i++ { + bmsg, err := sender.prepareBroadcastMessage([]byte(fmt.Sprintf("msg%d", i))) require.NoError(t, err) bmsg.NodeID = committee[0].NodeID bcastMsgs = append(bcastMsgs, bmsg) diff --git a/module/dkg/controller_test.go b/module/dkg/controller_test.go index 39ee830764a..22f8ec6a100 100644 --- a/module/dkg/controller_test.go +++ b/module/dkg/controller_test.go @@ -229,7 +229,7 @@ func initNodes(t *testing.T, n int, phase1Duration, phase2Duration, phase3Durati // Create the channels through which the nodes will communicate privateChannels := make([]chan msg.PrivDKGMessageIn, 0, n) broadcastChannels := make([]chan msg.BroadcastDKGMessage, 0, n) - for range n { + for i := 0; i < n; i++ { privateChannels = append(privateChannels, make(chan msg.PrivDKGMessageIn, 5*n*n)) broadcastChannels = append(broadcastChannels, make(chan msg.BroadcastDKGMessage, 5*n*n)) } @@ -237,7 +237,7 @@ func initNodes(t *testing.T, n int, phase1Duration, phase2Duration, phase3Durati nodes := make([]*node, 0, n) // Setup - for i := range n { + for i := 0; i < n; i++ { logger := zerolog.New(os.Stderr).With().Int("id", i).Logger() broker := &broker{ @@ -309,7 +309,7 @@ func checkArtifacts(t *testing.T, nodes []*node, totalNodes int) { require.Len(t, publicKeys, totalNodes) - for j := range totalNodes { + for j := 0; j < totalNodes; j++ { if !refPublicKeys[j].Equals(publicKeys[j]) { t.Fatalf("node %d has a different pubs[%d] than node 0: %s, %s", i, diff --git a/module/epochs/errors.go b/module/epochs/errors.go index 9554f0d877f..34035635ed6 100644 --- a/module/epochs/errors.go +++ b/module/epochs/errors.go @@ -21,7 +21,7 @@ func (err ClusterQCNoVoteError) Unwrap() error { return err.Err } -func NewClusterQCNoVoteErrorf(msg string, args ...any) ClusterQCNoVoteError { +func NewClusterQCNoVoteErrorf(msg string, args ...interface{}) ClusterQCNoVoteError { return ClusterQCNoVoteError{ Err: fmt.Errorf(msg, args...), } diff --git a/module/epochs/machine_account_test.go b/module/epochs/machine_account_test.go index ac3fc7996bd..2c6bbec9c3c 100644 --- a/module/epochs/machine_account_test.go +++ b/module/epochs/machine_account_test.go @@ -169,7 +169,7 @@ func TestMachineAccountValidatorBackoff_Overflow(t *testing.T) { lastWait, stop := backoff.Next() assert.False(t, stop) - for range 100 { + for i := 0; i < 100; i++ { wait, stop := backoff.Next() assert.False(t, stop) // the backoff value should either: diff --git a/module/execution/scripts_test.go b/module/execution/scripts_test.go index 9398d504f04..3cb832e119d 100644 --- a/module/execution/scripts_test.go +++ b/module/execution/scripts_test.go @@ -49,7 +49,7 @@ type scriptTestSuite struct { func (s *scriptTestSuite) TestScriptExecution() { s.Run("Simple Script Execution", func() { number := int64(42) - code := fmt.Appendf(nil, "access(all) fun main(): Int { return %d; }", number) + code := []byte(fmt.Sprintf("access(all) fun main(): Int { return %d; }", number)) result, err := s.scripts.ExecuteAtBlockHeight(context.Background(), code, nil, s.height) s.Require().NoError(err) @@ -59,10 +59,10 @@ func (s *scriptTestSuite) TestScriptExecution() { }) s.Run("Get Block", func() { - code := fmt.Appendf(nil, `access(all) fun main(): UInt64 { + code := []byte(fmt.Sprintf(`access(all) fun main(): UInt64 { getBlock(at: %d)! return getCurrentBlock().height - }`, s.height) + }`, s.height)) result, err := s.scripts.ExecuteAtBlockHeight(context.Background(), code, nil, s.height) s.Require().NoError(err) @@ -441,7 +441,7 @@ func transferTokensTx(chain flow.Chain) *flow.TransactionBodyBuilder { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) return flow.NewTransactionBodyBuilder(). - SetScript(fmt.Appendf(nil, + SetScript([]byte(fmt.Sprintf( ` // This transaction is a template for a transaction that // could be used by anyone to send tokens to another account @@ -483,6 +483,6 @@ func transferTokensTx(chain flow.Chain) *flow.TransactionBodyBuilder { }`, sc.FungibleToken.Address.Hex(), sc.FlowToken.Address.Hex(), - ), + )), ) } diff --git a/module/executiondatasync/execution_data/store.go b/module/executiondatasync/execution_data/store.go index 55c3416b155..e9ca87d4b54 100644 --- a/module/executiondatasync/execution_data/store.go +++ b/module/executiondatasync/execution_data/store.go @@ -154,7 +154,10 @@ func (s *store) addBlobs(ctx context.Context, v any) ([]cid.Cid, error) { // next, chunk the data into blobs of size up to maxBlobSize for len(data) > 0 { - blobLen := min(len(data), s.maxBlobSize) + blobLen := s.maxBlobSize + if len(data) < blobLen { + blobLen = len(data) + } blob := blobs.NewBlob(data[:blobLen]) data = data[blobLen:] diff --git a/module/executiondatasync/execution_data/store_test.go b/module/executiondatasync/execution_data/store_test.go index 4f8c07c01fc..ff475855447 100644 --- a/module/executiondatasync/execution_data/store_test.go +++ b/module/executiondatasync/execution_data/store_test.go @@ -31,7 +31,7 @@ func getExecutionDataStore(blobstore blobs.Blobstore, serializer execution_data. func generateBlockExecutionData(t *testing.T, numChunks int, minSerializedSizePerChunk uint64) *execution_data.BlockExecutionData { ceds := make([]*execution_data.ChunkExecutionData, numChunks) - for i := range numChunks { + for i := 0; i < numChunks; i++ { ceds[i] = unittest.ChunkExecutionDataFixture(t, int(minSerializedSizePerChunk)) } @@ -84,14 +84,14 @@ func TestHappyPath(t *testing.T) { type randomSerializer struct{} -func (rs *randomSerializer) Serialize(w io.Writer, v any) error { +func (rs *randomSerializer) Serialize(w io.Writer, v interface{}) error { data := make([]byte, 1024) _, _ = rand.Read(data) _, err := w.Write(data) return err } -func (rs *randomSerializer) Deserialize(r io.Reader) (any, error) { +func (rs *randomSerializer) Deserialize(r io.Reader) (interface{}, error) { return nil, fmt.Errorf("not implemented") } @@ -106,7 +106,7 @@ func newCorruptedTailSerializer(numChunks int) *corruptedTailSerializer { } } -func (cts *corruptedTailSerializer) Serialize(w io.Writer, v any) error { +func (cts *corruptedTailSerializer) Serialize(w io.Writer, v interface{}) error { if _, ok := v.(*execution_data.ChunkExecutionData); ok { cts.i++ if cts.i == cts.corruptedChunk { @@ -128,7 +128,7 @@ func (cts *corruptedTailSerializer) Serialize(w io.Writer, v any) error { return execution_data.DefaultSerializer.Serialize(w, v) } -func (cts *corruptedTailSerializer) Deserialize(r io.Reader) (any, error) { +func (cts *corruptedTailSerializer) Deserialize(r io.Reader) (interface{}, error) { return nil, fmt.Errorf("not implemented") } diff --git a/module/executiondatasync/optimistic_sync/execution_result_query_provider/execution_result_query_provider_test.go b/module/executiondatasync/optimistic_sync/execution_result_query_provider/execution_result_query_provider_test.go index 7b96472f246..23f388efb91 100644 --- a/module/executiondatasync/optimistic_sync/execution_result_query_provider/execution_result_query_provider_test.go +++ b/module/executiondatasync/optimistic_sync/execution_result_query_provider/execution_result_query_provider_test.go @@ -96,7 +96,7 @@ func (suite *ExecutionResultQueryProviderSuite) TestExecutionResultQuery() { provider := suite.createProvider(flow.IdentifierList{}, optimistic_sync.Criteria{}) receipts := make(flow.ExecutionReceiptList, totalReceipts) - for i := range totalReceipts { + for i := 0; i < totalReceipts; i++ { r := unittest.ReceiptForBlockFixture(block) r.ExecutorID = allExecutionNodes[i].NodeID r.ExecutionResult = *executionResult @@ -128,7 +128,7 @@ func (suite *ExecutionResultQueryProviderSuite) TestExecutionResultQuery() { otherResult := unittest.ExecutionResultFixture() // Create 3 receipts with the same result (executionResult) and 2 with a different result (otherResult) receipts := make(flow.ExecutionReceiptList, totalReceipts) - for i := range 3 { + for i := 0; i < 3; i++ { r := unittest.ReceiptForBlockFixture(block) r.ExecutorID = allExecutionNodes[i].NodeID r.ExecutionResult = *executionResult @@ -183,7 +183,7 @@ func (suite *ExecutionResultQueryProviderSuite) TestExecutionResultQuery() { suite.Run("required executors not found returns error", func() { provider := suite.createProvider(flow.IdentifierList{}, optimistic_sync.Criteria{}) receipts := make(flow.ExecutionReceiptList, totalReceipts) - for i := range totalReceipts { + for i := 0; i < totalReceipts; i++ { r := unittest.ReceiptForBlockFixture(block) r.ExecutorID = allExecutionNodes[i].NodeID r.ExecutionResult = *executionResult @@ -245,7 +245,7 @@ func (suite *ExecutionResultQueryProviderSuite) TestPreferredAndRequiredExecutio numReceipts := 6 // Create receipts from the first `numReceipts` execution nodes receipts := make(flow.ExecutionReceiptList, numReceipts) - for i := range numReceipts { + for i := 0; i < numReceipts; i++ { r := unittest.ReceiptForBlockFixture(block) r.ExecutorID = allExecutionNodes[i].NodeID r.ExecutionResult = *executionResult diff --git a/module/executiondatasync/tracker/storage.go b/module/executiondatasync/tracker/storage.go index 5740218c553..c7677f79ca7 100644 --- a/module/executiondatasync/tracker/storage.go +++ b/module/executiondatasync/tracker/storage.go @@ -349,7 +349,10 @@ func (s *storage) trackBlobs(blockHeight uint64, cids ...cid.Cid) error { } for len(cids) > 0 { - batchSize := min(len(cids), cidsPerBatch) + batchSize := cidsPerBatch + if len(cids) < batchSize { + batchSize = len(cids) + } batch := cids[:batchSize] if err := retryOnConflict(s.db, func(txn *badger.Txn) error { diff --git a/module/finalizer/consensus/finalizer_test.go b/module/finalizer/consensus/finalizer_test.go index c3fcbf857ca..965654328dc 100644 --- a/module/finalizer/consensus/finalizer_test.go +++ b/module/finalizer/consensus/finalizer_test.go @@ -42,7 +42,7 @@ func TestMakeFinalValidChain(t *testing.T) { parent := final var pending []*flow.Header total := 8 - for range total { + for i := 0; i < total; i++ { header := unittest.BlockHeaderFixture() header.Height = parent.Height + 1 header.ParentID = parent.ID() @@ -56,7 +56,7 @@ func TestMakeFinalValidChain(t *testing.T) { // make sure we get a finalize call for the blocks that we want to cutoff := total - 3 var lastID flow.Identifier - for i := range cutoff { + for i := 0; i < cutoff; i++ { state.On("Finalize", mock.Anything, pending[i].ID()).Return(nil) lastID = pending[i].ID() } diff --git a/module/forest/concurrency_helpers_test.go b/module/forest/concurrency_helpers_test.go index 6f937d86aa5..fb73b7ac1d0 100644 --- a/module/forest/concurrency_helpers_test.go +++ b/module/forest/concurrency_helpers_test.go @@ -139,7 +139,7 @@ func Test_VertexIteratorConcurrencySafe(t *testing.T) { go func() { // Go Routine 1 <-start - for i := range 1000 { + for i := 0; i < 1000; i++ { // add additional child vertex of [C] var v Vertex = NewVertexMock(fmt.Sprintf("v%03d", i), 3, "C", 2) err := forest.VerifyAndAddVertex(&v) diff --git a/module/forest/vertex.go b/module/forest/vertex.go index a9f3be2be9e..8f5d5e94a42 100644 --- a/module/forest/vertex.go +++ b/module/forest/vertex.go @@ -120,7 +120,7 @@ func IsInvalidVertexError(err error) bool { // NewInvalidVertexErrorf instantiates an [InvalidVertexError]. The // inputs `msg` and `args` follow the pattern of [fmt.Errorf]. -func NewInvalidVertexErrorf(vertex Vertex, msg string, args ...any) InvalidVertexError { +func NewInvalidVertexErrorf(vertex Vertex, msg string, args ...interface{}) InvalidVertexError { return InvalidVertexError{ Vertex: vertex, msg: fmt.Sprintf(msg, args...), diff --git a/module/id/filtered_provider_test.go b/module/id/filtered_provider_test.go index 0b0143e918a..bc34eebe712 100644 --- a/module/id/filtered_provider_test.go +++ b/module/id/filtered_provider_test.go @@ -14,18 +14,18 @@ import ( func TestFilteredIdentitiesProvider(t *testing.T) { identities := make([]*flow.Identity, 10) - for i := range identities { + for i := 0; i < len(identities); i++ { identities[i] = unittest.IdentityFixture() } identifiers := (flow.IdentityList)(identities).NodeIDs() oddIdentifiers := make([]flow.Identifier, 5) - for j := range 5 { + for j := 0; j < 5; j++ { oddIdentifiers[j] = identifiers[2*j+1] } oddIdentities := make([]*flow.Identity, 5) - for j := range 5 { + for j := 0; j < 5; j++ { oddIdentities[j] = identities[2*j+1] } diff --git a/module/id/fixed_provider_test.go b/module/id/fixed_provider_test.go index 68bf808d992..b53e84c7d2d 100644 --- a/module/id/fixed_provider_test.go +++ b/module/id/fixed_provider_test.go @@ -2,7 +2,6 @@ package id import ( "math/rand" - "slices" "testing" "github.com/onflow/flow-go/model/flow" @@ -15,7 +14,7 @@ import ( func TestFixedIdentifierProvider(t *testing.T) { identifiers := make([]flow.Identifier, 10) - for i := range identifiers { + for i := 0; i < len(identifiers); i++ { identifiers[i] = unittest.IdentifierFixture() } @@ -31,7 +30,7 @@ func TestFixedIdentifierProvider(t *testing.T) { func TestFixedIdentitiesProvider(t *testing.T) { identities := make([]*flow.Identity, 10) - for i := range identities { + for i := 0; i < len(identities); i++ { identities[i] = unittest.IdentityFixture() } @@ -46,9 +45,19 @@ func TestFixedIdentitiesProvider(t *testing.T) { } func contains(a []flow.Identifier, b flow.Identifier) bool { - return slices.Contains(a, b) + for _, i := range a { + if b == i { + return true + } + } + return false } func idContains(a []*flow.Identity, b *flow.Identity) bool { - return slices.Contains(a, b) + for _, i := range a { + if b == i { + return true + } + } + return false } diff --git a/module/jobqueue/consumer_behavior_test.go b/module/jobqueue/consumer_behavior_test.go index 2844210bc88..8e6cfe7eed8 100644 --- a/module/jobqueue/consumer_behavior_test.go +++ b/module/jobqueue/consumer_behavior_test.go @@ -491,7 +491,7 @@ func testWorkOnNextAfterFastforward(t *testing.T) { func testStopRunning(t *testing.T) { runWith(t, DefaultIndex, func(c module.JobConsumer, cp storage.ConsumerProgress, w *mockWorker, j *jobqueue.MockJobs, db *pebble.DB) { require.NoError(t, c.Start()) - for range 4 { + for i := 0; i < 4; i++ { require.NoError(t, j.PushOne()) c.Check() } @@ -525,11 +525,13 @@ func testConcurrency(t *testing.T) { // Pushing job and checking job concurrently var pushAll sync.WaitGroup - for range 100 { - pushAll.Go(func() { + for i := 0; i < 100; i++ { + pushAll.Add(1) + go func() { require.NoError(t, j.PushOne()) c.Check() - }) + pushAll.Done() + }() } // wait until pushed all diff --git a/module/jobqueue/sealed_header_reader_test.go b/module/jobqueue/sealed_header_reader_test.go index 74ac3159a42..735ed5ab09b 100644 --- a/module/jobqueue/sealed_header_reader_test.go +++ b/module/jobqueue/sealed_header_reader_test.go @@ -62,7 +62,7 @@ func RunWithReader( var seals []*flow.Header parent := unittest.Block.Genesis(flow.Emulator).ToHeader() - for i := range blockCount { + for i := 0; i < blockCount; i++ { seals = []*flow.Header{parent} height := uint64(i) + 1 diff --git a/module/jobqueue/workerpool.go b/module/jobqueue/workerpool.go index 99e00166ce9..fe7b6d05c2e 100644 --- a/module/jobqueue/workerpool.go +++ b/module/jobqueue/workerpool.go @@ -46,7 +46,7 @@ func NewWorkerPool(processor JobProcessor, notify NotifyDone, workers uint64) *W builder := component.NewComponentManagerBuilder() - for range workers { + for i := uint64(0); i < workers; i++ { builder.AddWorker(func(ctx irrecoverable.SignalerContext, ready component.ReadyFunc) { ready() w.workerLoop(ctx) diff --git a/module/lifecycle/lifecycle_test.go b/module/lifecycle/lifecycle_test.go index fd6b253c7de..ed3707960a2 100644 --- a/module/lifecycle/lifecycle_test.go +++ b/module/lifecycle/lifecycle_test.go @@ -26,7 +26,7 @@ func (suite *LifecycleManagerSuite) TestConcurrentStart() { var numStarts uint32 lm := suite.lm - for range 10 { + for i := 0; i < 10; i++ { go func() { lm.OnStart(func() { atomic.AddUint32(&numStarts, 1) @@ -48,7 +48,7 @@ func (suite *LifecycleManagerSuite) TestConcurrentStop() { var numStops uint32 lm := suite.lm - for range 10 { + for i := 0; i < 10; i++ { go func() { lm.OnStop(func() { atomic.AddUint32(&numStops, 1) diff --git a/module/limiters/concurrency_limiter_test.go b/module/limiters/concurrency_limiter_test.go index bae54995922..4af4f29208b 100644 --- a/module/limiters/concurrency_limiter_test.go +++ b/module/limiters/concurrency_limiter_test.go @@ -135,8 +135,10 @@ func TestConcurrencyLimiter_Acquire_ConcurrentCalls(t *testing.T) { start := make(chan struct{}) - for range totalGoroutines { - wg.Go(func() { + for i := 0; i < totalGoroutines; i++ { + wg.Add(1) + go func() { + defer wg.Done() <-start if limiter.Acquire() { n := current.Add(1) @@ -150,7 +152,7 @@ func TestConcurrencyLimiter_Acquire_ConcurrentCalls(t *testing.T) { current.Add(-1) limiter.Release() } - }) + }() } close(start) @@ -188,8 +190,10 @@ func TestConcurrencyLimiter_Allow_ConcurrentCalls(t *testing.T) { start := make(chan struct{}) - for range totalGoroutines { - wg.Go(func() { + for i := 0; i < totalGoroutines; i++ { + wg.Add(1) + go func() { + defer wg.Done() <-start limiter.Allow(func() { n := current.Add(1) @@ -204,7 +208,7 @@ func TestConcurrencyLimiter_Allow_ConcurrentCalls(t *testing.T) { time.Sleep(time.Millisecond) // hold the slot briefly current.Add(-1) }) - }) + }() } close(start) diff --git a/module/mempool/chunk_requests.go b/module/mempool/chunk_requests.go index 44c65bd9078..5962ad6ef56 100644 --- a/module/mempool/chunk_requests.go +++ b/module/mempool/chunk_requests.go @@ -27,7 +27,11 @@ func ExponentialUpdater(multiplier float64, maxInterval time.Duration, minInterv if float64(retryAfter) >= float64(maxInterval)/multiplier { retryAfter = maxInterval } else { - retryAfter = max(time.Duration(float64(retryAfter)*multiplier), minInterval) + retryAfter = time.Duration(float64(retryAfter) * multiplier) + + if retryAfter < minInterval { + retryAfter = minInterval + } } return attempts + 1, retryAfter, true diff --git a/module/mempool/consensus/exec_fork_suppressor_test.go b/module/mempool/consensus/exec_fork_suppressor_test.go index 81ebe5acaff..a4d565402a1 100644 --- a/module/mempool/consensus/exec_fork_suppressor_test.go +++ b/module/mempool/consensus/exec_fork_suppressor_test.go @@ -339,7 +339,7 @@ func Test_AddRemove_SmokeTest(t *testing.T) { // * add 10 seals to mempool, which should eject 7 seals // * test that ejected seals are not in mempool anymore // * remove remaining seals - for i := range 100 { + for i := 0; i < 100; i++ { seals := unittest.IncorporatedResultSeal.Fixtures(10) for j, s := range seals { // fix height for each seal diff --git a/module/mempool/consensus/receipt_equivalence_class.go b/module/mempool/consensus/receipt_equivalence_class.go index afa6f93836e..c112de94459 100644 --- a/module/mempool/consensus/receipt_equivalence_class.go +++ b/module/mempool/consensus/receipt_equivalence_class.go @@ -62,7 +62,7 @@ func (rsr *ReceiptsOfSameResult) AddReceipt(receipt *flow.ExecutionReceipt) (uin // - error in case of unforeseen problems func (rsr *ReceiptsOfSameResult) AddReceipts(receipts ...*flow.ExecutionReceipt) (uint, error) { receiptsAdded := uint(0) - for i := range receipts { + for i := 0; i < len(receipts); i++ { added, err := rsr.AddReceipt(receipts[i]) if err != nil { return receiptsAdded, fmt.Errorf("failed to add receipt (%x) to equivalence class: %w", receipts[i].ID(), err) diff --git a/module/mempool/epochs/transactions_test.go b/module/mempool/epochs/transactions_test.go index f66becbcc16..07bd798d9c8 100644 --- a/module/mempool/epochs/transactions_test.go +++ b/module/mempool/epochs/transactions_test.go @@ -38,12 +38,14 @@ func TestMultipleEpochs(t *testing.T) { pools := epochs.NewTransactionPools(create) var wg sync.WaitGroup - for range 10 { - wg.Go(func() { + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { + defer wg.Done() epoch := rand.Uint64() var transactions []*flow.TransactionBody - for range 10 { + for i := 0; i < 10; i++ { pool := pools.ForEpoch(epoch) assert.Equal(t, uint(len(transactions)), pool.Size()) for _, tx := range transactions { @@ -54,7 +56,7 @@ func TestMultipleEpochs(t *testing.T) { transactions = append(transactions, &tx) pool.Add(tx.ID(), &tx) } - }) + }() } unittest.AssertReturnsBefore(t, wg.Wait, time.Second) } @@ -70,7 +72,7 @@ func TestCombinedSize(t *testing.T) { transactionsPerEpoch := rand.Uint64() % 10 expected := uint(nEpochs * transactionsPerEpoch) - for epoch := range nEpochs { + for epoch := uint64(0); epoch < nEpochs; epoch++ { pool := pools.ForEpoch(epoch) for i := 0; i < int(transactionsPerEpoch); i++ { next := unittest.TransactionBodyFixture() diff --git a/module/mempool/herocache/backdata/cache.go b/module/mempool/herocache/backdata/cache.go index b11e7b010ab..cf6c3843b38 100644 --- a/module/mempool/herocache/backdata/cache.go +++ b/module/mempool/herocache/backdata/cache.go @@ -360,7 +360,7 @@ func (c *Cache[V]) put(key flow.Identifier, value V) bool { // The boolean return value determines whether an value with given id exists in the BackData. func (c *Cache[V]) get(key flow.Identifier) (value V, bckIndex bucketIndex, sltIndex slotIndex, ok bool) { entityId32of256, b := c.entityId32of256AndBucketIndex(key) - for s := range slotIndex(slotsPerBucket) { + for s := slotIndex(0); s < slotIndex(slotsPerBucket); s++ { if c.buckets[b].slots[s].valueId32of256 != entityId32of256 { continue } @@ -417,7 +417,7 @@ func (c *Cache[V]) slotIndexInBucket(b bucketIndex, slotId sha32of256, entityId oldestSlotInBucket := c.slotCount + 1 // initializes the oldest slot to current max. - for s := range slotIndex(slotsPerBucket) { + for s := slotIndex(0); s < slotIndex(slotsPerBucket); s++ { if c.buckets[b].slots[s].slotAge < oldestSlotInBucket { // record slot s as oldest slot oldestSlotInBucket = c.buckets[b].slots[s].slotAge diff --git a/module/mempool/herocache/backdata/cache_test.go b/module/mempool/herocache/backdata/cache_test.go index efe843649b1..c3bd2801991 100644 --- a/module/mempool/herocache/backdata/cache_test.go +++ b/module/mempool/herocache/backdata/cache_test.go @@ -509,9 +509,11 @@ func TestArrayBackData_All(t *testing.T) { testIdentifiersMatchCount(t, bd.Keys(), entities, int(tc.limit)) } else { // in LRU ejection mode we match All items based on a from index (i.e., last "from" items). - from := max(int(tc.items)-int(tc.limit), + from := int(tc.items) - int(tc.limit) + if from < 0 { // we are below limit, hence we start matching from index 0 - 0) + from = 0 + } testMapMatchFrom(t, bd.All(), entities, from) testEntitiesMatchFrom(t, bd.Values(), entities, from) testIdentifiersMatchFrom(t, bd.Keys(), entities, from) diff --git a/module/mempool/herocache/backdata/heropool/pool_test.go b/module/mempool/herocache/backdata/heropool/pool_test.go index 21a65b31c13..2df32131bbe 100644 --- a/module/mempool/herocache/backdata/heropool/pool_test.go +++ b/module/mempool/herocache/backdata/heropool/pool_test.go @@ -284,12 +284,12 @@ func testAddRemoveEntities(t *testing.T, limit uint32, entityCount uint32, eject // this map maintains entities currently stored in the pool. addedEntities := make(map[flow.Identifier]int) addedEntitiesInPool := make(map[flow.Identifier]EIndex) - for range numberOfOperations { + for i := 0; i < numberOfOperations; i++ { // choose between Add and Remove with a probability of probabilityOfAdding and 1-probabilityOfAdding respectively. if float32(randomIntN(math.MaxInt32))/math.MaxInt32 < probabilityOfAdding || len(addedEntities) == 0 { // keeps finding an entity to add until it finds one that is not already in the pool. found := false - for range retryLimit { + for retryTime := 0; retryTime < retryLimit; retryTime++ { toAddIndex := randomIntN(int(entityCount)) _, found = addedEntities[entities[toAddIndex].Identifier] if !found { @@ -376,7 +376,7 @@ func testInvalidatingHead(t *testing.T, pool *Pool[flow.Identifier, *unittest.Mo freeListInitialSize := len(pool.poolEntities) - totalEntitiesStored // (i+1) keeps total invalidated (head) entities. - for i := range totalEntitiesStored { + for i := 0; i < totalEntitiesStored; i++ { headIndex := pool.invalidateUsedHead() // head index should be moved to the next index after each head invalidation. require.Equal(t, entities[i], headIndex) @@ -462,7 +462,7 @@ func testInvalidatingHead(t *testing.T, pool *Pool[flow.Identifier, *unittest.Mo func testInvalidatingTail(t *testing.T, pool *Pool[flow.Identifier, *unittest.MockEntity], entities []*unittest.MockEntity) { size := len(entities) offset := len(pool.poolEntities) - size - for i := range size { + for i := 0; i < size; i++ { // invalidates tail index tailIndex := pool.states[stateUsed].tail require.Equal(t, EIndex(size-1-i), tailIndex) @@ -833,7 +833,7 @@ func tailAccessibleFromHead(t *testing.T, headSliceIndex EIndex, tailSliceIndex seen := make(map[EIndex]struct{}) index := headSliceIndex - for i := range steps { + for i := uint32(0); i < steps; i++ { if i == steps-1 { require.Equal(t, tailSliceIndex, index, "tail not reachable after steps steps") return @@ -853,7 +853,7 @@ func headAccessibleFromTail(t *testing.T, headSliceIndex EIndex, tailSliceIndex seen := make(map[EIndex]struct{}) index := tailSliceIndex - for i := range total { + for i := uint32(0); i < total; i++ { if i == total-1 { require.Equal(t, headSliceIndex, index, "head not reachable after total steps") return @@ -875,7 +875,7 @@ func checkEachEntityIsInFreeOrUsedState(t *testing.T, pool *Pool[flow.Identifier // check elelments nodesInFree := discoverEntitiesBelongingToStateList(t, pool, stateFree) nodesInUsed := discoverEntitiesBelongingToStateList(t, pool, stateUsed) - for i := range pool_capacity { + for i := 0; i < pool_capacity; i++ { require.False(t, !nodesInFree[i] && !nodesInUsed[i], "Node is not in any state list") require.False(t, nodesInFree[i] && nodesInUsed[i], "Node is in two state lists at the same time") } diff --git a/module/mempool/herocache/dns_cache_test.go b/module/mempool/herocache/dns_cache_test.go index c69a7c423dc..0d08fb459ad 100644 --- a/module/mempool/herocache/dns_cache_test.go +++ b/module/mempool/herocache/dns_cache_test.go @@ -177,7 +177,7 @@ func TestDNSCache_LRU(t *testing.T) { require.Equal(t, uint(sizeLimit), txts) // only last 500 ip domains and txt records must be retained in the DNS cache - for i := range total { + for i := 0; i < total; i++ { if i < total-int(sizeLimit) { // old dns entries must be ejected // ip @@ -266,7 +266,7 @@ func TestDNSCache_Remove(t *testing.T) { require.Equal(t, uint(total-1), txts) // only last 500 ip domains and txt records must be retained in the DNS cache - for i := range total { + for i := 0; i < total; i++ { if i == 0 { // removed entries must no longer exist. // ip diff --git a/module/mempool/herocache/execution_data_test.go b/module/mempool/herocache/execution_data_test.go index 616e53fd5b3..c83a5b0e906 100644 --- a/module/mempool/herocache/execution_data_test.go +++ b/module/mempool/herocache/execution_data_test.go @@ -71,7 +71,7 @@ func TestBlockExecutionDataConcurrentWriteAndRead(t *testing.T) { wg.Add(total) // storing all cache - for i := range total { + for i := 0; i < total; i++ { go func(ed *execution_data.BlockExecutionDataEntity) { require.True(t, cache.Add(ed.BlockID, ed)) @@ -84,7 +84,7 @@ func TestBlockExecutionDataConcurrentWriteAndRead(t *testing.T) { wg.Add(total) // reading all cache - for i := range total { + for i := 0; i < total; i++ { go func(ed *execution_data.BlockExecutionDataEntity) { actual, ok := cache.Get(ed.BlockID) require.True(t, ok) @@ -104,7 +104,7 @@ func TestBlockExecutionDataAllReturnsInOrder(t *testing.T) { cache := herocache.NewBlockExecutionData(uint32(total), unittest.Logger(), metrics.NewNoopCollector()) // storing all cache - for i := range total { + for i := 0; i < total; i++ { require.True(t, cache.Add(execDatas[i].BlockID, execDatas[i])) ed, ok := cache.Get(execDatas[i].BlockID) require.True(t, ok) @@ -113,7 +113,7 @@ func TestBlockExecutionDataAllReturnsInOrder(t *testing.T) { // all cache must be retrieved in the same order as they are added all := cache.All() - for i := range total { + for i := 0; i < total; i++ { val, exists := all[execDatas[i].BlockID] require.True(t, exists) assert.Equal(t, execDatas[i], val) diff --git a/module/mempool/herocache/transactions_test.go b/module/mempool/herocache/transactions_test.go index b569fbc825b..6fbf710b949 100644 --- a/module/mempool/herocache/transactions_test.go +++ b/module/mempool/herocache/transactions_test.go @@ -69,7 +69,7 @@ func TestConcurrentWriteAndRead(t *testing.T) { wg.Add(total) // storing all transactions - for i := range total { + for i := 0; i < total; i++ { go func(tx flow.TransactionBody) { require.True(t, transactions.Add(tx.ID(), &tx)) @@ -82,7 +82,7 @@ func TestConcurrentWriteAndRead(t *testing.T) { wg.Add(total) // reading all transactions - for i := range total { + for i := 0; i < total; i++ { go func(tx flow.TransactionBody) { actual, ok := transactions.Get(tx.ID()) require.True(t, ok) @@ -102,7 +102,7 @@ func TestValuesReturnsInOrder(t *testing.T) { transactions := herocache.NewTransactions(uint32(total), unittest.Logger(), metrics.NewNoopCollector()) // storing all transactions - for i := range total { + for i := 0; i < total; i++ { require.True(t, transactions.Add(txs[i].ID(), &txs[i])) tx, ok := transactions.Get(txs[i].ID()) require.True(t, ok) @@ -111,7 +111,7 @@ func TestValuesReturnsInOrder(t *testing.T) { // all transactions must be retrieved in the same order as they are added all := transactions.Values() - for i := range total { + for i := 0; i < total; i++ { require.Equal(t, txs[i], *all[i]) } } diff --git a/module/mempool/queue/heroQueue_test.go b/module/mempool/queue/heroQueue_test.go index c027948e2a3..0107c789a56 100644 --- a/module/mempool/queue/heroQueue_test.go +++ b/module/mempool/queue/heroQueue_test.go @@ -37,7 +37,7 @@ func TestHeroQueue_Sequential(t *testing.T) { } // once queue meets the size limit, any extra push should fail. - for range 100 { + for i := 0; i < 100; i++ { entity := unittest.MockEntityFixture() require.False(t, q.Push(entity.Identifier, entity)) @@ -73,6 +73,7 @@ func TestHeroQueue_Concurrent(t *testing.T) { entities := unittest.EntityListFixture(uint(sizeLimit)) // pushing entities concurrently. for _, e := range entities { + e := e // suppress loop variable go func() { require.True(t, q.Push(e.Identifier, e)) pushWG.Done() @@ -82,7 +83,7 @@ func TestHeroQueue_Concurrent(t *testing.T) { // once queue meets the size limit, any extra push should fail. pushWG.Add(sizeLimit) - for range sizeLimit { + for i := 0; i < sizeLimit; i++ { go func() { entity := unittest.MockEntityFixture() require.False(t, q.Push(entity.Identifier, entity)) @@ -96,7 +97,7 @@ func TestHeroQueue_Concurrent(t *testing.T) { matchLock := &sync.Mutex{} // pop-ing entities concurrently. - for range sizeLimit { + for i := 0; i < sizeLimit; i++ { go func() { popedE, ok := q.Pop() require.True(t, ok) diff --git a/module/mempool/queue/heroStore_test.go b/module/mempool/queue/heroStore_test.go index a7567ec48af..209faee37cd 100644 --- a/module/mempool/queue/heroStore_test.go +++ b/module/mempool/queue/heroStore_test.go @@ -20,7 +20,7 @@ func TestHeroStore_Sequential(t *testing.T) { store := queue.NewHeroStore(uint32(sizeLimit), unittest.Logger(), metrics.NewNoopCollector()) messages := unittest.EngineMessageFixtures(sizeLimit) - for i := range sizeLimit { + for i := 0; i < sizeLimit; i++ { require.True(t, store.Put(messages[i])) // duplicate put should fail @@ -28,12 +28,12 @@ func TestHeroStore_Sequential(t *testing.T) { } // once store meets the size limit, any extra put should fail. - for range 100 { + for i := 0; i < 100; i++ { require.False(t, store.Put(unittest.EngineMessageFixture())) } // getting entities sequentially. - for i := range sizeLimit { + for i := 0; i < sizeLimit; i++ { msg, ok := store.Get() require.True(t, ok) require.Equal(t, messages[i], msg) @@ -56,6 +56,7 @@ func TestHeroStore_Concurrent(t *testing.T) { messages := unittest.EngineMessageFixtures(sizeLimit) // putting messages concurrently. for _, m := range messages { + m := m go func() { require.True(t, store.Put(m)) putWG.Done() @@ -65,7 +66,7 @@ func TestHeroStore_Concurrent(t *testing.T) { // once store meets the size limit, any extra put should fail. putWG.Add(sizeLimit) - for range sizeLimit { + for i := 0; i < sizeLimit; i++ { go func() { require.False(t, store.Put(unittest.EngineMessageFixture())) putWG.Done() @@ -78,7 +79,7 @@ func TestHeroStore_Concurrent(t *testing.T) { matchLock := &sync.Mutex{} // pop-ing entities concurrently. - for range sizeLimit { + for i := 0; i < sizeLimit; i++ { go func() { msg, ok := store.Get() require.True(t, ok) diff --git a/module/mempool/stdmap/backDataHeapBenchmark_test.go b/module/mempool/stdmap/backDataHeapBenchmark_test.go index 2179a5d41d7..79cff38abd0 100644 --- a/module/mempool/stdmap/backDataHeapBenchmark_test.go +++ b/module/mempool/stdmap/backDataHeapBenchmark_test.go @@ -222,7 +222,7 @@ func (b *baselineLRU[K, V]) Keys() []K { keys := make([]K, b.c.Len()) valueKeys := b.c.Keys() total := len(valueKeys) - for i := range total { + for i := 0; i < total; i++ { keys[i] = valueKeys[i] } return keys @@ -232,7 +232,7 @@ func (b *baselineLRU[K, V]) Values() []V { values := make([]V, b.c.Len()) valuesIds := b.c.Keys() total := len(valuesIds) - for i := range total { + for i := 0; i < total; i++ { entity, ok := b.Get(valuesIds[i]) if !ok { panic("could not retrieve entity from mempool") diff --git a/module/mempool/stdmap/backdata/mapBackData.go b/module/mempool/stdmap/backdata/mapBackData.go index f46ef6292af..ab86f468d36 100644 --- a/module/mempool/stdmap/backdata/mapBackData.go +++ b/module/mempool/stdmap/backdata/mapBackData.go @@ -1,7 +1,5 @@ package backdata -import "maps" - // MapBackData implements a map-based generic memory BackData backed by a Go map. // Note that this implementation is NOT thread-safe, and the higher-level Backend is responsible for concurrency management. type MapBackData[K comparable, V any] struct { @@ -98,7 +96,9 @@ func (b *MapBackData[K, V]) Size() uint { // All returns all stored key-value pairs as a map. func (b *MapBackData[K, V]) All() map[K]V { values := make(map[K]V) - maps.Copy(values, b.dataMap) + for key, value := range b.dataMap { + values[key] = value + } return values } diff --git a/module/mempool/stdmap/backend_test.go b/module/mempool/stdmap/backend_test.go index 91c94f1b1a7..73cd2c5ef6e 100644 --- a/module/mempool/stdmap/backend_test.go +++ b/module/mempool/stdmap/backend_test.go @@ -122,7 +122,7 @@ func TestBackend_RunLimitChecking(t *testing.T) { wg := sync.WaitGroup{} wg.Add(swarm) - for i := range swarm { + for i := 0; i < swarm; i++ { go func(x int) { // creates and adds a fake item to the mempool item := unittest.MockEntityFixture() @@ -170,7 +170,7 @@ func TestBackend_RegisterEjectionCallback(t *testing.T) { wg := sync.WaitGroup{} wg.Add(swarm) - for i := range swarm { + for i := 0; i < swarm; i++ { go func(x int) { // creates and adds a fake item to the mempool item := unittest.MockEntityFixture() diff --git a/module/mempool/stdmap/chunk_requests_test.go b/module/mempool/stdmap/chunk_requests_test.go index 3588bcb5e1f..6d9f3a897fd 100644 --- a/module/mempool/stdmap/chunk_requests_test.go +++ b/module/mempool/stdmap/chunk_requests_test.go @@ -121,7 +121,7 @@ func withUpdaterScenario(t *testing.T, chunks int, times int, updater mempool.Ch wg := &sync.WaitGroup{} wg.Add(times * chunks) for _, request := range chunkReqs { - for range times { + for i := 0; i < times; i++ { go func(chunkID flow.Identifier) { _, _, _, ok := requests.UpdateRequestHistory(chunkID, updater) require.True(t, ok) diff --git a/module/mempool/stdmap/eject_test.go b/module/mempool/stdmap/eject_test.go index 10ff7d024ea..a9ddefb7901 100644 --- a/module/mempool/stdmap/eject_test.go +++ b/module/mempool/stdmap/eject_test.go @@ -75,7 +75,7 @@ func TestLRUEjector_Track_Many(t *testing.T) { // creates and tracks 100 items size := 100 items := flow.IdentifierList{} - for range size { + for i := 0; i < size; i++ { var id flow.Identifier _, _ = crand.Read(id[:]) ejector.Track(id) @@ -183,7 +183,7 @@ func TestLRUEjector_UntrackEject(t *testing.T) { items := make(flow.IdentifierList, size) - for i := range size { + for i := 0; i < size; i++ { mockEntity := unittest.MockEntityFixture() require.True(t, backEnd.Add(mockEntity.Identifier, mockEntity)) @@ -211,7 +211,7 @@ func TestLRUEjector_EjectAll(t *testing.T) { items := make(flow.IdentifierList, size) - for i := range size { + for i := 0; i < size; i++ { mockEntity := unittest.MockEntityFixture() require.True(t, backEnd.Add(mockEntity.Identifier, mockEntity)) @@ -223,7 +223,7 @@ func TestLRUEjector_EjectAll(t *testing.T) { require.Equal(t, uint(size), backEnd.Size()) // ejects one by one - for i := range size { + for i := 0; i < size; i++ { id := Eject(ejector, backEnd) require.Equal(t, id, items[i]) } diff --git a/module/mempool/stdmap/identifier_map_test.go b/module/mempool/stdmap/identifier_map_test.go index 55983ad6715..f09a9ebd823 100644 --- a/module/mempool/stdmap/identifier_map_test.go +++ b/module/mempool/stdmap/identifier_map_test.go @@ -190,7 +190,7 @@ func TestCapacity(t *testing.T) { wg := sync.WaitGroup{} wg.Add(swarm) - for range swarm { + for i := 0; i < swarm; i++ { go func() { // adds an item on a separate goroutine key := unittest.IdentifierFixture() diff --git a/module/mempool/stdmap/incorporated_result_seals_test.go b/module/mempool/stdmap/incorporated_result_seals_test.go index 8295bd9e1ca..c9160cc606d 100644 --- a/module/mempool/stdmap/incorporated_result_seals_test.go +++ b/module/mempool/stdmap/incorporated_result_seals_test.go @@ -204,7 +204,7 @@ func TestIncorporatedResultSeals(t *testing.T) { pool := NewIncorporatedResultSeals(1000) seals := make([]*flow.IncorporatedResultSeal, 0, 100) - for i := range 100 { + for i := 0; i < 100; i++ { seal := unittest.IncorporatedResultSeal.Fixture(func(s *flow.IncorporatedResultSeal) { s.Header.Height = uint64(i) }) diff --git a/module/mempool/stdmap/pending_receipts_test.go b/module/mempool/stdmap/pending_receipts_test.go index 9e53b673636..6d5044c899f 100644 --- a/module/mempool/stdmap/pending_receipts_test.go +++ b/module/mempool/stdmap/pending_receipts_test.go @@ -65,29 +65,29 @@ func TestPendingReceipts(t *testing.T) { pool := NewPendingReceipts(headers, 100) rs := chainedReceipts(100) - for i := range 100 { + for i := 0; i < 100; i++ { rs[i] = unittest.ExecutionReceiptFixture() } - for i := range 100 { + for i := 0; i < 100; i++ { r := rs[i] ok := pool.Add(r) require.True(t, ok) } - for i := range 100 { + for i := 0; i < 100; i++ { r := rs[i] actual := pool.ByPreviousResultID(r.ExecutionResult.PreviousResultID) require.Equal(t, []*flow.ExecutionReceipt{r}, actual) } - for i := range 100 { + for i := 0; i < 100; i++ { r := rs[i] ok := pool.Remove(r.ID()) require.True(t, ok) } - for i := range 100 { + for i := 0; i < 100; i++ { r := rs[i] actual := pool.ByPreviousResultID(r.ExecutionResult.PreviousResultID) require.Equal(t, empty, actual) @@ -100,7 +100,7 @@ func TestPendingReceipts(t *testing.T) { parent := unittest.ExecutionReceiptFixture() parentID := parent.ID() rs := make([]*flow.ExecutionReceipt, 100) - for i := range 100 { + for i := 0; i < 100; i++ { rs[i] = unittest.ExecutionReceiptFixture(func(receipt *flow.ExecutionReceipt) { // having the same parent receipt.ExecutionResult.PreviousResultID = parentID @@ -120,11 +120,11 @@ func TestPendingReceipts(t *testing.T) { pool := NewPendingReceipts(headers, 60) rs := chainedReceipts(100) - for i := range 100 { + for i := 0; i < 100; i++ { rs[i] = unittest.ExecutionReceiptFixture() } - for i := range 100 { + for i := 0; i < 100; i++ { r := rs[i] ok := pool.Add(r) require.True(t, ok) @@ -133,7 +133,7 @@ func TestPendingReceipts(t *testing.T) { // adding 100 will cause 40 to be ejected, // since there are 60 left and be found total := 0 - for i := range 100 { + for i := 0; i < 100; i++ { r := rs[i] actual := pool.ByPreviousResultID(r.ExecutionResult.PreviousResultID) if len(actual) > 0 { @@ -144,7 +144,7 @@ func TestPendingReceipts(t *testing.T) { // since there are 60 left, should remove 60 in total total = 0 - for i := range 100 { + for i := 0; i < 100; i++ { ok := pool.Remove(rs[i].ID()) if ok { total++ @@ -157,7 +157,7 @@ func TestPendingReceipts(t *testing.T) { pool := NewPendingReceipts(headers, 100) rs := chainedReceipts(100) - for i := range 100 { + for i := 0; i < 100; i++ { rs[i] = unittest.ExecutionReceiptFixture() } @@ -195,7 +195,7 @@ func TestPendingReceipts(t *testing.T) { headers.On("ByBlockID", executedBlock.ID()).Return(executedBlock.ToHeader(), nil) headers.On("ByBlockID", nextExecutedBlock.ID()).Return(nextExecutedBlock.ToHeader(), nil) ids := make(map[flow.Identifier]struct{}) - for range 10 { + for i := 0; i < 10; i++ { receipt := unittest.ExecutionReceiptFixture(unittest.WithResult(er)) pool.Add(receipt) ids[receipt.ID()] = struct{}{} diff --git a/module/metrics/example/collection/main.go b/module/metrics/example/collection/main.go index 2d0a3ac70b8..f265e991dfa 100644 --- a/module/metrics/example/collection/main.go +++ b/module/metrics/example/collection/main.go @@ -38,7 +38,7 @@ func main() { message1 := "CollectionRequest" message2 := "ClusterBlockProposal" - for i := range 100 { + for i := 0; i < 100; i++ { collector.TransactionIngested(unittest.IdentifierFixture()) collector.HotStuffBusyDuration(10, metrics.HotstuffEventTypeLocalTimeout) collector.HotStuffWaitDuration(10, metrics.HotstuffEventTypeLocalTimeout) diff --git a/module/metrics/example/consensus/main.go b/module/metrics/example/consensus/main.go index b90531ca8e7..8c18ffbfc4e 100644 --- a/module/metrics/example/consensus/main.go +++ b/module/metrics/example/consensus/main.go @@ -37,7 +37,7 @@ func main() { MempoolCollector: metrics.NewMempoolCollector(5 * time.Second), } - for i := range 100 { + for i := 0; i < 100; i++ { block := unittest.BlockFixture() collector.MempoolEntries(metrics.ResourceGuarantee, 22) collector.BlockFinalized(block) diff --git a/module/metrics/example/execution/main.go b/module/metrics/example/execution/main.go index ab5eb6689db..94837711d2d 100644 --- a/module/metrics/example/execution/main.go +++ b/module/metrics/example/execution/main.go @@ -31,7 +31,7 @@ func main() { NetworkCollector: metrics.NewNetworkCollector(unittest.Logger()), } diskTotal := rand.Int63n(1024 * 1024 * 1024) - for range 1000 { + for i := 0; i < 1000; i++ { blockID := unittest.BlockFixture().ID() collector.StartBlockReceivedToExecuted(blockID) diff --git a/module/metrics/example/verification/main.go b/module/metrics/example/verification/main.go index f46a46d898b..103b751240b 100644 --- a/module/metrics/example/verification/main.go +++ b/module/metrics/example/verification/main.go @@ -119,7 +119,7 @@ func demo() { // to collect or not. // This is done to stretch metrics and scatter their pattern // for a clear visualization. - for i := range 100 { + for i := 0; i < 100; i++ { // consumer tryRandomCall(func() { vc.OnBlockConsumerJobDone(rand.Uint64() % 10000) diff --git a/module/queue/concurrent_priority_queue_test.go b/module/queue/concurrent_priority_queue_test.go index e98520f2946..734295da80d 100644 --- a/module/queue/concurrent_priority_queue_test.go +++ b/module/queue/concurrent_priority_queue_test.go @@ -1,6 +1,7 @@ package queue import ( + "context" "fmt" "math" "sync" @@ -235,7 +236,7 @@ func TestConcurrentPriorityQueue_Channel(t *testing.T) { ch := mq.Channel() // Push multiple items rapidly - for i := range 10 { + for i := 0; i < 10; i++ { mq.Push("test", uint64(i)) } @@ -256,7 +257,7 @@ func TestConcurrentPriorityQueue_Channel(t *testing.T) { ch := mq.Channel() // Push multiple items without reading from channel - for i := range 5 { + for i := 0; i < 5; i++ { mq.Push("test", uint64(i)) } @@ -281,7 +282,7 @@ func TestConcurrentPriorityQueue_Concurrency(t *testing.T) { var wg sync.WaitGroup // Start multiple goroutines pushing items - for i := range numGoroutines { + for i := 0; i < numGoroutines; i++ { wg.Add(1) go func(id int) { defer wg.Done() @@ -296,7 +297,7 @@ func TestConcurrentPriorityQueue_Concurrency(t *testing.T) { // Verify items can be popped correctly popped := make(map[int]bool) - for range numGoroutines { + for i := 0; i < numGoroutines; i++ { item, ok := mq.Pop() assert.True(t, ok) assert.False(t, popped[item], "duplicate item popped: %d", item) @@ -314,7 +315,7 @@ func TestConcurrentPriorityQueue_Concurrency(t *testing.T) { popped := make(map[int]bool) // Start goroutines that push items - for i := range numGoroutines { + for i := 0; i < numGoroutines; i++ { wg.Add(1) go func(id int) { defer wg.Done() @@ -328,7 +329,9 @@ func TestConcurrentPriorityQueue_Concurrency(t *testing.T) { // Now start goroutines that pop items var popWg sync.WaitGroup for i := 0; i < numGoroutines/2; i++ { - popWg.Go(func() { + popWg.Add(1) + go func() { + defer popWg.Done() for { item, ok := mq.Pop() if !ok { @@ -339,7 +342,7 @@ func TestConcurrentPriorityQueue_Concurrency(t *testing.T) { popped[item] = true mu.Unlock() } - }) + }() } popWg.Wait() @@ -354,7 +357,7 @@ func TestConcurrentPriorityQueue_Concurrency(t *testing.T) { var wg sync.WaitGroup // Start goroutines that push items - for i := range numGoroutines { + for i := 0; i < numGoroutines; i++ { wg.Add(1) go func(id int) { defer wg.Done() @@ -364,11 +367,13 @@ func TestConcurrentPriorityQueue_Concurrency(t *testing.T) { // Start goroutines that call Len for i := 0; i < numGoroutines/2; i++ { - wg.Go(func() { - for range 100 { + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < 100; j++ { _ = mq.Len() } - }) + }() } wg.Wait() @@ -496,7 +501,8 @@ func TestConcurrentPriorityQueue_Integration(t *testing.T) { }) t.Run("queue processing using channel", func(t *testing.T) { - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() mq := NewConcurrentPriorityQueue[string](true) diff --git a/module/queue/priority_queue_test.go b/module/queue/priority_queue_test.go index 7d14dfedcc1..c7c8b65d025 100644 --- a/module/queue/priority_queue_test.go +++ b/module/queue/priority_queue_test.go @@ -261,7 +261,7 @@ func TestPriorityQueue_HeapOperations(t *testing.T) { // Pop items and verify order results := make([]string, 4) - for i := range 4 { + for i := 0; i < 4; i++ { item := heap.Pop(pq).(*PriorityQueueItem[string]) results[i] = item.message } diff --git a/module/signature/checksum_test.go b/module/signature/checksum_test.go index b07bf7e3655..635d86a6a59 100644 --- a/module/signature/checksum_test.go +++ b/module/signature/checksum_test.go @@ -65,7 +65,7 @@ func TestPrefixCheckSum(t *testing.T) { // 2. `CompareAndExtract` returns `ErrInvalidChecksum` is the checksum does not match func Test_InvalidCheckSum(t *testing.T) { t.Run("checksum too short", func(t *testing.T) { - for i := range 4 { + for i := 0; i < 4; i++ { _, _, err := msig.SplitCheckSum(unittest.RandomBytes(i)) require.ErrorIs(t, err, msig.ErrInvalidChecksum) } diff --git a/module/signature/signer_indices_test.go b/module/signature/signer_indices_test.go index 5f9b0686d4a..2a10311e2a9 100644 --- a/module/signature/signer_indices_test.go +++ b/module/signature/signer_indices_test.go @@ -23,7 +23,7 @@ import ( func TestEncodeDecodeIdentities(t *testing.T) { canonicalIdentities := unittest.IdentityListFixture(20).Sort(flow.Canonical[flow.Identity]).ToSkeleton() canonicalIdentifiers := canonicalIdentities.NodeIDs() - for s := range 20 { + for s := 0; s < 20; s++ { for e := s; e < 20; e++ { var signers = canonicalIdentities[s:e] diff --git a/module/state_synchronization/indexer/extended/contracts_test.go b/module/state_synchronization/indexer/extended/contracts_test.go index cb746593a55..3712e455219 100644 --- a/module/state_synchronization/indexer/extended/contracts_test.go +++ b/module/state_synchronization/indexer/extended/contracts_test.go @@ -3,7 +3,6 @@ package extended_test import ( "bytes" "fmt" - "maps" "strings" "testing" @@ -942,8 +941,12 @@ func makeMultiAccountSnapshot( ) fvmsnapshot.MapStorageSnapshot { t.Helper() snap := make(fvmsnapshot.MapStorageSnapshot) - maps.Copy(snap, makeContractSnapshot(t, addr1, contracts1)) - maps.Copy(snap, makeContractSnapshot(t, addr2, contracts2)) + for k, v := range makeContractSnapshot(t, addr1, contracts1) { + snap[k] = v + } + for k, v := range makeContractSnapshot(t, addr2, contracts2) { + snap[k] = v + } return snap } diff --git a/module/state_synchronization/indexer/extended/scheduled_transaction_requester.go b/module/state_synchronization/indexer/extended/scheduled_transaction_requester.go index 54256a51c16..9ae161a788a 100644 --- a/module/state_synchronization/indexer/extended/scheduled_transaction_requester.go +++ b/module/state_synchronization/indexer/extended/scheduled_transaction_requester.go @@ -147,5 +147,5 @@ func (r *ScheduledTransactionRequester) fetchMissingTxs( // lookups on the given chain. Exposed for testing. func GetTransactionDataScript(chainID flow.ChainID) []byte { sc := systemcontracts.SystemContractsForChain(chainID) - return fmt.Appendf(nil, getTransactionDataScriptTemplate, sc.FlowTransactionScheduler.Address.Hex()) + return []byte(fmt.Sprintf(getTransactionDataScriptTemplate, sc.FlowTransactionScheduler.Address.Hex())) } diff --git a/module/state_synchronization/indexer/util.go b/module/state_synchronization/indexer/util.go index 5586f8072c0..5526776716b 100644 --- a/module/state_synchronization/indexer/util.go +++ b/module/state_synchronization/indexer/util.go @@ -2,7 +2,6 @@ package indexer import ( "fmt" - "slices" "github.com/onflow/cadence" "github.com/onflow/cadence/common" @@ -23,8 +22,10 @@ var ( func hasAuthorizedTransaction(collections []*flow.Collection, address flow.Address) bool { for _, collection := range collections { for _, tx := range collection.Transactions { - if slices.Contains(tx.Authorizers, address) { - return true + for _, authorizer := range tx.Authorizers { + if authorizer == address { + return true + } } } } diff --git a/module/state_synchronization/requester/execution_data_requester_test.go b/module/state_synchronization/requester/execution_data_requester_test.go index 637df865e42..4bf9607c85f 100644 --- a/module/state_synchronization/requester/execution_data_requester_test.go +++ b/module/state_synchronization/requester/execution_data_requester_test.go @@ -654,7 +654,7 @@ func generateTestData(t *testing.T, blobstore blobs.Blobstore, blockCount int, s var previousBlock *flow.Block var previousResult *flow.ExecutionResult - for i := range blockCount { + for i := 0; i < blockCount; i++ { var seals []*flow.Header if i >= firstSeal { diff --git a/module/util/log.go b/module/util/log.go index 91aa70f3433..560a90710ea 100644 --- a/module/util/log.go +++ b/module/util/log.go @@ -60,10 +60,13 @@ func NewLogProgressConfig[T int | uint | int32 | uint32 | uint64 | int64]( } // add the tick at 0% - ticks = min( - // sanitize ticks - // number of ticks should be at most total + 1 - uint64(total+1), ticks+1) + ticks = ticks + 1 + + // sanitize ticks + // number of ticks should be at most total + 1 + if uint64(total+1) < ticks { + ticks = uint64(total + 1) + } // sanitize noDataLogDuration if noDataLogDuration < time.Millisecond { @@ -115,7 +118,10 @@ func LogProgress[T int | uint | int32 | uint32 | uint64 | int64]( etaString := "unknown" if percentage > 0 { - eta := max(time.Duration(float64(elapsed)/percentage*(100-percentage)), 0) + eta := time.Duration(float64(elapsed) / percentage * (100 - percentage)) + if eta < 0 { + eta = 0 + } etaString = eta.Round(1 * time.Second).String() } @@ -130,7 +136,10 @@ func LogProgress[T int | uint | int32 | uint32 | uint64 | int64]( logProgress(0) // sanitize inputs and calculate increment - ticksIncludingZero := max(config.ticks, 2) + ticksIncludingZero := config.ticks + if ticksIncludingZero < 2 { + ticksIncludingZero = 2 + } ticks := ticksIncludingZero - 1 increment := total / ticks diff --git a/module/util/util_test.go b/module/util/util_test.go index 3ebe46ee906..8d0f42ed1ed 100644 --- a/module/util/util_test.go +++ b/module/util/util_test.go @@ -40,7 +40,7 @@ func TestAllDone(t *testing.T) { func testAllDone(n int, t *testing.T) { components := make([]realmodule.ReadyDoneAware, n) - for i := range n { + for i := 0; i < n; i++ { components[i] = new(module.ReadyDoneAware) unittest.ReadyDoneify(components[i]) } @@ -57,7 +57,7 @@ func testAllDone(n int, t *testing.T) { func testAllReady(n int, t *testing.T) { components := make([]realmodule.ReadyDoneAware, n) - for i := range n { + for i := 0; i < n; i++ { components[i] = new(module.ReadyDoneAware) unittest.ReadyDoneify(components[i]) } @@ -138,6 +138,8 @@ func TestMergeChannels(t *testing.T) { channels := []chan int{make(chan int), make(chan int), make(chan int)} merged := util.MergeChannels(channels).(<-chan int) for i, ch := range channels { + i := i + ch := ch go func() { ch <- i close(ch) @@ -152,7 +154,8 @@ func TestMergeChannels(t *testing.T) { } func TestWaitClosed(t *testing.T) { - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() t.Run("channel closed returns nil", func(t *testing.T) { finished := make(chan struct{}) @@ -193,7 +196,7 @@ func TestWaitClosed(t *testing.T) { // both conditions are met when WaitClosed is called. Since one is randomly selected, // there is a 99.9% probability that each condition will be picked first at least once // during this test. - for range 10 { + for i := 0; i < 10; i++ { testCtx, testCancel := context.WithCancel(ctx) finished := make(chan struct{}) ch := make(chan struct{}) @@ -223,7 +226,8 @@ func TestCheckClosed(t *testing.T) { } func TestWaitError(t *testing.T) { - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() testErr := errors.New("test error channel") t.Run("error received returns error", func(t *testing.T) { @@ -266,7 +270,7 @@ func TestWaitError(t *testing.T) { // both conditions are met when WaitError is called. Since one is randomly selected, // there is a 99.9% probability that each condition will be picked first at least once // during this test. - for range 10 { + for i := 0; i < 10; i++ { finished := make(chan struct{}) ch := make(chan error, 1) // buffered so we can add before starting done := make(chan struct{}) diff --git a/network/alsp/internal/cache_test.go b/network/alsp/internal/cache_test.go index 82d564c4e7c..8a7e116e3bb 100644 --- a/network/alsp/internal/cache_test.go +++ b/network/alsp/internal/cache_test.go @@ -373,7 +373,7 @@ func TestSpamRecordCache_ConcurrentSameRecordAdjust(t *testing.T) { var wg sync.WaitGroup wg.Add(concurrentAttempts) - for range concurrentAttempts { + for i := 0; i < concurrentAttempts; i++ { go func() { defer wg.Done() penalty, err := cache.AdjustWithInit(originID, adjustFn) @@ -539,6 +539,7 @@ func TestSpamRecordCache_ConcurrentInitAndRemove(t *testing.T) { // initialize spam records concurrently for _, originID := range originIDsToAdd { + originID := originID // capture range variable go func() { defer wg.Done() penalty, err := cache.AdjustWithInit(originID, adjustFnNoOp) @@ -611,6 +612,7 @@ func TestSpamRecordCache_ConcurrentInitRemoveAdjust(t *testing.T) { // Initialize spam records concurrently for _, originID := range originIDsToAdd { + originID := originID // capture range variable go func() { defer wg.Done() penalty, err := cache.AdjustWithInit(originID, adjustFnNoOp) @@ -682,6 +684,7 @@ func TestSpamRecordCache_ConcurrentInitRemoveAndAdjust(t *testing.T) { // initialize spam records concurrently for _, originID := range originIDsToAdd { + originID := originID go func() { defer wg.Done() penalty, err := cache.AdjustWithInit(originID, adjustFnNoOp) @@ -692,6 +695,7 @@ func TestSpamRecordCache_ConcurrentInitRemoveAndAdjust(t *testing.T) { // remove spam records concurrently for _, originID := range originIDsToRemove { + originID := originID go func() { defer wg.Done() cache.Remove(originID) @@ -700,6 +704,7 @@ func TestSpamRecordCache_ConcurrentInitRemoveAndAdjust(t *testing.T) { // adjust spam records concurrently for _, originID := range originIDsToAdjust { + originID := originID go func() { defer wg.Done() _, err := cache.AdjustWithInit(originID, func(record *model.ProtocolSpamRecord) (*model.ProtocolSpamRecord, error) { @@ -768,6 +773,7 @@ func TestSpamRecordCache_ConcurrentIdentitiesAndOperations(t *testing.T) { // initialize spam records concurrently for _, originID := range originIDsToAdd { + originID := originID go func() { defer wg.Done() penalty, err := cache.AdjustWithInit(originID, adjustFnNoOp) @@ -781,6 +787,7 @@ func TestSpamRecordCache_ConcurrentIdentitiesAndOperations(t *testing.T) { // remove spam records concurrently for _, originID := range originIDsToRemove { + originID := originID go func() { defer wg.Done() require.True(t, cache.Remove(originID)) @@ -791,7 +798,7 @@ func TestSpamRecordCache_ConcurrentIdentitiesAndOperations(t *testing.T) { } // call Identities method concurrently - for range 10 { + for i := 0; i < 10; i++ { go func() { defer wg.Done() ids := cache.Identities() diff --git a/network/alsp/manager/manager_test.go b/network/alsp/manager/manager_test.go index 6c5fe7b5a22..0a2a60aaef2 100644 --- a/network/alsp/manager/manager_test.go +++ b/network/alsp/manager/manager_test.go @@ -136,7 +136,7 @@ func TestHandleReportedMisbehavior_Cache_Integration(t *testing.T) { numReportsPerPeer := 5 peersReports := make(map[flow.Identifier][]network.MisbehaviorReport) - for range numPeers { + for i := 0; i < numPeers; i++ { originID := unittest.IdentifierFixture() reports := createRandomMisbehaviorReportsForOriginId(t, originID, numReportsPerPeer) peersReports[originID] = reports @@ -251,7 +251,7 @@ func TestHandleReportedMisbehavior_And_DisallowListing_Integration(t *testing.T) // the spammer is definitely disallow-listed. reportCount := 120 wg := sync.WaitGroup{} - for range reportCount { + for i := 0; i < reportCount; i++ { wg.Add(1) // reports the misbehavior r := report // capture range variable @@ -357,7 +357,7 @@ func TestHandleReportedMisbehavior_And_DisallowListing_RepeatOffender_Integratio // the spammer is definitely disallow-listed. reportCount := 120 wg := sync.WaitGroup{} - for range reportCount { + for reportCounter := 0; reportCounter < reportCount; reportCounter++ { wg.Add(1) // reports the misbehavior r := report // capture range variable @@ -511,11 +511,13 @@ func TestHandleReportedMisbehavior_And_SlashingViolationsConsumer_Integration(t violationsWg := sync.WaitGroup{} violationCount := 120 for _, testCase := range slashingViolationTestCases { - for range violationCount { + for i := 0; i < violationCount; i++ { testCase := testCase - violationsWg.Go(func() { + violationsWg.Add(1) + go func() { + defer violationsWg.Done() testCase.violationsConsumerFunc(testCase.violation) - }) + }() } } unittest.RequireReturnsBefore(t, violationsWg.Wait, 100*time.Millisecond, "slashing violations not reported in time") @@ -1114,7 +1116,7 @@ func TestHandleMisbehaviorReport_MultiplePenaltyReportsForMultiplePeers_Sequenti numReportsPerPeer := 5 peersReports := make(map[flow.Identifier][]network.MisbehaviorReport) - for range numPeers { + for i := 0; i < numPeers; i++ { originID := unittest.IdentifierFixture() reports := createRandomMisbehaviorReportsForOriginId(t, originID, numReportsPerPeer) peersReports[originID] = reports @@ -1195,7 +1197,7 @@ func TestHandleMisbehaviorReport_MultiplePenaltyReportsForMultiplePeers_Concurre numReportsPerPeer := 5 peersReports := make(map[flow.Identifier][]network.MisbehaviorReport) - for range numPeers { + for i := 0; i < numPeers; i++ { originID := unittest.IdentifierFixture() reports := createRandomMisbehaviorReportsForOriginId(t, originID, numReportsPerPeer) peersReports[originID] = reports @@ -1276,7 +1278,7 @@ func TestHandleMisbehaviorReport_DuplicateReportsForSinglePeer_Concurrently(t *t wg.Add(times) // concurrently reports the same misbehavior report twice - for range times { + for i := 0; i < times; i++ { go func() { defer wg.Done() @@ -1346,7 +1348,7 @@ func TestDecayMisbehaviorPenalty_SingleHeartbeat(t *testing.T) { wg.Add(times) // concurrently reports the same misbehavior report twice - for range times { + for i := 0; i < times; i++ { go func() { defer wg.Done() @@ -1436,7 +1438,7 @@ func TestDecayMisbehaviorPenalty_MultipleHeartbeats(t *testing.T) { wg.Add(times) // concurrently reports the same misbehavior report twice - for range times { + for i := 0; i < times; i++ { go func() { defer wg.Done() @@ -1526,7 +1528,7 @@ func TestDecayMisbehaviorPenalty_DecayToZero(t *testing.T) { wg.Add(times) // concurrently reports the same misbehavior report twice - for range times { + for i := 0; i < times; i++ { go func() { defer wg.Done() @@ -1698,7 +1700,7 @@ func TestDisallowListNotification(t *testing.T) { wg.Add(times) // concurrently reports the same misbehavior report twice - for range times { + for i := 0; i < times; i++ { go func() { defer wg.Done() @@ -1754,7 +1756,7 @@ func TestDisallowListNotification(t *testing.T) { func createRandomMisbehaviorReportsForOriginId(t *testing.T, originID flow.Identifier, numReports int) []network.MisbehaviorReport { reports := make([]network.MisbehaviorReport, numReports) - for i := range numReports { + for i := 0; i < numReports; i++ { reports[i] = misbehaviorReportFixture(t, originID) } @@ -1771,7 +1773,7 @@ func createRandomMisbehaviorReportsForOriginId(t *testing.T, originID flow.Ident func createRandomMisbehaviorReports(t *testing.T, numReports int) []network.MisbehaviorReport { reports := make([]network.MisbehaviorReport, numReports) - for i := range numReports { + for i := 0; i < numReports; i++ { reports[i] = misbehaviorReportFixture(t, unittest.IdentifierFixture()) } diff --git a/network/cache/rcvcache_test.go b/network/cache/rcvcache_test.go index 329e9e65c2b..36cc7b600bc 100644 --- a/network/cache/rcvcache_test.go +++ b/network/cache/rcvcache_test.go @@ -76,7 +76,7 @@ func (r *ReceiveCacheTestSuite) TestMultipleElementAdd() { // creates and populates slice of 10 events eventIDs := make([]hash.Hash, 0) for i := 0; i < r.size; i++ { - eventID, err := message.EventId(channels.Channel("1"), fmt.Appendf(nil, "event-%d", i)) + eventID, err := message.EventId(channels.Channel("1"), []byte(fmt.Sprintf("event-%d", i))) require.NoError(r.T(), err) eventIDs = append(eventIDs, eventID) @@ -113,15 +113,15 @@ func (r *ReceiveCacheTestSuite) TestMultipleElementAdd() { func (r *ReceiveCacheTestSuite) TestLRU() { eventIDs := make([]hash.Hash, 0) total := r.size + 1 - for i := range total { - eventID, err := message.EventId(channels.Channel("1"), fmt.Appendf(nil, "event-%d", i)) + for i := 0; i < total; i++ { + eventID, err := message.EventId(channels.Channel("1"), []byte(fmt.Sprintf("event-%d", i))) require.NoError(r.T(), err) eventIDs = append(eventIDs, eventID) } // adding non-existing even id must return true - for i := range total { + for i := 0; i < total; i++ { assert.True(r.Suite.T(), r.c.Add(eventIDs[i])) } diff --git a/network/internal/p2pfixtures/fixtures.go b/network/internal/p2pfixtures/fixtures.go index 542d118f2c2..fab3fb6228a 100644 --- a/network/internal/p2pfixtures/fixtures.go +++ b/network/internal/p2pfixtures/fixtures.go @@ -373,7 +373,7 @@ func LongStringMessageFactoryFixture(t *testing.T) func() string { } // MustEncodeEvent encodes and returns the given event and fails the test if it faces any issue while encoding. -func MustEncodeEvent(t *testing.T, v any, channel channels.Channel) []byte { +func MustEncodeEvent(t *testing.T, v interface{}, channel channels.Channel) []byte { bz, err := unittest.NetworkCodec().Encode(v) require.NoError(t, err) diff --git a/network/internal/testutils/fixtures.go b/network/internal/testutils/fixtures.go index 347e4d247a7..b2fff20abbb 100644 --- a/network/internal/testutils/fixtures.go +++ b/network/internal/testutils/fixtures.go @@ -39,7 +39,7 @@ func MisbehaviorReportFixture(t *testing.T) network.MisbehaviorReport { // This is used in tests to generate random misbehavior reports. func MisbehaviorReportsFixture(t *testing.T, count int) []network.MisbehaviorReport { reports := make([]network.MisbehaviorReport, 0, count) - for range count { + for i := 0; i < count; i++ { reports = append(reports, MisbehaviorReportFixture(t)) } diff --git a/network/internal/testutils/meshengine.go b/network/internal/testutils/meshengine.go index 36f2430ed08..a8dafef6df7 100644 --- a/network/internal/testutils/meshengine.go +++ b/network/internal/testutils/meshengine.go @@ -20,7 +20,7 @@ type MeshEngine struct { t *testing.T Con network.Conduit // used to directly communicate with the network originID flow.Identifier // used to keep track of the id of the sender of the messages - Event chan any // used to keep track of the events that the node receives + Event chan interface{} // used to keep track of the events that the node receives Channel chan channels.Channel // used to keep track of the channels that events are Received on Received chan struct{} // used as an indicator on reception of messages for testing mockcomponent.Component @@ -29,7 +29,7 @@ type MeshEngine struct { func NewMeshEngine(t *testing.T, net network.EngineRegistry, cap int, channel channels.Channel) *MeshEngine { te := &MeshEngine{ t: t, - Event: make(chan any, cap), + Event: make(chan interface{}, cap), Channel: make(chan channels.Channel, cap), Received: make(chan struct{}, cap), } @@ -43,13 +43,13 @@ func NewMeshEngine(t *testing.T, net network.EngineRegistry, cap int, channel ch // SubmitLocal is implemented for a valid type assertion to Engine // any call to it fails the test -func (e *MeshEngine) SubmitLocal(event any) { +func (e *MeshEngine) SubmitLocal(event interface{}) { require.Fail(e.t, "not implemented") } // Submit is implemented for a valid type assertion to Engine // any call to it fails the test -func (e *MeshEngine) Submit(channel channels.Channel, originID flow.Identifier, event any) { +func (e *MeshEngine) Submit(channel channels.Channel, originID flow.Identifier, event interface{}) { go func() { err := e.Process(channel, originID, event) if err != nil { @@ -60,14 +60,14 @@ func (e *MeshEngine) Submit(channel channels.Channel, originID flow.Identifier, // ProcessLocal is implemented for a valid type assertion to Engine // any call to it fails the test -func (e *MeshEngine) ProcessLocal(event any) error { +func (e *MeshEngine) ProcessLocal(event interface{}) error { require.Fail(e.t, "not implemented") return fmt.Errorf(" unexpected method called") } // Process receives an originID and an Event and casts them into the corresponding fields of the // MeshEngine. It then flags the Received Channel on reception of an Event. -func (e *MeshEngine) Process(channel channels.Channel, originID flow.Identifier, event any) error { +func (e *MeshEngine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { e.Lock() defer e.Unlock() diff --git a/network/internal/testutils/testUtil.go b/network/internal/testutils/testUtil.go index f6daa4fd74f..84715619016 100644 --- a/network/internal/testutils/testUtil.go +++ b/network/internal/testutils/testUtil.go @@ -131,7 +131,7 @@ func LibP2PNodeForNetworkFixture(t *testing.T, sporkId flow.Identifier, n int, o idProvider := unittest.NewUpdatableIDProvider(flow.IdentityList{}) opts = append(opts, p2ptest.WithUnicastHandlerFunc(nil)) - for range n { + for i := 0; i < n; i++ { node, nodeId := p2ptest.NodeFixture(t, sporkId, t.Name(), @@ -155,7 +155,7 @@ func NetworksFixture(t *testing.T, nets := make([]*underlay.Network, 0) idProviders := make([]*unittest.UpdatableIDProvider, 0) - for i := range count { + for i := 0; i < count; i++ { idProvider := unittest.NewUpdatableIDProvider(ids) params := NetworkConfigFixture(t, *ids[i], idProvider, sporkId, libp2pNodes[i]) diff --git a/network/internal/testutils/wrapper.go b/network/internal/testutils/wrapper.go index 81b0540a037..eb43c7f0846 100644 --- a/network/internal/testutils/wrapper.go +++ b/network/internal/testutils/wrapper.go @@ -10,20 +10,20 @@ import ( // ConduitSendWrapperFunc is a wrapper around the set of methods offered by the // Conduit (e.g., Publish). This data type is solely introduced at the test level. // Its primary purpose is to make the same test reusable on different Conduit methods. -type ConduitSendWrapperFunc func(msg any, conduit network.Conduit, targetIDs ...flow.Identifier) error +type ConduitSendWrapperFunc func(msg interface{}, conduit network.Conduit, targetIDs ...flow.Identifier) error type ConduitWrapper struct{} // Publish defines a function that receives a message, conduit of an engine instance, and // a set target IDs. It then sends the message to the target IDs using the Publish method of conduit. -func (c *ConduitWrapper) Publish(msg any, conduit network.Conduit, targetIDs ...flow.Identifier) error { +func (c *ConduitWrapper) Publish(msg interface{}, conduit network.Conduit, targetIDs ...flow.Identifier) error { return conduit.Publish(msg, targetIDs...) } // Unicast defines a function that receives a message, conduit of an engine instance, and // a set of target IDs. It then sends the message to the target IDs using individual Unicasts to each // target in the underlying network. -func (c *ConduitWrapper) Unicast(msg any, conduit network.Conduit, targetIDs ...flow.Identifier) error { +func (c *ConduitWrapper) Unicast(msg interface{}, conduit network.Conduit, targetIDs ...flow.Identifier) error { for _, id := range targetIDs { if err := conduit.Unicast(msg, id); err != nil { return fmt.Errorf("could not unicast to node ID %x: %w", id, err) @@ -34,6 +34,6 @@ func (c *ConduitWrapper) Unicast(msg any, conduit network.Conduit, targetIDs ... // Multicast defines a function that receives a message, conduit of an engine instance, and // a set of target ID. It then sends the message to the target IDs using the Multicast method of conduit. -func (c *ConduitWrapper) Multicast(msg any, conduit network.Conduit, targetIDs ...flow.Identifier) error { +func (c *ConduitWrapper) Multicast(msg interface{}, conduit network.Conduit, targetIDs ...flow.Identifier) error { return conduit.Multicast(msg, uint(len(targetIDs)), targetIDs...) } diff --git a/network/p2p/cache/gossipsub_spam_records_test.go b/network/p2p/cache/gossipsub_spam_records_test.go index a3cc19fa564..bee5ecdc26e 100644 --- a/network/p2p/cache/gossipsub_spam_records_test.go +++ b/network/p2p/cache/gossipsub_spam_records_test.go @@ -86,7 +86,7 @@ func TestGossipSubSpamRecordCache_Concurrent_Adjust(t *testing.T) { wg.Add(numRecords) // adds the records concurrently. - for i := range numRecords { + for i := 0; i < numRecords; i++ { go func(num int) { defer wg.Done() peerID := fmt.Sprintf("peer%d", num) @@ -106,7 +106,7 @@ func TestGossipSubSpamRecordCache_Concurrent_Adjust(t *testing.T) { unittest.RequireReturnsBefore(t, wg.Wait, 100*time.Millisecond, "could not adjust all records concurrently on time") // checks if the cache can retrieve all records. - for i := range numRecords { + for i := 0; i < numRecords; i++ { peerID := fmt.Sprintf("peer%d", i) record, err, found := cache.Get(peer.ID(peerID)) require.True(t, found) diff --git a/network/p2p/cache/protocol_state_provider_test.go b/network/p2p/cache/protocol_state_provider_test.go index b2be5d30d91..65713767e9f 100644 --- a/network/p2p/cache/protocol_state_provider_test.go +++ b/network/p2p/cache/protocol_state_provider_test.go @@ -124,7 +124,7 @@ func (suite *ProtocolStateProviderTestSuite) checkStateTransition() { } func (suite *ProtocolStateProviderTestSuite) TestUpdateState() { - for range 10 { + for i := 0; i < 10; i++ { suite.checkStateTransition() } } diff --git a/network/p2p/config/gossipsub.go b/network/p2p/config/gossipsub.go index 685db16f760..a8ea16ce604 100644 --- a/network/p2p/config/gossipsub.go +++ b/network/p2p/config/gossipsub.go @@ -107,7 +107,7 @@ type ScoringParameters struct { // Note: When new topic delivery weights are added to the struct this func should be updated. func (g *GossipSubParameters) PeerGaterTopicDeliveryWeights() (map[string]float64, error) { m := make(map[string]float64) - for weightConfig := range strings.SplitSeq(g.PeerGaterTopicDeliveryWeightsOverride, ",") { + for _, weightConfig := range strings.Split(g.PeerGaterTopicDeliveryWeightsOverride, ",") { wc := strings.Split(weightConfig, ":") f, err := strconv.ParseFloat(strings.TrimSpace(wc[1]), 64) if err != nil { diff --git a/network/p2p/connection/connection_gater_test.go b/network/p2p/connection/connection_gater_test.go index 90578bf02cd..beb7cc218ac 100644 --- a/network/p2p/connection/connection_gater_test.go +++ b/network/p2p/connection/connection_gater_test.go @@ -252,7 +252,7 @@ func TestConnectionGater_InterceptUpgrade(t *testing.T) { allPeerIds := make(peer.IDSlice, 0, count) idProvider := mockmodule.NewIdentityProvider(t) connectionGater := mockp2p.NewConnectionGater(t) - for range count { + for i := 0; i < count; i++ { handler, inbound := p2ptest.StreamHandlerFixture(t) node, id := p2ptest.NodeFixture( t, @@ -335,7 +335,7 @@ func TestConnectionGater_Disallow_Integration(t *testing.T) { disallowedList := concurrentmap.New[*flow.Identity, struct{}]() - for range count { + for i := 0; i < count; i++ { handler, inbound := p2ptest.StreamHandlerFixture(t) node, id := p2ptest.NodeFixture( t, @@ -427,7 +427,7 @@ func ensureCommunicationSilenceAmongGroups( groupBIdentifiers, blockTopic, 1, - func() any { + func() interface{} { return (*messages.Proposal)(unittest.ProposalFixture()) }) p2pfixtures.EnsureNoStreamCreationBetweenGroups(t, ctx, groupANodes, groupBNodes) @@ -437,7 +437,7 @@ func ensureCommunicationSilenceAmongGroups( func ensureCommunicationOverAllProtocols(t *testing.T, ctx context.Context, sporkId flow.Identifier, nodes []p2p.LibP2PNode, inbounds []chan string) { blockTopic := channels.TopicFromChannel(channels.PushBlocks, sporkId) p2ptest.TryConnectionAndEnsureConnected(t, ctx, nodes) - p2ptest.EnsurePubsubMessageExchange(t, ctx, nodes, blockTopic, 1, func() any { + p2ptest.EnsurePubsubMessageExchange(t, ctx, nodes, blockTopic, 1, func() interface{} { return (*messages.Proposal)(unittest.ProposalFixture()) }) p2pfixtures.EnsureMessageExchangeOverUnicast(t, ctx, nodes, inbounds, p2pfixtures.LongStringMessageFactoryFixture(t)) diff --git a/network/p2p/connection/peerManager_test.go b/network/p2p/connection/peerManager_test.go index f1470594714..b776143dc12 100644 --- a/network/p2p/connection/peerManager_test.go +++ b/network/p2p/connection/peerManager_test.go @@ -40,7 +40,7 @@ func (suite *PeerManagerTestSuite) SetupTest() { func (suite *PeerManagerTestSuite) generatePeerIDs(n int) peer.IDSlice { pids := peer.IDSlice{} - for range n { + for i := 0; i < n; i++ { key := p2pfixtures.NetworkingKeyFixtures(suite.T()) pid, err := keyutils.PeerIDFromFlowPublicKey(key.PublicKey()) require.NoError(suite.T(), err) diff --git a/network/p2p/dht/dht_test.go b/network/p2p/dht/dht_test.go index ae59329b8f1..ef23ccb9901 100644 --- a/network/p2p/dht/dht_test.go +++ b/network/p2p/dht/dht_test.go @@ -216,7 +216,7 @@ func TestPubSubWithDHTDiscovery(t *testing.T) { // fullyConnectedGraph checks that each node is directly connected to all the other nodes fullyConnectedGraph := func() bool { - for i := range nodes { + for i := 0; i < len(nodes); i++ { for j := i + 1; j < len(nodes); j++ { if nodes[i].Host().Network().Connectedness(nodes[j].ID()) == network.NotConnected { return false @@ -236,7 +236,7 @@ func TestPubSubWithDHTDiscovery(t *testing.T) { recv := make(map[peer.ID]bool, count) loop: - for range count { + for i := 0; i < count; i++ { select { case res := <-ch: recv[res] = true diff --git a/network/p2p/dns/resolver.go b/network/p2p/dns/resolver.go index 6c57179b686..63df7b47ec3 100644 --- a/network/p2p/dns/resolver.go +++ b/network/p2p/dns/resolver.go @@ -86,11 +86,11 @@ func NewResolver(logger zerolog.Logger, collector module.ResolverMetrics, dnsCac cm := component.NewComponentManagerBuilder() - for range numIPAddrLookupWorkers { + for i := 0; i < numIPAddrLookupWorkers; i++ { cm.AddWorker(resolver.processIPAddrLookups) } - for range numTxtLookupWorkers { + for i := 0; i < numTxtLookupWorkers; i++ { cm.AddWorker(resolver.processTxtLookups) } diff --git a/network/p2p/dns/resolver_test.go b/network/p2p/dns/resolver_test.go index 76c7cf3a120..a69089a6bc2 100644 --- a/network/p2p/dns/resolver_test.go +++ b/network/p2p/dns/resolver_test.go @@ -215,13 +215,13 @@ func syncThenAsyncQuery(t *testing.T, wg.Add(times * (len(txtTestCases) + len(ipTestCases))) for _, txttc := range txtTestCases { - cacheAndQuery(t, func(domain string) (any, error) { + cacheAndQuery(t, func(domain string) (interface{}, error) { return resolver.LookupTXT(ctx, domain) }, txttc.Txt, txttc.Records, times, wg, happyPath) } for _, iptc := range ipTestCases { - cacheAndQuery(t, func(domain string) (any, error) { + cacheAndQuery(t, func(domain string) (interface{}, error) { return resolver.LookupIPAddr(ctx, domain) }, iptc.Domain, iptc.Result, times, wg, happyPath) } @@ -233,16 +233,16 @@ func syncThenAsyncQuery(t *testing.T, // concurrent queries for each test case for the specified number of times. The wait group is released when all // queries resolved. func cacheAndQuery(t *testing.T, - resolver func(domain string) (any, error), + resolver func(domain string) (interface{}, error), domain string, - result any, + result interface{}, times int, wg *sync.WaitGroup, happyPath bool) { - firstCallDone := make(chan any) + firstCallDone := make(chan interface{}) - for i := range times { + for i := 0; i < times; i++ { go func(index int) { if index != 0 { // other invocations (except first one) of each test diff --git a/network/p2p/inspector/internal/cache/cache_test.go b/network/p2p/inspector/internal/cache/cache_test.go index 7982eb880c8..a9ccfeb5ed9 100644 --- a/network/p2p/inspector/internal/cache/cache_test.go +++ b/network/p2p/inspector/internal/cache/cache_test.go @@ -90,7 +90,7 @@ func TestRecordCache_ConcurrentSameRecordInit(t *testing.T) { var wg sync.WaitGroup wg.Add(concurrentAttempts) - for range concurrentAttempts { + for i := 0; i < concurrentAttempts; i++ { go func() { defer wg.Done() gauge, found, err := cache.GetWithInit(nodeID) @@ -478,7 +478,7 @@ func TestRecordCache_EdgeCasesAndInvalidInputs(t *testing.T) { expectedIds[i] = p2p.MakeId(pid) } // call NodeIDs method concurrently - for range 10 { + for i := 0; i < 10; i++ { go func() { defer wg.Done() ids := cache.NodeIDs() diff --git a/network/p2p/inspector/validation/control_message_validation_inspector.go b/network/p2p/inspector/validation/control_message_validation_inspector.go index 92eadbc71a2..0f094511f27 100644 --- a/network/p2p/inspector/validation/control_message_validation_inspector.go +++ b/network/p2p/inspector/validation/control_message_validation_inspector.go @@ -639,7 +639,10 @@ func (c *ControlMsgValidationInspector) inspectRpcPublishMessages(from peer.ID, return nil, 0 } - sampleSize := min(c.config.PublishMessages.MaxSampleSize, totalMessages) + sampleSize := c.config.PublishMessages.MaxSampleSize + if sampleSize > totalMessages { + sampleSize = totalMessages + } c.performSample(p2pmsg.RpcPublishMessage, uint(totalMessages), uint(sampleSize), func(i, j uint) { messages[i], messages[j] = messages[j], messages[i] }) @@ -828,7 +831,10 @@ func (c *ControlMsgValidationInspector) truncateIHaveMessages(from peer.ID, rpc if originalIHaveCount > c.config.IHave.MessageCountThreshold { // truncate ihaves and update metrics - sampleSize := min(c.config.IHave.MessageCountThreshold, originalIHaveCount) + sampleSize := c.config.IHave.MessageCountThreshold + if sampleSize > originalIHaveCount { + sampleSize = originalIHaveCount + } c.performSample(p2pmsg.CtrlMsgIHave, uint(originalIHaveCount), uint(sampleSize), func(i, j uint) { ihaves[i], ihaves[j] = ihaves[j], ihaves[i] }) @@ -859,7 +865,10 @@ func (c *ControlMsgValidationInspector) truncateIHaveMessageIds(from peer.ID, rp } if originalMessageIdCount > c.config.IHave.MessageIdCountThreshold { - sampleSize := min(c.config.IHave.MessageIdCountThreshold, originalMessageIdCount) + sampleSize := c.config.IHave.MessageIdCountThreshold + if sampleSize > originalMessageIdCount { + sampleSize = originalMessageIdCount + } c.performSample(p2pmsg.CtrlMsgIHave, uint(originalMessageIdCount), uint(sampleSize), func(i, j uint) { messageIDs[i], messageIDs[j] = messageIDs[j], messageIDs[i] }) @@ -892,7 +901,10 @@ func (c *ControlMsgValidationInspector) truncateIWantMessages(from peer.ID, rpc if originalIWantCount > c.config.IWant.MessageCountThreshold { // truncate iWants and update metrics - sampleSize := min(c.config.IWant.MessageCountThreshold, originalIWantCount) + sampleSize := c.config.IWant.MessageCountThreshold + if sampleSize > originalIWantCount { + sampleSize = originalIWantCount + } c.performSample(p2pmsg.CtrlMsgIWant, originalIWantCount, sampleSize, func(i, j uint) { iWants[i], iWants[j] = iWants[j], iWants[i] }) diff --git a/network/p2p/inspector/validation/control_message_validation_inspector_test.go b/network/p2p/inspector/validation/control_message_validation_inspector_test.go index 023b38fff20..8258f598f0f 100644 --- a/network/p2p/inspector/validation/control_message_validation_inspector_test.go +++ b/network/p2p/inspector/validation/control_message_validation_inspector_test.go @@ -5,7 +5,6 @@ import ( "fmt" "io" "math/rand" - "slices" "sync" "testing" "time" @@ -337,8 +336,10 @@ func TestControlMessageInspection_ValidRpc(t *testing.T) { id, ok := args[0].(string) require.True(t, ok) for _, iwant := range iwants { - if slices.Contains(iwant.GetMessageIDs(), id) { - return + for _, messageID := range iwant.GetMessageIDs() { + if id == messageID { + return + } } } require.Fail(t, "message id not found in iwant messages") @@ -1446,7 +1447,7 @@ func TestNewControlMsgValidationInspector_validateClusterPrefixedTopic(t *testin inspector.Start(signalerCtx) unittest.RequireComponentsReadyBefore(t, 1*time.Second, inspector) - for range 11 { + for i := 0; i < 11; i++ { require.NoError(t, inspector.Inspect(from, inspectMsgRpc)) } require.Eventually(t, func() bool { diff --git a/network/p2p/logging/logging_test.go b/network/p2p/logging/logging_test.go index 98e357a01be..1dc80e3af4d 100644 --- a/network/p2p/logging/logging_test.go +++ b/network/p2p/logging/logging_test.go @@ -24,7 +24,7 @@ func BenchmarkPeerIdString(b *testing.B) { count := 100 pids := make([]peer.ID, 0, count) - for range count { + for i := 0; i < count; i++ { pids = append(pids, unittest.PeerIdFixture(b)) } @@ -41,7 +41,7 @@ func BenchmarkPeerIdLogging(b *testing.B) { count := 100 pids := make([]peer.ID, 0, count) - for range count { + for i := 0; i < count; i++ { pids = append(pids, unittest.PeerIdFixture(b)) } diff --git a/network/p2p/node/internal/protocolPeerCache_test.go b/network/p2p/node/internal/protocolPeerCache_test.go index 47b24bf7cb5..cc6d4202996 100644 --- a/network/p2p/node/internal/protocolPeerCache_test.go +++ b/network/p2p/node/internal/protocolPeerCache_test.go @@ -1,6 +1,7 @@ package internal_test import ( + "context" "slices" "testing" "time" @@ -19,7 +20,8 @@ import ( ) func TestProtocolPeerCache(t *testing.T) { - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() p1 := protocol.ID("p1") p2 := protocol.ID("p2") diff --git a/network/p2p/node/libp2pNode_test.go b/network/p2p/node/libp2pNode_test.go index 946cbfb8ec7..04c25e4694a 100644 --- a/network/p2p/node/libp2pNode_test.go +++ b/network/p2p/node/libp2pNode_test.go @@ -82,7 +82,7 @@ func TestSingleNodeLifeCycle(t *testing.T) { // their libp2p info. It generates an address, and checks whether repeated translations // yields the same info or not. func TestGetPeerInfo(t *testing.T) { - for range 10 { + for i := 0; i < 10; i++ { key := p2pfixtures.NetworkingKeyFixtures(t) // creates node-i identity @@ -93,7 +93,7 @@ func TestGetPeerInfo(t *testing.T) { require.NoError(t, err) // repeats the translation for node-i - for range 10 { + for j := 0; j < 10; j++ { rinfo, err := utils.PeerAddressInfo(identity.IdentitySkeleton) require.NoError(t, err) assert.Equal(t, rinfo.String(), info.String(), "inconsistent id generated") @@ -301,7 +301,7 @@ func createConcurrentStreams(t *testing.T, ctx context.Context, nodes []p2p.LibP require.NoError(t, err) this.Host().Peerstore().AddAddrs(pInfo.ID, pInfo.Addrs, peerstore.AddressTTL) - for range n { + for j := 0; j < n; j++ { wg.Add(1) go func(sender p2p.LibP2PNode) { defer wg.Done() diff --git a/network/p2p/node/libp2pStream_test.go b/network/p2p/node/libp2pStream_test.go index 31703586592..9b8e8453014 100644 --- a/network/p2p/node/libp2pStream_test.go +++ b/network/p2p/node/libp2pStream_test.go @@ -54,7 +54,7 @@ func TestStreamClosing(t *testing.T) { senderWG := sync.WaitGroup{} senderWG.Add(count) - for i := range count { + for i := 0; i < count; i++ { go func(i int) { // Create stream from node 1 to node 2 (reuse if one already exists) nodes[0].Host().Peerstore().AddAddrs(nodeInfo1.ID, nodeInfo1.Addrs, peerstore.AddressTTL) @@ -159,7 +159,7 @@ func testCreateStream(t *testing.T, sporkId flow.Identifier, unicasts []protocol streamCount := 100 var streams []network.Stream allStreamsClosedWg := sync.WaitGroup{} - for range streamCount { + for i := 0; i < streamCount; i++ { allStreamsClosedWg.Add(1) pInfo, err := utils.PeerAddressInfo(id2.IdentitySkeleton) require.NoError(t, err) @@ -234,7 +234,7 @@ func TestCreateStream_FallBack(t *testing.T) { streamCount := 10 var streams []network.Stream allStreamsClosedWg := sync.WaitGroup{} - for range streamCount { + for i := 0; i < streamCount; i++ { allStreamsClosedWg.Add(1) pInfo, err := utils.PeerAddressInfo(otherId.IdentitySkeleton) require.NoError(t, err) @@ -309,7 +309,7 @@ func TestCreateStreamIsConcurrencySafe(t *testing.T) { } // kick off 10 concurrent calls to CreateStream - for range 10 { + for i := 0; i < 10; i++ { wg.Add(1) go createStream() } @@ -323,7 +323,8 @@ func TestCreateStreamIsConcurrencySafe(t *testing.T) { // TestNoBackoffWhenCreatingStream checks that backoff is not enabled between attempts to connect to a remote peer // for one-to-one direct communication. func TestNoBackoffWhenCreatingStream(t *testing.T) { - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() // setup per node contexts so they can be stopped independently ctx1, cancel1 := context.WithCancel(ctx) @@ -377,7 +378,7 @@ func TestNoBackoffWhenCreatingStream(t *testing.T) { // In this case, there will be MaxDialRetryAttemptTimes (3) connection attempts on the first CreateStream() call and MaxDialRetryAttemptTimes (3) attempts on the second CreateStream() call. // make two separate stream creation attempt and assert that no connection back off happened - for range 2 { + for i := 0; i < 2; i++ { // limit the maximum amount of time to wait for a connection to be established by using a context that times out ctx, cancel := context.WithTimeout(ctx, maxTimeToWait) diff --git a/network/p2p/node/resourceManager_test.go b/network/p2p/node/resourceManager_test.go index 4ff370be5a1..b68624fd604 100644 --- a/network/p2p/node/resourceManager_test.go +++ b/network/p2p/node/resourceManager_test.go @@ -72,12 +72,14 @@ func TestCreateStream_InboundConnResourceLimit(t *testing.T) { // streams this indicates a bug in the libp2p PeerBaseLimitConnsInbound limit. defaultProtocolID := protocols.FlowProtocolID(sporkID) expectedNumOfStreams := int64(50) - for range expectedNumOfStreams { - allStreamsCreated.Go(func() { + for i := int64(0); i < expectedNumOfStreams; i++ { + allStreamsCreated.Add(1) + go func() { + defer allStreamsCreated.Done() require.NoError(t, sender.Host().Connect(ctx, receiver.Host().Peerstore().PeerInfo(receiver.ID()))) _, err := sender.Host().NewStream(ctx, receiver.ID(), defaultProtocolID) require.NoError(t, err) - }) + }() } unittest.RequireReturnsBefore(t, allStreamsCreated.Wait, 2*time.Second, "could not create streams on time") @@ -374,7 +376,7 @@ func testCreateStreamInboundStreamResourceLimits(t *testing.T, cfg *testPeerLimi streamListMu := sync.Mutex{} // mutex to protect the streamsList. streamsList := make([]network.Stream, 0) // list of all streams created to avoid garbage collection. for sIndex := range senders { - for range loadLimit { + for i := 0; i < loadLimit; i++ { allStreamsCreated.Add(1) go func(sIndex int) { defer allStreamsCreated.Done() diff --git a/network/p2p/scoring/internal/appSpecificScoreCache_test.go b/network/p2p/scoring/internal/appSpecificScoreCache_test.go index a7ef3490e3d..bea5f355833 100644 --- a/network/p2p/scoring/internal/appSpecificScoreCache_test.go +++ b/network/p2p/scoring/internal/appSpecificScoreCache_test.go @@ -148,7 +148,7 @@ func TestAppSpecificScoreCache_Eviction(t *testing.T) { require.Equal(t, len(peerIds), len(scores), "peer ids and scores must have the same length") // add scores to cache - for i := range peerIds { + for i := 0; i < len(peerIds); i++ { err := cache.AdjustWithInit(peerIds[i], scores[i], time.Now()) require.Nil(t, err, "failed to add score to cache") } diff --git a/network/p2p/scoring/internal/subscriptionCache_test.go b/network/p2p/scoring/internal/subscriptionCache_test.go index 8b05d7eac48..54b88707702 100644 --- a/network/p2p/scoring/internal/subscriptionCache_test.go +++ b/network/p2p/scoring/internal/subscriptionCache_test.go @@ -244,10 +244,12 @@ func TestSubscriptionCache_ConcurrentUpdate(t *testing.T) { for _, topic := range topics { pid := pid topic := topic - allUpdatesDone.Go(func() { + allUpdatesDone.Add(1) + go func() { + defer allUpdatesDone.Done() _, err := cache.AddWithInitTopicForPeer(pid, topic) require.NoError(t, err, "adding topic to peer should not produce an error") - }) + }() } } @@ -256,11 +258,14 @@ func TestSubscriptionCache_ConcurrentUpdate(t *testing.T) { // verify that all peers have all topics; concurrently allTopicsVerified := sync.WaitGroup{} for _, pid := range peerIds { - allTopicsVerified.Go(func() { + pid := pid + allTopicsVerified.Add(1) + go func() { + defer allTopicsVerified.Done() topics, found := cache.GetSubscribedTopics(pid) require.True(t, found, "peer should be found") require.ElementsMatch(t, topics, topics, "retrieved topics should match the added topics") - }) + }() } unittest.RequireReturnsBefore(t, allTopicsVerified.Wait, 1*time.Second, "all topics were not verified in time") diff --git a/network/p2p/scoring/registry_test.go b/network/p2p/scoring/registry_test.go index b767235ca3a..7b8bb9fe3d2 100644 --- a/network/p2p/scoring/registry_test.go +++ b/network/p2p/scoring/registry_test.go @@ -5,7 +5,6 @@ import ( "fmt" "io" "math" - "slices" "sync" "testing" "time" @@ -1259,12 +1258,19 @@ func withStakedIdentities(peerIds ...peer.ID) func(cfg *scoring.GossipSubAppSpec return func(cfg *scoring.GossipSubAppSpecificScoreRegistryConfig) { cfg.IdProvider.(*mock.IdentityProvider).On("ByPeerID", testifymock.AnythingOfType("peer.ID")). Return(func(pid peer.ID) *flow.Identity { - if slices.Contains(peerIds, pid) { - return unittest.IdentityFixture() + for _, peerID := range peerIds { + if peerID == pid { + return unittest.IdentityFixture() + } } return nil }, func(pid peer.ID) bool { - return slices.Contains(peerIds, pid) + for _, peerID := range peerIds { + if peerID == pid { + return true + } + } + return false }).Maybe() } } @@ -1276,8 +1282,10 @@ func withValidSubscriptions(peerIds ...peer.ID) func(cfg *scoring.GossipSubAppSp cfg.Validator.(*mockp2p.SubscriptionValidator). On("CheckSubscribedToAllowedTopics", testifymock.AnythingOfType("peer.ID"), testifymock.Anything). Return(func(pid peer.ID, _ flow.Role) error { - if slices.Contains(peerIds, pid) { - return nil + for _, peerID := range peerIds { + if peerID == pid { + return nil + } } return fmt.Errorf("invalid subscriptions") }).Maybe() diff --git a/network/p2p/scoring/scoring_test.go b/network/p2p/scoring/scoring_test.go index 5f08d1b8365..fb85db3e06a 100644 --- a/network/p2p/scoring/scoring_test.go +++ b/network/p2p/scoring/scoring_test.go @@ -109,13 +109,13 @@ func TestInvalidCtrlMsgScoringIntegration(t *testing.T) { p2ptest.LetNodesDiscoverEachOther(t, ctx, nodes, ids) blockTopic := channels.TopicFromChannel(channels.PushBlocks, sporkId) // checks end-to-end message delivery works on GossipSub. - p2ptest.EnsurePubsubMessageExchange(t, ctx, nodes, blockTopic, 1, func() any { + p2ptest.EnsurePubsubMessageExchange(t, ctx, nodes, blockTopic, 1, func() interface{} { return (*messages.Proposal)(unittest.ProposalFixture()) }) // simulates node2 spamming node1 with invalid gossipsub control messages until node2 gets dissallow listed. // since the decay will start lower than .99 and will only be incremented by default .01, we need to spam a lot of messages so that the node gets disallow listed - for range 750 { + for i := 0; i < 750; i++ { notificationConsumer.OnInvalidControlMessageNotification(&p2p.InvCtrlMsgNotif{ PeerID: node2.ID(), MsgType: p2pmsg.ControlMessageTypes()[rand.Intn(len(p2pmsg.ControlMessageTypes()))], @@ -135,7 +135,7 @@ func TestInvalidCtrlMsgScoringIntegration(t *testing.T) { flow.IdentifierList{id2.NodeID}, blockTopic, 1, - func() any { + func() interface{} { return (*messages.Proposal)(unittest.ProposalFixture()) }) } diff --git a/network/p2p/test/fixtures.go b/network/p2p/test/fixtures.go index 8032982da96..88f3c7667cd 100644 --- a/network/p2p/test/fixtures.go +++ b/network/p2p/test/fixtures.go @@ -439,7 +439,7 @@ func NodesFixture(t *testing.T, // creating nodes var identities flow.IdentityList - for range count { + for i := 0; i < count; i++ { // create a node on localhost with a random port assigned by the OS node, identity := NodeFixture(t, sporkID, dhtPrefix, idProvider, opts...) nodes = append(nodes, node) @@ -628,7 +628,7 @@ func EnsureStreamCreationInBothDirections(t *testing.T, ctx context.Context, nod // // Note-1: this function assumes a timeout of 5 seconds for each message to be received. // Note-2: TryConnectionAndEnsureConnected() must be called to connect all nodes before calling this function. -func EnsurePubsubMessageExchange(t *testing.T, ctx context.Context, nodes []p2p.LibP2PNode, topic channels.Topic, count int, messageFactory func() any) { +func EnsurePubsubMessageExchange(t *testing.T, ctx context.Context, nodes []p2p.LibP2PNode, topic channels.Topic, count int, messageFactory func() interface{}) { subs := make([]p2p.Subscription, len(nodes)) for i, node := range nodes { ps, err := node.Subscribe(topic, validator.TopicValidator(unittest.Logger(), unittest.AllowAllPeerFilter())) @@ -640,7 +640,7 @@ func EnsurePubsubMessageExchange(t *testing.T, ctx context.Context, nodes []p2p. time.Sleep(1 * time.Second) for _, node := range nodes { - for range count { + for i := 0; i < count; i++ { // creates a unique message to be published by the node payload := messageFactory() outgoingMessageScope, err := message.NewOutgoingScope(flow.IdentifierList{unittest.IdentifierFixture()}, @@ -679,7 +679,7 @@ func EnsurePubsubMessageExchangeFromNode(t *testing.T, receiverIdentifier flow.Identifier, topic channels.Topic, count int, - messageFactory func() any) { + messageFactory func() interface{}) { _, err := sender.Subscribe(topic, validator.TopicValidator(unittest.Logger(), unittest.AllowAllPeerFilter())) require.NoError(t, err) @@ -689,7 +689,7 @@ func EnsurePubsubMessageExchangeFromNode(t *testing.T, // let subscriptions propagate time.Sleep(1 * time.Second) - for range count { + for i := 0; i < count; i++ { // creates a unique message to be published by the node payload := messageFactory() outgoingMessageScope, err := message.NewOutgoingScope(flow.IdentifierList{receiverIdentifier}, @@ -732,7 +732,7 @@ func EnsureNoPubsubMessageExchange(t *testing.T, toIdentifiers flow.IdentifierList, topic channels.Topic, count int, - messageFactory func() any) { + messageFactory func() interface{}) { subs := make([]p2p.Subscription, len(to)) tv := validator.TopicValidator(unittest.Logger(), unittest.AllowAllPeerFilter()) var err error @@ -752,8 +752,10 @@ func EnsureNoPubsubMessageExchange(t *testing.T, wg := &sync.WaitGroup{} for _, node := range from { - for range count { - wg.Go(func() { + node := node // capture range variable + for i := 0; i < count; i++ { + wg.Add(1) + go func() { // creates a unique message to be published by the node. payload := messageFactory() @@ -764,7 +766,8 @@ func EnsureNoPubsubMessageExchange(t *testing.T, ctx, cancel := context.WithTimeout(ctx, 5*time.Second) p2pfixtures.SubsMustNeverReceiveAnyMessage(t, ctx, subs) cancel() - }) + wg.Done() + }() } } @@ -792,7 +795,7 @@ func EnsureNoPubsubExchangeBetweenGroups(t *testing.T, groupBIdentifiers flow.IdentifierList, topic channels.Topic, count int, - messageFactory func() any) { + messageFactory func() interface{}) { // ensure no message exchange from group A to group B EnsureNoPubsubMessageExchange(t, ctx, groupANodes, groupBNodes, groupBIdentifiers, topic, count, messageFactory) // ensure no message exchange from group B to group A @@ -808,7 +811,7 @@ func EnsureNoPubsubExchangeBetweenGroups(t *testing.T, // - peer.IDSlice: slice of peer IDs func PeerIdSliceFixture(t *testing.T, n int) peer.IDSlice { ids := make([]peer.ID, n) - for i := range n { + for i := 0; i < n; i++ { ids[i] = unittest.PeerIdFixture(t) } return ids @@ -831,7 +834,7 @@ func NewConnectionGater(idProvider module.IdentityProvider, allowListFilter p2p. func GossipSubRpcFixtures(t *testing.T, count int) []*pb.RPC { c := 10 rpcs := make([]*pb.RPC, 0) - for range count { + for i := 0; i < count; i++ { rpcs = append(rpcs, GossipSubRpcFixture(t, c, @@ -859,7 +862,7 @@ func GossipSubRpcFixture(t *testing.T, msgCnt int, opts ...GossipSubCtrlOption) numSubscriptions := 10 topicIdSize := 10 subscriptions := make([]*pb.RPC_SubOpts, numSubscriptions) - for i := range numSubscriptions { + for i := 0; i < numSubscriptions; i++ { subscribe := rand.Intn(2) == 1 topicID, err := randutils.GenerateRandomString(topicIdSize) require.NoError(t, err) @@ -871,7 +874,7 @@ func GossipSubRpcFixture(t *testing.T, msgCnt int, opts ...GossipSubCtrlOption) // generates random messages messages := make([]*pb.Message, msgCnt) - for i := range msgCnt { + for i := 0; i < msgCnt; i++ { messages[i] = GossipSubMessageFixture(t) } @@ -903,7 +906,7 @@ func GossipSubCtrlFixture(opts ...GossipSubCtrlOption) *pb.ControlMessage { func WithIHave(msgCount, msgIDCount int, topicId string) GossipSubCtrlOption { return func(msg *pb.ControlMessage) { iHaves := make([]*pb.ControlIHave, msgCount) - for i := range msgCount { + for i := 0; i < msgCount; i++ { iHaves[i] = &pb.ControlIHave{ TopicID: &topicId, MessageIDs: GossipSubMessageIdsFixture(msgIDCount), @@ -938,7 +941,7 @@ func WithIHaveMessageIDs(msgIDs []string, topicId string) GossipSubCtrlOption { func WithIWant(iWantCount int, msgIdsPerIWant int) GossipSubCtrlOption { return func(msg *pb.ControlMessage) { iWants := make([]*pb.ControlIWant, iWantCount) - for i := range iWantCount { + for i := 0; i < iWantCount; i++ { iWants[i] = &pb.ControlIWant{ MessageIDs: GossipSubMessageIdsFixture(msgIdsPerIWant), } @@ -951,7 +954,7 @@ func WithIWant(iWantCount int, msgIdsPerIWant int) GossipSubCtrlOption { func WithGraft(msgCount int, topicId string) GossipSubCtrlOption { return func(msg *pb.ControlMessage) { grafts := make([]*pb.ControlGraft, msgCount) - for i := range msgCount { + for i := 0; i < msgCount; i++ { grafts[i] = &pb.ControlGraft{ TopicID: &topicId, } @@ -977,7 +980,7 @@ func WithGrafts(topicIds ...string) GossipSubCtrlOption { func WithPrune(msgCount int, topicId string) GossipSubCtrlOption { return func(msg *pb.ControlMessage) { prunes := make([]*pb.ControlPrune, msgCount) - for i := range msgCount { + for i := 0; i < msgCount; i++ { prunes[i] = &pb.ControlPrune{ TopicID: &topicId, } @@ -1014,7 +1017,7 @@ func GossipSubTopicIdFixture() string { // GossipSubMessageIdsFixture returns a slice of random gossipSub message IDs of the given size. func GossipSubMessageIdsFixture(count int) []string { msgIds := make([]string, count) - for i := range count { + for i := 0; i < count; i++ { msgIds[i] = gossipSubMessageIdFixture() } return msgIds diff --git a/network/p2p/test/sporking_test.go b/network/p2p/test/sporking_test.go index 292c275f979..2d0d8e9586e 100644 --- a/network/p2p/test/sporking_test.go +++ b/network/p2p/test/sporking_test.go @@ -42,7 +42,8 @@ import ( // if it's network key is updated while the libp2p protocol ID remains the same func TestCrosstalkPreventionOnNetworkKeyChange(t *testing.T) { idProvider := unittest.NewUpdatableIDProvider(flow.IdentityList{}) - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() ctx1, cancel1 := context.WithCancel(ctx) signalerCtx1 := irrecoverable.NewMockSignalerContext(t, ctx1) @@ -126,7 +127,8 @@ func TestCrosstalkPreventionOnNetworkKeyChange(t *testing.T) { // if the Flow libp2p protocol ID is updated while the network keys are kept the same. func TestOneToOneCrosstalkPrevention(t *testing.T) { idProvider := unittest.NewUpdatableIDProvider(flow.IdentityList{}) - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() ctx1, cancel1 := context.WithCancel(ctx) signalerCtx1 := irrecoverable.NewMockSignalerContext(t, ctx1) @@ -190,7 +192,8 @@ func TestOneToOneCrosstalkPrevention(t *testing.T) { // if the channel is updated while the network keys are kept the same. func TestOneToKCrosstalkPrevention(t *testing.T) { idProvider := unittest.NewUpdatableIDProvider(flow.IdentityList{}) - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() ctx1, cancel1 := context.WithCancel(ctx) signalerCtx1 := irrecoverable.NewMockSignalerContext(t, ctx1) diff --git a/network/p2p/tracer/internal/duplicate_msgs_counter_cache_test.go b/network/p2p/tracer/internal/duplicate_msgs_counter_cache_test.go index 10f458e23a6..6e53d89ec1f 100644 --- a/network/p2p/tracer/internal/duplicate_msgs_counter_cache_test.go +++ b/network/p2p/tracer/internal/duplicate_msgs_counter_cache_test.go @@ -88,7 +88,7 @@ func TestDuplicateMessageTrackerCache_ConcurrentSameRecordInit(t *testing.T) { var wg sync.WaitGroup wg.Add(concurrentAttempts) - for range concurrentAttempts { + for i := 0; i < concurrentAttempts; i++ { go func() { defer wg.Done() gauge, found, err := cache.GetWithInit(peerID) diff --git a/network/p2p/tracer/internal/rpc_sent_cache_test.go b/network/p2p/tracer/internal/rpc_sent_cache_test.go index 4813cde8063..91cdeda6df3 100644 --- a/network/p2p/tracer/internal/rpc_sent_cache_test.go +++ b/network/p2p/tracer/internal/rpc_sent_cache_test.go @@ -84,7 +84,7 @@ func TestCache_ConcurrentSameRecordAdd(t *testing.T) { successGauge := atomic.Int32{} - for range concurrentAttempts { + for i := 0; i < concurrentAttempts; i++ { go func() { defer wg.Done() initSuccess := cache.add(messageID, controlMsgType) diff --git a/network/p2p/tracer/internal/rpc_sent_tracker_test.go b/network/p2p/tracer/internal/rpc_sent_tracker_test.go index 8bd0bb41583..938a998cf46 100644 --- a/network/p2p/tracer/internal/rpc_sent_tracker_test.go +++ b/network/p2p/tracer/internal/rpc_sent_tracker_test.go @@ -54,6 +54,7 @@ func TestRPCSentTracker_IHave(t *testing.T) { } iHaves := make([]*pb.ControlIHave, len(testCases)) for i, testCase := range testCases { + testCase := testCase iHaves[i] = &pb.ControlIHave{ MessageIDs: testCase.messageIDS, } @@ -130,7 +131,8 @@ func TestRPCSentTracker_ConcurrentTracking(t *testing.T) { numOfMsgIds := 100 numOfRPCs := 100 rpcs := make([]*pubsub.RPC, numOfRPCs) - for i := range numOfRPCs { + for i := 0; i < numOfRPCs; i++ { + i := i go func() { rpc := rpcFixture(withIhaves([]*pb.ControlIHave{{MessageIDs: unittest.IdentifierListFixture(numOfMsgIds).Strings()}})) require.NoError(t, tracker.Track(rpc)) @@ -210,7 +212,7 @@ func TestRPCSentTracker_LastHighestIHaveRPCSize(t *testing.T) { // mockIHaveFixture generate list of iHaves of size n. Each iHave will be created with m number of random message ids. func mockIHaveFixture(n, m int) []*pb.ControlIHave { iHaves := make([]*pb.ControlIHave, n) - for i := range n { + for i := 0; i < n; i++ { // topic does not have to be a valid flow topic, for teting purposes we can use a random string topic := unittest.IdentifierFixture().String() iHaves[i] = &pb.ControlIHave{ diff --git a/network/p2p/translator/unstaked_translator_test.go b/network/p2p/translator/unstaked_translator_test.go index 12e59b0cff9..d8ef5f82137 100644 --- a/network/p2p/translator/unstaked_translator_test.go +++ b/network/p2p/translator/unstaked_translator_test.go @@ -18,7 +18,7 @@ import ( // This test shows we can't use ECDSA P-256 keys for libp2p and expect PeerID <=> PublicKey bijections func TestIDTranslationP256(t *testing.T) { loops := 50 - for range loops { + for i := 0; i < loops; i++ { pID := createPeerIDFromAlgo(t, fcrypto.ECDSAP256) // check that we can not extract the public key back @@ -33,7 +33,7 @@ func TestIDTranslationP256(t *testing.T) { // This test shows we can use ECDSA Secp256k1 keys for libp2p and expect PeerID <=> PublicKey bijections func TestIDTranslationSecp256k1(t *testing.T) { loops := 50 - for range loops { + for i := 0; i < loops; i++ { pID := createPeerIDFromAlgo(t, fcrypto.ECDSASecp256k1) // check that we can extract the public key back diff --git a/network/p2p/unicast/cache/unicastConfigCache_test.go b/network/p2p/unicast/cache/unicastConfigCache_test.go index 2e703a75fdc..23d83f1a354 100644 --- a/network/p2p/unicast/cache/unicastConfigCache_test.go +++ b/network/p2p/unicast/cache/unicastConfigCache_test.go @@ -178,7 +178,9 @@ func TestConcurrent_Adjust_And_Get_Is_Safe(t *testing.T) { wg := sync.WaitGroup{} for i := 0; i < int(sizeLimit); i++ { // concurrently adjusts the unicast configs. - wg.Go(func() { + wg.Add(1) + go func() { + defer wg.Done() peerId := unittest.PeerIdFixture(t) updatedConfig, err := cache.AdjustWithInit(peerId, func(cfg unicast.Config) (unicast.Config, error) { cfg.StreamCreationRetryAttemptBudget = 2 // some random adjustment @@ -188,7 +190,7 @@ func TestConcurrent_Adjust_And_Get_Is_Safe(t *testing.T) { require.NoError(t, err) // concurrent adjustment must not fail. require.Equal(t, uint64(2), updatedConfig.StreamCreationRetryAttemptBudget) require.Equal(t, uint64(3), updatedConfig.ConsecutiveSuccessfulStream) - }) + }() } // assert that the unicast config for each peer is adjusted i times, concurrently. diff --git a/network/p2p/unicast/manager_test.go b/network/p2p/unicast/manager_test.go index 702fe00b778..1ab85e16cd8 100644 --- a/network/p2p/unicast/manager_test.go +++ b/network/p2p/unicast/manager_test.go @@ -1,6 +1,7 @@ package unicast_test import ( + "context" "fmt" "testing" @@ -133,7 +134,8 @@ func TestUnicastManager_SuccessfulStream(t *testing.T) { streamFactory.On("NewStream", mock.Anything, peerID, mock.Anything).Return(&p2ptest.MockStream{}, nil).Once() - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() s, err := mgr.CreateStream(ctx, peerID) require.NoError(t, err) @@ -162,7 +164,8 @@ func TestUnicastManager_StreamBackoff(t *testing.T) { Return(nil, fmt.Errorf("some error")). Times(int(cfg.NetworkConfig.Unicast.UnicastManager.MaxStreamCreationRetryAttemptTimes + 1)) - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() s, err := mgr.CreateStream(ctx, peerID) require.Error(t, err) @@ -192,7 +195,8 @@ func TestUnicastManager_StreamFactory_StreamBackoff(t *testing.T) { Return(nil, fmt.Errorf("some error")). Times(int(cfg.NetworkConfig.Unicast.UnicastManager.MaxStreamCreationRetryAttemptTimes + 1)) - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() s, err := mgr.CreateStream(ctx, peerID) require.Error(t, err) require.Nil(t, s) @@ -221,9 +225,10 @@ func TestUnicastManager_Stream_ConsecutiveStreamCreation_Increment(t *testing.T) // mocks that it attempts to create a stream 10 times, and each time it succeeds. streamFactory.On("NewStream", mock.Anything, peerID, mock.Anything).Return(&p2ptest.MockStream{}, nil).Times(totalSuccessAttempts) - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() - for i := range totalSuccessAttempts { + for i := 0; i < totalSuccessAttempts; i++ { s, err := mgr.CreateStream(ctx, peerID) require.NoError(t, err) require.NotNil(t, s) @@ -260,7 +265,8 @@ func TestUnicastManager_Stream_ConsecutiveStreamCreation_Reset(t *testing.T) { require.NoError(t, err) require.Equal(t, uint64(5), adjustedUnicastConfig.ConsecutiveSuccessfulStream) - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() s, err := mgr.CreateStream(ctx, peerID) require.Error(t, err) @@ -286,7 +292,8 @@ func TestUnicastManager_StreamFactory_ErrProtocolNotSupported(t *testing.T) { Return(nil, stream.NewProtocolNotSupportedErr(peerID, protocol.ID("protocol-1"), fmt.Errorf("some error"))). Once() - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() s, err := mgr.CreateStream(ctx, peerID) require.Error(t, err) require.Nil(t, s) @@ -307,7 +314,8 @@ func TestUnicastManager_StreamFactory_ErrNoAddresses(t *testing.T) { Return(nil, fmt.Errorf("some error to ensure wrapping works fine: %w", swarm.ErrNoAddresses)). Once() - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() s, err := mgr.CreateStream(ctx, peerID) require.Error(t, err) require.Nil(t, s) @@ -335,7 +343,8 @@ func TestUnicastManager_Stream_ErrSecurityProtocolNegotiationFailed(t *testing.T Return(nil, stream.NewSecurityProtocolNegotiationErr(peerID, fmt.Errorf("some error"))). Once() - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() s, err := mgr.CreateStream(ctx, peerID) require.Error(t, err) require.Nil(t, s) @@ -361,7 +370,8 @@ func TestUnicastManager_StreamFactory_ErrGaterDisallowedConnection(t *testing.T) Return(nil, stream.NewGaterDisallowedConnectionErr(fmt.Errorf("some error"))). Once() - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() s, err := mgr.CreateStream(ctx, peerID) require.Error(t, err) require.Nil(t, s) @@ -396,7 +406,8 @@ func TestUnicastManager_Stream_BackoffBudgetDecremented(t *testing.T) { Return(nil, fmt.Errorf("some error")). Times(int(totalAttempts)) - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() for i := 0; i < int(maxStreamRetryBudget); i++ { s, err := mgr.CreateStream(ctx, peerID) require.Error(t, err) @@ -448,7 +459,8 @@ func TestUnicastManager_Stream_BackoffBudgetResetToDefault(t *testing.T) { require.Equal(t, uint64(0), adjustedCfg.StreamCreationRetryAttemptBudget) require.Equal(t, cfg.NetworkConfig.Unicast.UnicastManager.StreamZeroRetryResetThreshold+1, adjustedCfg.ConsecutiveSuccessfulStream) - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() s, err := mgr.CreateStream(ctx, peerID) require.NoError(t, err) @@ -480,7 +492,8 @@ func TestUnicastManager_Stream_NoBackoff_When_Budget_Is_Zero(t *testing.T) { require.Equal(t, uint64(0), adjustedCfg.StreamCreationRetryAttemptBudget) require.Equal(t, uint64(2), adjustedCfg.ConsecutiveSuccessfulStream) - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() s, err := mgr.CreateStream(ctx, peerID) require.Error(t, err) diff --git a/network/p2p/unicast/protocols/internal/compressedStream_test.go b/network/p2p/unicast/protocols/internal/compressedStream_test.go index 5d220aa5c57..e4ebee9b547 100644 --- a/network/p2p/unicast/protocols/internal/compressedStream_test.go +++ b/network/p2p/unicast/protocols/internal/compressedStream_test.go @@ -25,17 +25,21 @@ func TestHappyPath(t *testing.T) { // writes on stream mca writeWG := sync.WaitGroup{} - writeWG.Go(func() { + writeWG.Add(1) + go func() { + defer writeWG.Done() n, err := mca.Write(textByte) require.NoError(t, err) require.Equal(t, n, len(text)) - }) + }() // write on stream mca should be read on steam mcb readWG := sync.WaitGroup{} - readWG.Go(func() { + readWG.Add(1) + go func() { + defer readWG.Done() b := make([]byte, textByteLen) n, err := mcb.Read(b) @@ -43,7 +47,7 @@ func TestHappyPath(t *testing.T) { require.Equal(t, n, textByteLen) require.Equal(t, b, textByte) - }) + }() unittest.RequireReturnsBefore(t, writeWG.Wait, 1*time.Second, "timeout for writing on stream") unittest.RequireReturnsBefore(t, readWG.Wait, 1*time.Second, "timeout for reading from stream") @@ -62,18 +66,22 @@ func TestUnhappyPath(t *testing.T) { // writes on sa (uncompressed) writeWG := sync.WaitGroup{} - writeWG.Go(func() { + writeWG.Add(1) + go func() { + defer writeWG.Done() // writes data uncompressed n, err := sa.Write(textByte) require.NoError(t, err) require.Equal(t, n, len(text)) - }) + }() // write on uncompressed stream sa should NOT be read on compressed steam mcb readWG := sync.WaitGroup{} - readWG.Go(func() { + readWG.Add(1) + go func() { + defer readWG.Done() b := make([]byte, textByteLen) n, err := mcb.Read(b) @@ -84,7 +92,7 @@ func TestUnhappyPath(t *testing.T) { // b on reader side. require.Equal(t, n, 0) require.Equal(t, b, make([]byte, textByteLen)) - }) + }() unittest.RequireReturnsBefore(t, writeWG.Wait, 1*time.Second, "timeout for writing on stream") unittest.RequireReturnsBefore(t, readWG.Wait, 1*time.Second, "timeout for reading from stream") diff --git a/network/p2p/utils/ratelimiter/internal/rate_limiter_map_test.go b/network/p2p/utils/ratelimiter/internal/rate_limiter_map_test.go index 3d56927393a..79bbe0fad6a 100644 --- a/network/p2p/utils/ratelimiter/internal/rate_limiter_map_test.go +++ b/network/p2p/utils/ratelimiter/internal/rate_limiter_map_test.go @@ -71,7 +71,8 @@ func TestLimiterMap_cleanup(t *testing.T) { limiter, _ = m.Get(peerID3) limiter.SetLastAccessed(start.Add(-20 * time.Minute)) - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() signalerCtx := irrecoverable.NewMockSignalerContext(t, ctx) // kick off clean up process, tick should happen immediately diff --git a/network/proxy/network_test.go b/network/proxy/network_test.go index d274a56c962..c9ec7dc06c0 100644 --- a/network/proxy/network_test.go +++ b/network/proxy/network_test.go @@ -14,7 +14,7 @@ import ( "github.com/onflow/flow-go/utils/unittest" ) -func getEvent() any { +func getEvent() interface{} { return struct { foo string }{ @@ -71,7 +71,7 @@ func (suite *Suite) TestPublish() { channel := channels.TestNetworkChannel targetIDs := make([]flow.Identifier, 10) - for range 10 { + for i := 0; i < 10; i++ { targetIDs = append(targetIDs, unittest.IdentifierFixture()) } @@ -95,7 +95,7 @@ func (suite *Suite) TestMulticast() { channel := channels.TestNetworkChannel targetIDs := make([]flow.Identifier, 10) - for range 10 { + for i := 0; i < 10; i++ { targetIDs = append(targetIDs, unittest.IdentifierFixture()) } diff --git a/network/queue/messageQueue_test.go b/network/queue/messageQueue_test.go index ddd5442f028..4e316749780 100644 --- a/network/queue/messageQueue_test.go +++ b/network/queue/messageQueue_test.go @@ -165,7 +165,8 @@ func testQueue(t *testing.T, messages map[string]queue.Priority) { func BenchmarkPush(b *testing.B) { b.StopTimer() - ctx := b.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() var mq = queue.NewMessageQueue(ctx, randomPriority, metrics.NewNoopCollector(), 0) for i := 0; i < b.N; i++ { err := mq.Insert("test") @@ -184,7 +185,8 @@ func BenchmarkPush(b *testing.B) { func BenchmarkPop(b *testing.B) { b.StopTimer() - ctx := b.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() var mq = queue.NewMessageQueue(ctx, randomPriority, metrics.NewNoopCollector(), 0) for i := 0; i < b.N; i++ { err := mq.Insert("test") @@ -222,13 +224,14 @@ func randomPriority(_ any) (queue.Priority, error) { // TestQueueFull tests that inserting into a full queue returns ErrQueueFull func TestQueueFull(t *testing.T) { - ctx := t.Context() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() maxSize := 10 mq := queue.NewMessageQueue(ctx, fixedPriority, metrics.NewNoopCollector(), maxSize) // fill the queue to capacity - for range maxSize { + for i := 0; i < maxSize; i++ { err := mq.Insert("message") assert.NoError(t, err) } diff --git a/network/stub/hash.go b/network/stub/hash.go index 4fa550e0bdd..dd119bafa76 100644 --- a/network/stub/hash.go +++ b/network/stub/hash.go @@ -15,7 +15,7 @@ import ( func eventKey(from flow.Identifier, channel channels.Channel, event any) (string, error) { marshaler := json.NewMarshaler() - tag, err := marshaler.Marshal(fmt.Appendf(nil, "testthenetwork %s %T", channel, event)) + tag, err := marshaler.Marshal([]byte(fmt.Sprintf("testthenetwork %s %T", channel, event))) if err != nil { return "", fmt.Errorf("could not encode the tag: %w", err) } diff --git a/network/test/cohort1/meshengine_test.go b/network/test/cohort1/meshengine_test.go index b1409d1631c..0ee19c0dde3 100644 --- a/network/test/cohort1/meshengine_test.go +++ b/network/test/cohort1/meshengine_test.go @@ -92,7 +92,7 @@ func (suite *MeshEngineTestSuite) SetupTest() { require.NoError(suite.T(), err) opts := []p2ptest.NodeFixtureParameterOption{p2ptest.WithUnicastHandlerFunc(nil)} - for range count { + for i := 0; i < count; i++ { connManager, err := testutils.NewTagWatchingConnManager( unittest.Logger(), metrics.NewNoopCollector(), @@ -280,7 +280,7 @@ func (suite *MeshEngineTestSuite) allToAllScenario(send testutils.ConduitSendWra receivedIndices, err := extractSenderID(count, e.Event, "hello from node") require.NoError(suite.Suite.T(), err) - for j := range count { + for j := 0; j < count; j++ { // evaluates self-gossip if j == index { assert.False(suite.Suite.T(), (receivedIndices)[index], fmt.Sprintf("self gossiped for node %v detected", index)) @@ -469,7 +469,7 @@ func (suite *MeshEngineTestSuite) conduitCloseScenario(send testutils.ConduitSen wg.Add(1) go func(e *testutils.MeshEngine) { expectedMsgCnt := count - 2 // count less self and unsubscribed engine - for range expectedMsgCnt { + for x := 0; x < expectedMsgCnt; x++ { <-e.Received } wg.Done() @@ -496,11 +496,11 @@ func assertChannelReceived(t *testing.T, e *testutils.MeshEngine, channel channe // events is the channel of received events // expectedMsgTxt is the common prefix among all the messages that we expect to receive, for example // we expect to receive "hello from node x" in this test, and then expectedMsgTxt is "hello form node" -func extractSenderID(enginesNum int, events chan any, expectedMsgTxt string) ([]bool, error) { +func extractSenderID(enginesNum int, events chan interface{}, expectedMsgTxt string) ([]bool, error) { indices := make([]bool, enginesNum) expectedMsgSize := len(expectedMsgTxt) for i := 0; i < enginesNum-1; i++ { - var event any + var event interface{} select { case event = <-events: default: diff --git a/network/test/cohort1/network_test.go b/network/test/cohort1/network_test.go index 03814dcddea..70b926c362e 100644 --- a/network/test/cohort1/network_test.go +++ b/network/test/cohort1/network_test.go @@ -69,7 +69,7 @@ type tagsObserver struct { log zerolog.Logger } -func (co *tagsObserver) OnNext(peertag any) { +func (co *tagsObserver) OnNext(peertag interface{}) { pt, ok := peertag.(testutils.PeerTag) if ok { @@ -368,7 +368,7 @@ func (suite *NetworkTestSuite) TestUnicastRateLimit_Messages() { // with the rate limit configured to 5 msg/sec we send 10 messages at once and expect the rate limiter // to be invoked at-least once. We send 10 messages due to the flakiness that is caused by async stream // handling of streams. - for i := range 10 { + for i := 0; i < 10; i++ { err = con0.Unicast(&libp2pmessage.TestMessage{ Text: fmt.Sprintf("hello-%d", i), }, newId.NodeID) @@ -691,7 +691,7 @@ func (suite *NetworkTestSuite) MultiPing(count int) { receivedPayloads.Add(msgPayload.Text, struct{}{}) }).Return(nil) - for i := range count { + for i := 0; i < count; i++ { receiveWG.Add(1) sendWG.Add(1) diff --git a/network/test/cohort2/blob_service_test.go b/network/test/cohort2/blob_service_test.go index ba910c13da4..ed31131d0cc 100644 --- a/network/test/cohort2/blob_service_test.go +++ b/network/test/cohort2/blob_service_test.go @@ -109,7 +109,7 @@ func (suite *BlobServiceTestSuite) SetupTest() { for i, net := range suite.networks { ds := sync.MutexWrap(datastore.NewMapDatastore()) suite.datastores = append(suite.datastores, ds) - blob := blobs.NewBlob(fmt.Appendf(nil, "foo%v", i)) + blob := blobs.NewBlob([]byte(fmt.Sprintf("foo%v", i))) suite.blobCids = append(suite.blobCids, blob.Cid()) suite.putBlob(ds, blob) blobService, err := net.RegisterBlobService(blobExchangeChannel, ds) @@ -207,7 +207,7 @@ func (suite *BlobServiceTestSuite) TestHas() { var blobsToGet []cid.Cid for j := 0; j < suite.numNodes; j++ { if j != i { - blob := blobs.NewBlob(fmt.Appendf(nil, "bar%v", i)) + blob := blobs.NewBlob([]byte(fmt.Sprintf("bar%v", i))) blobsToGet = append(blobsToGet, blob.Cid()) unreceivedBlobs[i][blob.Cid()] = struct{}{} } @@ -239,7 +239,7 @@ func (suite *BlobServiceTestSuite) TestHas() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - err := bex.AddBlob(ctx, blobs.NewBlob(fmt.Appendf(nil, "bar%v", i))) + err := bex.AddBlob(ctx, blobs.NewBlob([]byte(fmt.Sprintf("bar%v", i)))) suite.Require().NoError(err) } diff --git a/network/test/cohort2/echoengine.go b/network/test/cohort2/echoengine.go index c6930e3fcc4..1ad06064c53 100644 --- a/network/test/cohort2/echoengine.go +++ b/network/test/cohort2/echoengine.go @@ -24,7 +24,7 @@ type EchoEngine struct { t *testing.T con network.Conduit // used to directly communicate with the network originID flow.Identifier // used to keep track of the id of the sender of the messages - event chan any // used to keep track of the events that the node receives + event chan interface{} // used to keep track of the events that the node receives channel chan channels.Channel // used to keep track of the channels that events are received on received chan struct{} // used as an indicator on reception of messages for testing echomsg string // used as a fix string to be included in the reply echos @@ -38,7 +38,7 @@ func NewEchoEngine(t *testing.T, net network.EngineRegistry, cap int, channel ch te := &EchoEngine{ t: t, echomsg: "this is an echo", - event: make(chan any, cap), + event: make(chan interface{}, cap), channel: make(chan channels.Channel, cap), received: make(chan struct{}, cap), seen: make(map[string]int), @@ -55,13 +55,13 @@ func NewEchoEngine(t *testing.T, net network.EngineRegistry, cap int, channel ch // SubmitLocal is implemented for a valid type assertion to Engine // any call to it fails the test -func (te *EchoEngine) SubmitLocal(event any) { +func (te *EchoEngine) SubmitLocal(event interface{}) { require.Fail(te.t, "not implemented") } // Submit is implemented for a valid type assertion to Engine // any call to it fails the test -func (te *EchoEngine) Submit(channel channels.Channel, originID flow.Identifier, event any) { +func (te *EchoEngine) Submit(channel channels.Channel, originID flow.Identifier, event interface{}) { go func() { err := te.Process(channel, originID, event) if err != nil { @@ -72,7 +72,7 @@ func (te *EchoEngine) Submit(channel channels.Channel, originID flow.Identifier, // ProcessLocal is implemented for a valid type assertion to Engine // any call to it fails the test -func (te *EchoEngine) ProcessLocal(event any) error { +func (te *EchoEngine) ProcessLocal(event interface{}) error { require.Fail(te.t, "not implemented") return fmt.Errorf(" unexpected method called") } @@ -80,7 +80,7 @@ func (te *EchoEngine) ProcessLocal(event any) error { // Process receives an originID and an event and casts them into the corresponding fields of the // EchoEngine. It then flags the received channel on reception of an event. // It also sends back an echo of the message to the origin ID -func (te *EchoEngine) Process(channel channels.Channel, originID flow.Identifier, event any) error { +func (te *EchoEngine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { te.Lock() defer te.Unlock() te.originID = originID diff --git a/network/test/cohort2/echoengine_test.go b/network/test/cohort2/echoengine_test.go index 9aa8ed7cfd4..c8dcde26d08 100644 --- a/network/test/cohort2/echoengine_test.go +++ b/network/test/cohort2/echoengine_test.go @@ -222,7 +222,7 @@ func (suite *EchoEngineTestSuite) duplicateMessageSequential(send testutils.Cond } // sends the same message 10 times - for range 10 { + for i := 0; i < 10; i++ { require.NoError(suite.Suite.T(), send(event, sender.con, suite.ids[rcvID].NodeID)) } @@ -258,10 +258,12 @@ func (suite *EchoEngineTestSuite) duplicateMessageParallel(send testutils.Condui // sends the same message 10 times wg := sync.WaitGroup{} - for range 10 { - wg.Go(func() { + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { require.NoError(suite.Suite.T(), send(event, sender.con, suite.ids[rcvID].NodeID)) - }) + wg.Done() + }() } unittest.RequireReturnsBefore(suite.T(), wg.Wait, 3*time.Second, "could not send message on time") @@ -314,14 +316,16 @@ func (suite *EchoEngineTestSuite) duplicateMessageDifferentChan(send testutils.C // sends the same message 10 times on both channels wg := sync.WaitGroup{} - for range 10 { - wg.Go(func() { + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { + defer wg.Done() // sender1 to receiver1 on channel1 require.NoError(suite.Suite.T(), send(event, sender1.con, suite.ids[rcvNode].NodeID)) // sender2 to receiver2 on channel2 require.NoError(suite.Suite.T(), send(event, sender2.con, suite.ids[rcvNode].NodeID)) - }) + }() } unittest.RequireReturnsBefore(suite.T(), wg.Wait, 3*time.Second, "could not handle sending unicasts on time") time.Sleep(1 * time.Second) @@ -421,7 +425,7 @@ func (suite *EchoEngineTestSuite) multiMessageSync(echo bool, count int, send te // allow nodes to heartbeat and discover each other testutils.OptionalSleep(send) - for i := range count { + for i := 0; i < count; i++ { // Send the message to receiver event := &message.TestMessage{ Text: fmt.Sprintf("hello%d", i), @@ -498,7 +502,7 @@ func (suite *EchoEngineTestSuite) multiMessageAsync(echo bool, count int, send t // keeps track of async received echo messages at sender side // echorcv := make(map[string]struct{}) - for i := range count { + for i := 0; i < count; i++ { // Send the message to node 2 using the conduit of node 1 event := &message.TestMessage{ Text: fmt.Sprintf("hello%d", i), @@ -506,7 +510,7 @@ func (suite *EchoEngineTestSuite) multiMessageAsync(echo bool, count int, send t require.NoError(suite.Suite.T(), send(event, sender.con, suite.ids[1].NodeID)) } - for range count { + for i := 0; i < count; i++ { select { case <-receiver.received: // evaluates reception of message at the other side @@ -541,7 +545,7 @@ func (suite *EchoEngineTestSuite) multiMessageAsync(echo bool, count int, send t } } - for range count { + for i := 0; i < count; i++ { // evaluates echo back if echo { // evaluates reception of echo response diff --git a/network/test/cohort2/epochtransition_test.go b/network/test/cohort2/epochtransition_test.go index 5c3edad4293..e5a22bfd80c 100644 --- a/network/test/cohort2/epochtransition_test.go +++ b/network/test/cohort2/epochtransition_test.go @@ -211,7 +211,7 @@ func (suite *MutableIdentityTableSuite) addNodes(count int) { } // create the test engines - for i := range count { + for i := 0; i < count; i++ { node := testNode{ id: ids[i], libp2pNode: nodes[i], @@ -436,7 +436,7 @@ func (suite *MutableIdentityTableSuite) exchangeMessages( for i := range allowedEngs { wg.Add(expectedMsgCnt) go func(e *testutils.MeshEngine) { - for range expectedMsgCnt { + for x := 0; x < expectedMsgCnt; x++ { <-e.Received wg.Done() } diff --git a/network/test/cohort2/unicast_authorization_test.go b/network/test/cohort2/unicast_authorization_test.go index cd1dab32506..b961a1766e7 100644 --- a/network/test/cohort2/unicast_authorization_test.go +++ b/network/test/cohort2/unicast_authorization_test.go @@ -260,7 +260,7 @@ func (u *UnicastAuthorizationTestSuite) TestUnicastAuthorization_UnknownMsgCode( invalidMessageCode := codec.MessageCode(byte('X')) // register a custom encoder that encodes the message with an invalid message code when encoding a string. - u.codec.RegisterEncoder(reflect.TypeFor[string](), func(v any) ([]byte, error) { + u.codec.RegisterEncoder(reflect.TypeOf(""), func(v interface{}) ([]byte, error) { e, err := unittest.NetworkCodec().Encode(&libp2pmessage.TestMessage{ Text: v.(string), }) @@ -312,7 +312,7 @@ func (u *UnicastAuthorizationTestSuite) TestUnicastAuthorization_WrongMsgCode() modifiedMessageCode := codec.CodeDKGMessage // register a custom encoder that overrides the message code when encoding a TestMessage. - u.codec.RegisterEncoder(reflect.TypeFor[*libp2pmessage.TestMessage](), func(v any) ([]byte, error) { + u.codec.RegisterEncoder(reflect.TypeOf(&libp2pmessage.TestMessage{}), func(v interface{}) ([]byte, error) { e, err := unittest.NetworkCodec().Encode(v) require.NoError(u.T(), err) e[0] = modifiedMessageCode.Uint8() @@ -594,7 +594,7 @@ func (u *UnicastAuthorizationTestSuite) TestUnicastAuthorization_UnauthorizedSen // We specifically use this to override the encoder for the TestMessage type to encode it with an invalid message code. type overridableMessageEncoder struct { codec network.Codec - specificEncoder map[reflect.Type]func(any) ([]byte, error) + specificEncoder map[reflect.Type]func(interface{}) ([]byte, error) } var _ network.Codec = (*overridableMessageEncoder)(nil) @@ -602,12 +602,12 @@ var _ network.Codec = (*overridableMessageEncoder)(nil) func newOverridableMessageEncoder(codec network.Codec) *overridableMessageEncoder { return &overridableMessageEncoder{ codec: codec, - specificEncoder: make(map[reflect.Type]func(any) ([]byte, error)), + specificEncoder: make(map[reflect.Type]func(interface{}) ([]byte, error)), } } // RegisterEncoder registers an encoder for a specific type, overriding the default encoder for that type. -func (u *overridableMessageEncoder) RegisterEncoder(t reflect.Type, encoder func(any) ([]byte, error)) { +func (u *overridableMessageEncoder) RegisterEncoder(t reflect.Type, encoder func(interface{}) ([]byte, error)) { u.specificEncoder[t] = encoder } @@ -623,7 +623,7 @@ func (u *overridableMessageEncoder) NewDecoder(r io.Reader) network.Decoder { // Encode encodes a value into a byte slice. If a specific encoder is registered for the type of the value, it will be used. // Otherwise, the default encoder will be used. -func (u *overridableMessageEncoder) Encode(v any) ([]byte, error) { +func (u *overridableMessageEncoder) Encode(v interface{}) ([]byte, error) { if encoder, ok := u.specificEncoder[reflect.TypeOf(v)]; ok { return encoder(v) } diff --git a/network/validator/authorized_sender_validator_test.go b/network/validator/authorized_sender_validator_test.go index a40ea223c10..58ade33594c 100644 --- a/network/validator/authorized_sender_validator_test.go +++ b/network/validator/authorized_sender_validator_test.go @@ -29,7 +29,7 @@ type TestCase struct { Identity *flow.Identity GetIdentity func(pid peer.ID) (*flow.Identity, bool) Channel channels.Channel - Message any + Message interface{} MessageCode codec.MessageCode MessageStr string Protocols message.Protocols diff --git a/network/validator/target_validator.go b/network/validator/target_validator.go index f87a6f6bff0..d02901b166e 100644 --- a/network/validator/target_validator.go +++ b/network/validator/target_validator.go @@ -1,8 +1,6 @@ package validator import ( - "slices" - "github.com/rs/zerolog" "github.com/onflow/flow-go/model/flow" @@ -31,8 +29,10 @@ func ValidateTarget(log zerolog.Logger, target flow.Identifier) network.MessageV // Validate returns true if the message is intended for the given target ID else it returns false func (tv *TargetValidator) Validate(msg network.IncomingMessageScope) bool { - if slices.Contains(msg.TargetIDs(), tv.target) { - return true + for _, t := range msg.TargetIDs() { + if tv.target == t { + return true + } } tv.log.Debug(). Hex("message_target_id", logging.ID(tv.target)). diff --git a/state/cluster/badger/mutator_test.go b/state/cluster/badger/mutator_test.go index 5e95340cece..cbf68967be3 100644 --- a/state/cluster/badger/mutator_test.go +++ b/state/cluster/badger/mutator_test.go @@ -428,7 +428,7 @@ func (suite *MutatorSuite) TestExtend_WithExpiredReferenceBlock() { // build enough blocks so that using genesis as a reference block causes // the collection to be expired parent := suite.protoGenesis - for range flow.DefaultTransactionExpiry + 1 { + for i := 0; i < flow.DefaultTransactionExpiry+1; i++ { next := unittest.BlockWithParentProtocolState(parent) err := suite.protoState.ExtendCertified(context.Background(), unittest.NewCertifiedBlock(next)) suite.Require().Nil(err) diff --git a/state/cluster/badger/snapshot_test.go b/state/cluster/badger/snapshot_test.go index dba0a7b6691..76db04a71f5 100644 --- a/state/cluster/badger/snapshot_test.go +++ b/state/cluster/badger/snapshot_test.go @@ -162,7 +162,7 @@ func (suite *SnapshotSuite) InsertSubtree(parent model.Block, depth, fanout int) return } - for range fanout { + for i := 0; i < fanout; i++ { proposal := suite.ProposalWithParentAndPayload(&parent, suite.Payload()) suite.InsertBlock(proposal) suite.InsertSubtree(proposal.Block, depth-1, fanout) @@ -275,7 +275,7 @@ func (suite *SnapshotSuite) TestPending_WithPendingBlocks() { // check with some finalized blocks parent := suite.genesis pendings := make([]flow.Identifier, 0, 10) - for range 10 { + for i := 0; i < 10; i++ { next := suite.ProposalWithParentAndPayload(parent, suite.Payload()) suite.InsertBlock(next) pendings = append(pendings, next.Block.ID()) diff --git a/state/fork/traversal_test.go b/state/fork/traversal_test.go index 53af5528755..111981375df 100644 --- a/state/fork/traversal_test.go +++ b/state/fork/traversal_test.go @@ -51,7 +51,7 @@ func (s *TraverseSuite) SetupTest() { s.genesis = genesis parent := genesis - for range 10 { + for i := 0; i < 10; i++ { child := unittest.BlockHeaderWithParentFixture(parent) s.byID[child.ID()] = child s.byHeight[child.Height] = child @@ -508,7 +508,7 @@ func (s *TraverseSuite) TestTraverse_OnDifferentForkThanTerminalBlock() { // make other fork otherForkHead := s.genesis otherForkByHeight := make(map[uint64]*flow.Header) - for range 10 { + for i := 0; i < 10; i++ { child := unittest.BlockHeaderWithParentFixture(otherForkHead) s.byID[child.ID()] = child otherForkByHeight[child.Height] = child diff --git a/state/protocol/badger/snapshot_test.go b/state/protocol/badger/snapshot_test.go index 6bfe7418c20..2925e0845c0 100644 --- a/state/protocol/badger/snapshot_test.go +++ b/state/protocol/badger/snapshot_test.go @@ -117,7 +117,7 @@ func TestSnapshot_Params(t *testing.T) { // build some non-root blocks head := rootHeader const nBlocks = 10 - for range nBlocks { + for i := 0; i < nBlocks; i++ { next := unittest.BlockWithParentAndPayload( head, unittest.PayloadFixture(unittest.WithProtocolStateID(rootProtocolStateID)), @@ -166,7 +166,7 @@ func TestSnapshot_Descendants(t *testing.T) { usedViews[head.View] = struct{}{} for forkLength := range []int{5, 4} { // construct two forks with length 5 and 4, respectively parent := head - for range forkLength { + for n := 0; n < forkLength; n++ { block := unittest.BlockWithParentAndPayloadAndUniqueView( parent, unittest.PayloadFixture(unittest.WithProtocolStateID(rootProtocolStateID)), @@ -265,7 +265,7 @@ func TestClusters(t *testing.T) { require.Equal(t, nClusters, len(expectedClusters)) require.Equal(t, len(expectedClusters), len(actualClusters)) - for i := range nClusters { + for i := 0; i < nClusters; i++ { expected := expectedClusters[i] actual := actualClusters[i] @@ -401,7 +401,7 @@ func TestSealingSegment(t *testing.T) { parent := block1 // build a large chain of intermediary blocks - for i := range 100 { + for i := 0; i < 100; i++ { next := unittest.BlockWithParentProtocolState(parent) if i == 0 { // Repetitions of the same receipt in one fork would be a protocol violation. @@ -735,7 +735,7 @@ func TestSealingSegment(t *testing.T) { blocks := make([]*flow.Block, 0, flow.DefaultTransactionExpiry+3) parent := root - for range flow.DefaultTransactionExpiry + 1 { + for i := 0; i < flow.DefaultTransactionExpiry+1; i++ { next := unittest.BlockFixture( unittest.Block.WithParent(parent.ID(), parent.View, parent.Height), unittest.Block.WithPayload(unittest.PayloadFixture( @@ -835,7 +835,7 @@ func TestSealingSegment(t *testing.T) { // build chain, so it's long enough to not target blocks as inside of flow.DefaultTransactionExpiry window. parent := block4 - for range int(1.5 * flow.DefaultTransactionExpiry) { + for i := 0; i < 1.5*flow.DefaultTransactionExpiry; i++ { next := unittest.BlockFixture( unittest.Block.WithParent(parent.ID(), parent.View, parent.Height), unittest.Block.WithPayload(unittest.PayloadFixture( diff --git a/state/protocol/badger/state_test.go b/state/protocol/badger/state_test.go index b45475ceb76..83c05b1e40c 100644 --- a/state/protocol/badger/state_test.go +++ b/state/protocol/badger/state_test.go @@ -428,7 +428,7 @@ func TestBootstrapNonRoot(t *testing.T) { seals := []*flow.Seal{seal1, seal2, seal3} parent := block3 - for range flow.DefaultTransactionExpiry - 1 { + for i := 0; i < flow.DefaultTransactionExpiry-1; i++ { next := unittest.BlockWithParentAndPayload(parent.ToHeader(), unittest.PayloadFixture( unittest.WithReceipts(receipts[0]), unittest.WithProtocolStateID(calculateExpectedStateId(t, mutableState)(parent.ID(), parent.View+1, []*flow.Seal{seals[0]})), diff --git a/state/protocol/datastore/params.go b/state/protocol/datastore/params.go index b8d49ba4316..7f6389b5abb 100644 --- a/state/protocol/datastore/params.go +++ b/state/protocol/datastore/params.go @@ -138,7 +138,7 @@ func NewVersionedInstanceParams( versionedInstanceParams := &flow.VersionedInstanceParams{ Version: version, } - var data any + var data interface{} switch version { case 0: data = InstanceParamsV0{ diff --git a/state/protocol/protocol_state/epochs/fallback_statemachine_test.go b/state/protocol/protocol_state/epochs/fallback_statemachine_test.go index aa593d93794..996c71a71ae 100644 --- a/state/protocol/protocol_state/epochs/fallback_statemachine_test.go +++ b/state/protocol/protocol_state/epochs/fallback_statemachine_test.go @@ -748,7 +748,7 @@ func (s *EpochFallbackStateMachineSuite) TestProcessingMultipleEventsInTheSameBl var events []flow.ServiceEvent setupEvents := rapid.IntRange(0, 5).Draw(t, "number-of-setup-events") - for range setupEvents { + for i := 0; i < setupEvents; i++ { serviceEvent := unittest.EpochSetupFixture().ServiceEvent() s.consumer.On("OnServiceEventReceived", serviceEvent).Once() s.consumer.On("OnInvalidServiceEvent", serviceEvent, @@ -757,7 +757,7 @@ func (s *EpochFallbackStateMachineSuite) TestProcessingMultipleEventsInTheSameBl } commitEvents := rapid.IntRange(0, 5).Draw(t, "number-of-commit-events") - for range commitEvents { + for i := 0; i < commitEvents; i++ { serviceEvent := unittest.EpochCommitFixture().ServiceEvent() s.consumer.On("OnServiceEventReceived", serviceEvent).Once() s.consumer.On("OnInvalidServiceEvent", serviceEvent, @@ -766,7 +766,7 @@ func (s *EpochFallbackStateMachineSuite) TestProcessingMultipleEventsInTheSameBl } recoverEvents := rapid.IntRange(0, 5).Draw(t, "number-of-recover-events") - for range recoverEvents { + for i := 0; i < recoverEvents; i++ { serviceEvent := unittest.EpochRecoverFixture().ServiceEvent() s.consumer.On("OnServiceEventReceived", serviceEvent).Once() s.consumer.On("OnInvalidServiceEvent", serviceEvent, diff --git a/state/protocol/protocol_state/epochs/identity_ejector.go b/state/protocol/protocol_state/epochs/identity_ejector.go index 44fb8e8d712..02fb1ee0439 100644 --- a/state/protocol/protocol_state/epochs/identity_ejector.go +++ b/state/protocol/protocol_state/epochs/identity_ejector.go @@ -44,14 +44,14 @@ func newEjector() ejector { func (e *ejector) Eject(nodeID flow.Identifier) bool { l := len(e.identityLists) if len(e.ejected) == 0 { // if this is the first ejection sealed in this block, we have to populate the lookup first - for i := range l { + for i := 0; i < l; i++ { e.identityLists[i].identityLookup = e.identityLists[i].dynamicIdentities.Lookup() } } e.ejected = append(e.ejected, nodeID) var nodeFound bool - for i := range l { + for i := 0; i < l; i++ { dynamicIdentity, found := e.identityLists[i].identityLookup[nodeID] if found { nodeFound = true diff --git a/state/protocol/protocol_state/state/mutable_protocol_state_test.go b/state/protocol/protocol_state/state/mutable_protocol_state_test.go index d31d03f161d..d2f0f3709ea 100644 --- a/state/protocol/protocol_state/state/mutable_protocol_state_test.go +++ b/state/protocol/protocol_state/state/mutable_protocol_state_test.go @@ -579,8 +579,8 @@ func (s *StateMutatorSuite) Test_EncodeFailed() { // emptySlice returns a functor for testing that the input `slice` (with element type `T`) // is empty. This functor is intended to be used with testify's `Matchby` -func emptySlice[T any]() func(any) bool { - return func(slice any) bool { +func emptySlice[T any]() func(interface{}) bool { + return func(slice interface{}) bool { s := slice.([]T) return len(s) == 0 } @@ -604,7 +604,7 @@ func (s *StateMutatorSuite) mockStateTransition() *mockStateTransition { // call. This is helpful for testing cases, where the state machine modifies the Protocol State. type mockStateTransition struct { T *testing.T - expectedServiceEvents any + expectedServiceEvents interface{} runInEvolveState func(_ mock.Arguments) } @@ -619,7 +619,7 @@ func (m *mockStateTransition) ExpectedServiceEvents(es []flow.ServiceEvent) *moc // ServiceEventsMatch provides an argument matcher to verify properties if the input slice of Service Events. // Note that `ExpectedServiceEvents` and `ServiceEventsMatch` override all prior checks for the input slice of Service Events. // The method returns a self-reference for chaining. -func (m *mockStateTransition) ServiceEventsMatch(fn func(arg any) bool) *mockStateTransition { +func (m *mockStateTransition) ServiceEventsMatch(fn func(arg interface{}) bool) *mockStateTransition { m.expectedServiceEvents = mock.MatchedBy(fn) return m } diff --git a/storage/badger/operation/common.go b/storage/badger/operation/common.go index 6fde7e534ee..c1deb1b7f5a 100644 --- a/storage/badger/operation/common.go +++ b/storage/badger/operation/common.go @@ -20,7 +20,7 @@ import ( // - storage.ErrAlreadyExists if the key already exists in the database. // - generic error in case of unexpected failure from the database layer or // encoding failure. -func insert(key []byte, entity any) func(*badger.Txn) error { +func insert(key []byte, entity interface{}) func(*badger.Txn) error { return func(tx *badger.Txn) error { // update the maximum key size if the inserted key is bigger @@ -63,7 +63,7 @@ func insert(key []byte, entity any) func(*badger.Txn) error { // - storage.ErrNotFound if the key does not already exist in the database. // - generic error in case of unexpected failure from the database layer or // encoding failure. -func update(key []byte, entity any) func(*badger.Txn) error { +func update(key []byte, entity interface{}) func(*badger.Txn) error { return func(tx *badger.Txn) error { // retrieve the item from the key-value store @@ -93,7 +93,7 @@ func update(key []byte, entity any) func(*badger.Txn) error { // upsert will encode the given entity with MsgPack and upsert the binary data // under the given key in the badger DB. -func upsert(key []byte, entity any) func(*badger.Txn) error { +func upsert(key []byte, entity interface{}) func(*badger.Txn) error { return func(tx *badger.Txn) error { // update the maximum key size if the inserted key is bigger if uint32(len(key)) > max { @@ -174,7 +174,7 @@ func removeByPrefix(prefix []byte) func(*badger.Txn) error { // - storage.ErrNotFound if the key does not exist in the database // - generic error in case of unexpected failure from the database layer, or failure // to decode an existing database value -func retrieve(key []byte, entity any) func(*badger.Txn) error { +func retrieve(key []byte, entity interface{}) func(*badger.Txn) error { return func(tx *badger.Txn) error { // retrieve the item from the key-value store @@ -228,7 +228,7 @@ type checkFunc func(key []byte) bool // createFunc returns a pointer to an initialized entity that we can potentially // decode the next value into during a badger DB iteration. -type createFunc func() any +type createFunc func() interface{} // handleFunc is a function that starts the processing of the current key-value // pair during a badger iteration. It should be called after the key was checked @@ -253,7 +253,7 @@ func lookup(entityIDs *[]flow.Identifier) func() (checkFunc, createFunc, handleF return true } var entityID flow.Identifier - create := func() any { + create := func() interface{} { return &entityID } handle := func() error { @@ -318,7 +318,7 @@ func iterate(start []byte, end []byte, iteration iterationFunc, opts ...func(*ba modifier = -1 // make sure to stop after end prefix length := uint32(len(start)) diff := max - length - for range diff { + for i := uint32(0); i < diff; i++ { start = append(start, 0xff) } } else { @@ -327,7 +327,7 @@ func iterate(start []byte, end []byte, iteration iterationFunc, opts ...func(*ba // finishing. length := uint32(len(end)) diff := max - length - for range diff { + for i := uint32(0); i < diff; i++ { end = append(end, 0xff) } } @@ -451,7 +451,7 @@ func traverse(prefix []byte, iteration iterationFunc) func(*badger.Txn) error { func findHighestAtOrBelow( prefix []byte, height uint64, - entity any, + entity interface{}, ) func(*badger.Txn) error { return func(tx *badger.Txn) error { if len(prefix) == 0 { diff --git a/storage/badger/operation/common_test.go b/storage/badger/operation/common_test.go index 500b7cfb5c6..0bdbd77c629 100644 --- a/storage/badger/operation/common_test.go +++ b/storage/badger/operation/common_test.go @@ -354,7 +354,7 @@ func TestIterate(t *testing.T) { return !bytes.Equal(key, []byte{0x12}) } var val bool - create := func() any { + create := func() interface{} { return &val } handle := func() error { @@ -393,7 +393,7 @@ func TestTraverse(t *testing.T) { return !bytes.Equal(key, []byte{0x42, 0x56}) } var val bool - create := func() any { + create := func() interface{} { return &val } handle := func() error { @@ -578,7 +578,7 @@ func TestIterateBoundaries(t *testing.T) { found = append(found, key) return false } - create := func() any { + create := func() interface{} { return nil } handle := func() error { diff --git a/storage/indexes/account_ft_transfers_test.go b/storage/indexes/account_ft_transfers_test.go index 3bce33e3bd1..3bf20b85369 100644 --- a/storage/indexes/account_ft_transfers_test.go +++ b/storage/indexes/account_ft_transfers_test.go @@ -922,11 +922,11 @@ func TestFTTransfers_PaginationCoversAllEntries(t *testing.T) { require.Len(t, allCollected, 6) // First 3 results are from height 6 (newest first), next 3 from firstHeight. - for i := range 3 { + for i := 0; i < 3; i++ { assert.Equal(t, uint64(6), allCollected[i].BlockHeight) assert.Equal(t, uint32(i), allCollected[i].TransactionIndex) } - for i := range 3 { + for i := 0; i < 3; i++ { assert.Equal(t, firstHeight, allCollected[3+i].BlockHeight) assert.Equal(t, uint32(i), allCollected[3+i].TransactionIndex) } diff --git a/storage/indexes/account_nft_transfers_test.go b/storage/indexes/account_nft_transfers_test.go index d6ebcd61d4c..d31e2e9f7f6 100644 --- a/storage/indexes/account_nft_transfers_test.go +++ b/storage/indexes/account_nft_transfers_test.go @@ -777,11 +777,11 @@ func TestNFTTransfers_PaginationCoversAllEntries(t *testing.T) { require.Len(t, allCollected, 6) // First 3 results are from height 6 (newest first), next 3 from firstHeight. - for i := range 3 { + for i := 0; i < 3; i++ { assert.Equal(t, uint64(6), allCollected[i].BlockHeight) assert.Equal(t, uint32(i), allCollected[i].TransactionIndex) } - for i := range 3 { + for i := 0; i < 3; i++ { assert.Equal(t, firstHeight, allCollected[3+i].BlockHeight) assert.Equal(t, uint32(i), allCollected[3+i].TransactionIndex) } diff --git a/storage/indexes/account_transactions_test.go b/storage/indexes/account_transactions_test.go index 7a39ee4f075..253fbf92c2a 100644 --- a/storage/indexes/account_transactions_test.go +++ b/storage/indexes/account_transactions_test.go @@ -892,11 +892,11 @@ func TestAccountTransactions_PaginationCoversAllEntries(t *testing.T) { require.Len(t, allCollected, 6) // First 3 results are from height 6 (newest first), next 3 from firstHeight. - for i := range 3 { + for i := 0; i < 3; i++ { assert.Equal(t, uint64(6), allCollected[i].BlockHeight) assert.Equal(t, uint32(i), allCollected[i].TransactionIndex) } - for i := range 3 { + for i := 0; i < 3; i++ { assert.Equal(t, firstHeight, allCollected[3+i].BlockHeight) assert.Equal(t, uint32(i), allCollected[3+i].TransactionIndex) } diff --git a/storage/migration/migration.go b/storage/migration/migration.go index 165d8ed9d87..4df596d81ff 100644 --- a/storage/migration/migration.go +++ b/storage/migration/migration.go @@ -57,7 +57,7 @@ func GeneratePrefixes(n int) [][]byte { base := 1 << (8 * n) results := make([][]byte, 0, base) - for i := range base { + for i := 0; i < base; i++ { buf := make([]byte, n) switch n { case 1: diff --git a/storage/migration/migration_test.go b/storage/migration/migration_test.go index aae02b2fe2d..3bdbfe1e310 100644 --- a/storage/migration/migration_test.go +++ b/storage/migration/migration_test.go @@ -158,7 +158,7 @@ func generateRandomKVData(count, keyLen, valLen int) map[string]string { return string(b) } - for range count { + for i := 0; i < count; i++ { k := randomStr(keyLen) v := randomStr(valLen) data[k] = v diff --git a/storage/migration/sstables.go b/storage/migration/sstables.go index 8bf80e0ab9b..45c85802046 100644 --- a/storage/migration/sstables.go +++ b/storage/migration/sstables.go @@ -71,20 +71,24 @@ func CopyFromBadgerToPebbleSSTables(badgerDB *badger.DB, pebbleDB *pebble.DB, cf var readerWg sync.WaitGroup for i := 0; i < cfg.ReaderWorkerCount; i++ { - readerWg.Go(func() { + readerWg.Add(1) + go func() { + defer readerWg.Done() if err := readerWorker(ctx, lg, badgerDB, prefixJobs, kvChan, cfg.BatchByteSize); err != nil { reportFirstError(err) } - }) + }() } var writerWg sync.WaitGroup for i := 0; i < cfg.WriterWorkerCount; i++ { - writerWg.Go(func() { + writerWg.Add(1) + go func() { + defer writerWg.Done() if err := writerSSTableWorker(ctx, i, pebbleDB, sstableDir, kvChan); err != nil { reportFirstError(err) } - }) + }() } // Close kvChan after readers complete diff --git a/storage/operation/chunk_data_packs_test.go b/storage/operation/chunk_data_packs_test.go index db1a78e2d9e..96ba338e57d 100644 --- a/storage/operation/chunk_data_packs_test.go +++ b/storage/operation/chunk_data_packs_test.go @@ -254,7 +254,7 @@ func TestRemoveChunkDataPackID(t *testing.T) { chunkDataPackIDs := unittest.IdentifierListFixture(3) // Insert multiple chunk data pack IDs - for i := range 3 { + for i := 0; i < 3; i++ { err := unittest.WithLock(t, lockManager, storage.LockIndexChunkDataPackByChunkID, func(lctx lockctx.Context) error { return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { @@ -265,7 +265,7 @@ func TestRemoveChunkDataPackID(t *testing.T) { } // Remove all of them - for i := range 3 { + for i := 0; i < 3; i++ { err := db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { return operation.RemoveChunkDataPackID(rw.Writer(), chunkIDs[i]) }) @@ -273,7 +273,7 @@ func TestRemoveChunkDataPackID(t *testing.T) { } // Verify all are gone - for i := range 3 { + for i := 0; i < 3; i++ { var retrievedID flow.Identifier err := operation.RetrieveChunkDataPackID(db.Reader(), chunkIDs[i], &retrievedID) require.Error(t, err) diff --git a/storage/operation/cluster_test.go b/storage/operation/cluster_test.go index 4853c152c69..9cf4839b2af 100644 --- a/storage/operation/cluster_test.go +++ b/storage/operation/cluster_test.go @@ -82,7 +82,7 @@ func TestClusterHeights(t *testing.T) { clusterBlockIDs := unittest.IdentifierListFixture(3) clusterIDs := []flow.ChainID{"cluster-0", "cluster-1", "cluster-2"} var actual flow.Identifier - for i := range clusterBlockIDs { + for i := 0; i < len(clusterBlockIDs); i++ { err = operation.LookupClusterBlockHeight(db.Reader(), clusterIDs[i], height, &actual) assert.ErrorIs(t, err, storage.ErrNotFound) @@ -93,7 +93,7 @@ func TestClusterHeights(t *testing.T) { }) require.NoError(t, err) } - for i := range clusterBlockIDs { + for i := 0; i < len(clusterBlockIDs); i++ { err = operation.LookupClusterBlockHeight(db.Reader(), clusterIDs[i], height, &actual) assert.NoError(t, err) assert.Equal(t, clusterBlockIDs[i], actual) @@ -156,7 +156,7 @@ func Test_RetrieveClusterFinalizedHeight(t *testing.T) { clusterFinalizedHeights := []uint64{117, 11, 791} clusterIDs := []flow.ChainID{"cluster-0", "cluster-1", "cluster-2"} var actual uint64 - for i := range clusterFinalizedHeights { + for i := 0; i < len(clusterFinalizedHeights); i++ { err = operation.RetrieveClusterFinalizedHeight(db.Reader(), clusterIDs[i], &actual) assert.ErrorIs(t, err, storage.ErrNotFound) @@ -167,7 +167,7 @@ func Test_RetrieveClusterFinalizedHeight(t *testing.T) { }) require.NoError(t, err) } - for i := range clusterFinalizedHeights { + for i := 0; i < len(clusterFinalizedHeights); i++ { err = operation.RetrieveClusterFinalizedHeight(db.Reader(), clusterIDs[i], &actual) assert.NoError(t, err) assert.Equal(t, clusterFinalizedHeights[i], actual) @@ -283,7 +283,7 @@ func TestClusterBlockByReferenceHeight(t *testing.T) { // keep track of which ids are indexed at each nextHeight lookup := make(map[uint64][]flow.Identifier) err := unittest.WithLock(t, lockManager, storage.LockInsertOrFinalizeClusterBlock, func(lctx lockctx.Context) error { - for i := range ids { + for i := 0; i < len(ids); i++ { // randomly adjust the nextHeight, increasing on average r := rand.Intn(100) if r < 20 { @@ -445,7 +445,7 @@ func BenchmarkLookupClusterBlocksByReferenceHeightRange_100_000(b *testing.B) { func benchmarkLookupClusterBlocksByReferenceHeightRange(b *testing.B, n int) { lockManager := storage.NewTestingLockManager() dbtest.BenchWithStorages(b, func(b *testing.B, r storage.Reader, wr dbtest.WithWriter) { - for range n { + for i := 0; i < n; i++ { err := unittest.WithLock(b, lockManager, storage.LockInsertOrFinalizeClusterBlock, func(lctx lockctx.Context) error { return wr(func(w storage.Writer) error { return operation.IndexClusterBlockByReferenceHeight(lctx, w, rand.Uint64()%1000, unittest.IdentifierFixture()) diff --git a/storage/operation/iterate_bench_test.go b/storage/operation/iterate_bench_test.go index c20e75b2d97..29d0047495e 100644 --- a/storage/operation/iterate_bench_test.go +++ b/storage/operation/iterate_bench_test.go @@ -59,7 +59,7 @@ func BenchmarkFindHighestAtOrBelowByPrefixUsingSeeker(t *testing.B) { } // findHighestAtOrBelowByPrefixUsingIterator is the original operation.FindHighestAtOrBelowByPrefix(). -func findHighestAtOrBelowByPrefixUsingIterator(r storage.Reader, prefix []byte, height uint64, entity any) (errToReturn error) { +func findHighestAtOrBelowByPrefixUsingIterator(r storage.Reader, prefix []byte, height uint64, entity interface{}) (errToReturn error) { if len(prefix) == 0 { return fmt.Errorf("prefix must not be empty") } @@ -104,6 +104,6 @@ func findHighestAtOrBelowByPrefixUsingIterator(r storage.Reader, prefix []byte, return nil } -func findHighestAtOrBelowByPrefixUsingSeeker(r storage.Reader, prefix []byte, height uint64, entity any) (errToReturn error) { +func findHighestAtOrBelowByPrefixUsingSeeker(r storage.Reader, prefix []byte, height uint64, entity interface{}) (errToReturn error) { return operation.FindHighestAtOrBelowByPrefix(r, prefix, height, entity) } diff --git a/storage/operation/multi_iterator_test.go b/storage/operation/multi_iterator_test.go index c66587ddc07..db553541fc3 100644 --- a/storage/operation/multi_iterator_test.go +++ b/storage/operation/multi_iterator_test.go @@ -24,7 +24,7 @@ func TestMultiIterator(t *testing.T) { keys := make([][]byte, 0, keyCount) values := make([][]byte, 0, keyCount) - for i := range highBound + 1 { + for i := lowBound; i < highBound+1; i++ { keys = append(keys, operation.MakePrefix(prefix, byte(i))) values = append(values, []byte{byte(i)}) } diff --git a/storage/operation/stats_test.go b/storage/operation/stats_test.go index 5f375bd000d..95ccab8cee2 100644 --- a/storage/operation/stats_test.go +++ b/storage/operation/stats_test.go @@ -28,7 +28,7 @@ func TestSummarizeKeysByFirstByteConcurrent(t *testing.T) { } // insert 100 chunk data packs - for range 100 { + for i := 0; i < 100; i++ { collectionID := unittest.IdentifierFixture() cdp := &storage.StoredChunkDataPack{ ChunkID: unittest.IdentifierFixture(), @@ -48,7 +48,7 @@ func TestSummarizeKeysByFirstByteConcurrent(t *testing.T) { // insert 20 results err = db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { - for range 20 { + for i := 0; i < 20; i++ { result := unittest.ExecutionResultFixture() err := operation.InsertExecutionResult(rw.Writer(), result.ID(), result) if err != nil { @@ -66,7 +66,7 @@ func TestSummarizeKeysByFirstByteConcurrent(t *testing.T) { // print operation.PrintStats(unittest.Logger(), stats) - for i := range 256 { + for i := 0; i < 256; i++ { count := 0 if i == 102 { // events (codeEvent) count = 30 diff --git a/storage/operation/writes_bench_test.go b/storage/operation/writes_bench_test.go index 71a944485f2..4c569d397f0 100644 --- a/storage/operation/writes_bench_test.go +++ b/storage/operation/writes_bench_test.go @@ -22,12 +22,12 @@ func BenchmarkUpsert(t *testing.B) { func BenchmarkRemove(t *testing.B) { dbtest.BenchWithStorages(t, func(t *testing.B, r storage.Reader, withWriter dbtest.WithWriter) { n := t.N - for i := range n { + for i := 0; i < n; i++ { e := Entity{ID: uint64(i)} require.NoError(t, withWriter(operation.Upsert(e.Key(), e))) } t.ResetTimer() - for i := range n { + for i := 0; i < n; i++ { e := Entity{ID: uint64(i)} require.NoError(t, withWriter(operation.Remove(e.Key()))) } diff --git a/storage/operation/writes_test.go b/storage/operation/writes_test.go index 970b3d9b80f..f7307007888 100644 --- a/storage/operation/writes_test.go +++ b/storage/operation/writes_test.go @@ -235,7 +235,7 @@ func TestRemoveDiskUsage(t *testing.T) { } items := make([]*flow.ChunkDataPack, count) - for i := range count { + for i := 0; i < count; i++ { chunkID := unittest.IdentifierFixture() chunkDataPack := unittest.ChunkDataPackFixture(chunkID) items[i] = chunkDataPack @@ -243,7 +243,7 @@ func TestRemoveDiskUsage(t *testing.T) { // 1. Insert 10000 entities. require.NoError(t, withWriter(func(writer storage.Writer) error { - for i := range count { + for i := 0; i < count; i++ { if err := operation.Upsert(getKey(items[i]), items[i])(writer); err != nil { return err } @@ -261,7 +261,7 @@ func TestRemoveDiskUsage(t *testing.T) { // 4. Remove all entities require.NoError(t, withWriter(func(writer storage.Writer) error { - for i := range count { + for i := 0; i < count; i++ { if err := operation.Remove(getKey(items[i]))(writer); err != nil { return err } @@ -289,7 +289,7 @@ func TestConcurrentWrite(t *testing.T) { var wg sync.WaitGroup numWrites := 10 // number of concurrent writes - for i := range numWrites { + for i := 0; i < numWrites; i++ { wg.Add(1) go func(i int) { defer wg.Done() @@ -314,13 +314,13 @@ func TestConcurrentRemove(t *testing.T) { numDeletes := 10 // number of concurrent deletions // First, insert entities to be deleted concurrently - for i := range numDeletes { + for i := 0; i < numDeletes; i++ { e := Entity{ID: uint64(i)} require.NoError(t, withWriter(operation.Upsert(e.Key(), e))) } // Now, perform concurrent deletes - for i := range numDeletes { + for i := 0; i < numDeletes; i++ { wg.Add(1) go func(i int) { defer wg.Done() diff --git a/storage/pebble/bootstrap.go b/storage/pebble/bootstrap.go index 81cbde0be06..e70b1fec389 100644 --- a/storage/pebble/bootstrap.go +++ b/storage/pebble/bootstrap.go @@ -139,7 +139,7 @@ func (b *RegisterBootstrap) IndexCheckpointFile(ctx context.Context, workerCount start := time.Now() b.log.Info().Msgf("indexing registers from checkpoint with %v worker", workerCount) - for range workerCount { + for i := 0; i < workerCount; i++ { g.Go(func() error { return b.indexCheckpointFileWorker(gCtx) }) diff --git a/storage/pebble/bootstrap_test.go b/storage/pebble/bootstrap_test.go index 8bec1d24388..4225b5e5d47 100644 --- a/storage/pebble/bootstrap_test.go +++ b/storage/pebble/bootstrap_test.go @@ -228,7 +228,7 @@ func trieWithValidRegisterIDs(t *testing.T, n uint16) ([]*trie.MTrie, []*flow.Re func randomRegisterPayloads(n uint16) []ledger.Payload { p := make([]ledger.Payload, 0, n) - for range n { + for i := uint16(0); i < n; i++ { o := make([]byte, 0, 8) o = binary.BigEndian.AppendUint16(o, n) k := ledger.Key{KeyParts: []ledger.KeyPart{ @@ -245,7 +245,7 @@ func randomRegisterPayloads(n uint16) []ledger.Payload { func randomRegisterPaths(n uint16) []ledger.Path { p := make([]ledger.Path, 0, n) - for i := range n { + for i := uint16(0); i < n; i++ { p = append(p, testutils.PathByUint16(i)) } return p diff --git a/storage/pebble/registers/comparer_test.go b/storage/pebble/registers/comparer_test.go index a257f1540da..9781ad6b745 100644 --- a/storage/pebble/registers/comparer_test.go +++ b/storage/pebble/registers/comparer_test.go @@ -25,6 +25,7 @@ func Test_NewMVCCComparer_Split(t *testing.T) { } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() diff --git a/storage/pebble/registers_test.go b/storage/pebble/registers_test.go index 9feb91507f2..717ff6e7021 100644 --- a/storage/pebble/registers_test.go +++ b/storage/pebble/registers_test.go @@ -308,7 +308,7 @@ func Benchmark_PayloadStorage(b *testing.B) { return flow.NewRegisterID(owner, strconv.Itoa(i)) } valueForHeightAndKey := func(i, j int) []byte { - return fmt.Appendf(nil, "%d-%d", i, j) + return []byte(fmt.Sprintf("%d-%d", i, j)) } b.ResetTimer() @@ -320,7 +320,7 @@ func Benchmark_PayloadStorage(b *testing.B) { entries := make(flow.RegisterEntries, 1, batchSize) entries[0] = flow.RegisterEntry{ Key: batchSizeKey, - Value: fmt.Appendf(nil, "%d", batchSize), + Value: []byte(fmt.Sprintf("%d", batchSize)), } for j := 1; j < batchSize; j++ { entries = append(entries, flow.RegisterEntry{ diff --git a/storage/store/collections_test.go b/storage/store/collections_test.go index 8ea7def36cc..8ab091c67b4 100644 --- a/storage/store/collections_test.go +++ b/storage/store/collections_test.go @@ -144,8 +144,10 @@ func TestCollections_ConcurrentIndexByTx(t *testing.T) { errChan := make(chan error, 2*numCollections) // Insert col1 batch - wg.Go(func() { - for range numCollections { + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < numCollections; i++ { col := unittest.CollectionFixture(1) col.Transactions[0] = sharedTx // Ensure it shares the same transaction err := unittest.WithLock(t, lockManager, storage.LockInsertCollection, func(lctx lockctx.Context) error { @@ -154,11 +156,13 @@ func TestCollections_ConcurrentIndexByTx(t *testing.T) { }) errChan <- err } - }) + }() // Insert col2 batch - wg.Go(func() { - for range numCollections { + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < numCollections; i++ { col := unittest.CollectionFixture(1) col.Transactions[0] = sharedTx // Ensure it shares the same transaction err := unittest.WithLock(t, lockManager, storage.LockInsertCollection, func(lctx lockctx.Context) error { @@ -167,7 +171,7 @@ func TestCollections_ConcurrentIndexByTx(t *testing.T) { }) errChan <- err } - }) + }() wg.Wait() close(errChan) diff --git a/storage/store/headers_test.go b/storage/store/headers_test.go index b702c079ebb..bc4f8ceb12f 100644 --- a/storage/store/headers_test.go +++ b/storage/store/headers_test.go @@ -129,7 +129,7 @@ func TestHeadersByParentID(t *testing.T) { // Test case 2: Parent with 3 children var childProposals []*flow.Proposal - for range 3 { + for i := 0; i < 3; i++ { childProposal := unittest.ProposalFromBlock(unittest.BlockWithParentFixture(parentBlock.ToHeader())) childProposals = append(childProposals, childProposal) diff --git a/storage/store/latest_persisted_sealed_result_test.go b/storage/store/latest_persisted_sealed_result_test.go index c155dc0d77d..3a1f35ca82a 100644 --- a/storage/store/latest_persisted_sealed_result_test.go +++ b/storage/store/latest_persisted_sealed_result_test.go @@ -198,13 +198,15 @@ func TestLatestPersistedSealedResult_ConcurrentAccess(t *testing.T) { numGoroutines := 1000 for range numGoroutines { - wg.Go(func() { + wg.Add(1) + go func() { + defer wg.Done() actualResultID, actualHeight := latest.Latest() assert.Equal(t, initialResult.ID(), actualResultID) assert.Equal(t, initialHeader.Height, actualHeight) - }) + }() } wg.Wait() @@ -214,7 +216,7 @@ func TestLatestPersistedSealedResult_ConcurrentAccess(t *testing.T) { var wg sync.WaitGroup numGoroutines := 1000 - for i := range numGoroutines { + for i := 0; i < numGoroutines; i++ { wg.Add(2) go func(i int) { defer wg.Done() diff --git a/storage/store/light_transaction_results_test.go b/storage/store/light_transaction_results_test.go index 87e3ae2eb56..c773959b8b5 100644 --- a/storage/store/light_transaction_results_test.go +++ b/storage/store/light_transaction_results_test.go @@ -192,7 +192,7 @@ func TestBatchStoreLightTransactionResultsWrongLock(t *testing.T) { func getLightTransactionResultsFixture(n int) []flow.LightTransactionResult { txResults := make([]flow.LightTransactionResult, 0, n) - for i := range n { + for i := 0; i < n; i++ { expected := flow.LightTransactionResult{ TransactionID: unittest.IdentifierFixture(), Failed: i%2 == 0, diff --git a/storage/store/my_receipts_test.go b/storage/store/my_receipts_test.go index 45e9ff1011c..4dbc1e1d8c4 100644 --- a/storage/store/my_receipts_test.go +++ b/storage/store/my_receipts_test.go @@ -169,7 +169,7 @@ func TestMyExecutionReceiptsStorage(t *testing.T) { errChan := make(chan error, 10) // Store receipts concurrently - for i := range 10 { + for i := 0; i < 10; i++ { doneSinal.Add(1) go func(i int) { block := unittest.BlockFixture() // Each iteration gets a new block diff --git a/storage/store/transaction_result_error_messages_test.go b/storage/store/transaction_result_error_messages_test.go index 703f234c38c..5a779ec6ab5 100644 --- a/storage/store/transaction_result_error_messages_test.go +++ b/storage/store/transaction_result_error_messages_test.go @@ -37,7 +37,7 @@ func TestStoringTransactionResultErrorMessages(t *testing.T) { require.Nil(t, messages) txErrorMessages := make([]flow.TransactionResultErrorMessage, 0) - for i := range 10 { + for i := 0; i < 10; i++ { expected := flow.TransactionResultErrorMessage{ TransactionID: unittest.IdentifierFixture(), ErrorMessage: fmt.Sprintf("a runtime error %d", i), @@ -123,7 +123,7 @@ func TestBatchStoreTransactionResultErrorMessagesErrAlreadyExists(t *testing.T) blockID := unittest.IdentifierFixture() txResultErrMsgs := make([]flow.TransactionResultErrorMessage, 0) - for i := range 3 { + for i := 0; i < 3; i++ { expected := flow.TransactionResultErrorMessage{ TransactionID: unittest.IdentifierFixture(), ErrorMessage: fmt.Sprintf("a runtime error %d", i), @@ -143,7 +143,7 @@ func TestBatchStoreTransactionResultErrorMessagesErrAlreadyExists(t *testing.T) // Second batch store with the same blockID should fail with ErrAlreadyExists duplicateTxResultErrMsgs := make([]flow.TransactionResultErrorMessage, 0) - for i := range 2 { + for i := 0; i < 2; i++ { expected := flow.TransactionResultErrorMessage{ TransactionID: unittest.IdentifierFixture(), ErrorMessage: fmt.Sprintf("duplicate error %d", i), @@ -187,7 +187,7 @@ func TestBatchStoreTransactionResultErrorMessagesMissingLock(t *testing.T) { blockID := unittest.IdentifierFixture() txResultErrMsgs := make([]flow.TransactionResultErrorMessage, 0) - for i := range 3 { + for i := 0; i < 3; i++ { expected := flow.TransactionResultErrorMessage{ TransactionID: unittest.IdentifierFixture(), ErrorMessage: fmt.Sprintf("a runtime error %d", i), @@ -222,7 +222,7 @@ func TestBatchStoreTransactionResultErrorMessagesWrongLock(t *testing.T) { blockID := unittest.IdentifierFixture() txResultErrMsgs := make([]flow.TransactionResultErrorMessage, 0) - for i := range 3 { + for i := 0; i < 3; i++ { expected := flow.TransactionResultErrorMessage{ TransactionID: unittest.IdentifierFixture(), ErrorMessage: fmt.Sprintf("a runtime error %d", i), diff --git a/storage/store/transaction_results_test.go b/storage/store/transaction_results_test.go index 1f2a47c4690..bd0bc080d38 100644 --- a/storage/store/transaction_results_test.go +++ b/storage/store/transaction_results_test.go @@ -29,7 +29,7 @@ func TestBatchStoringTransactionResults(t *testing.T) { blockID := unittest.IdentifierFixture() txResults := make([]flow.TransactionResult, 0) - for i := range 10 { + for i := 0; i < 10; i++ { txID := unittest.IdentifierFixture() expected := flow.TransactionResult{ TransactionID: txID, @@ -201,7 +201,7 @@ func TestBatchStoreTransactionResultsErrAlreadyExists(t *testing.T) { blockID := unittest.IdentifierFixture() txResults := make([]flow.TransactionResult, 0) - for i := range 3 { + for i := 0; i < 3; i++ { txID := unittest.IdentifierFixture() expected := flow.TransactionResult{ TransactionID: txID, @@ -220,7 +220,7 @@ func TestBatchStoreTransactionResultsErrAlreadyExists(t *testing.T) { // Second batch store with the same blockID should fail with ErrAlreadyExists duplicateTxResults := make([]flow.TransactionResult, 0) - for i := range 2 { + for i := 0; i < 2; i++ { txID := unittest.IdentifierFixture() expected := flow.TransactionResult{ TransactionID: txID, @@ -264,7 +264,7 @@ func TestBatchStoreTransactionResultsMissingLock(t *testing.T) { blockID := unittest.IdentifierFixture() txResults := make([]flow.TransactionResult, 0) - for i := range 3 { + for i := 0; i < 3; i++ { txID := unittest.IdentifierFixture() expected := flow.TransactionResult{ TransactionID: txID, @@ -297,7 +297,7 @@ func TestBatchStoreTransactionResultsWrongLock(t *testing.T) { blockID := unittest.IdentifierFixture() txResults := make([]flow.TransactionResult, 0) - for i := range 3 { + for i := 0; i < 3; i++ { txID := unittest.IdentifierFixture() expected := flow.TransactionResult{ TransactionID: txID, diff --git a/storage/util/logger.go b/storage/util/logger.go index 1ab597ecee9..6a3cd914e97 100644 --- a/storage/util/logger.go +++ b/storage/util/logger.go @@ -20,22 +20,22 @@ func NewLogger(logger zerolog.Logger) *Logger { } } -func (l *Logger) Fatalf(msg string, args ...any) { +func (l *Logger) Fatalf(msg string, args ...interface{}) { l.log.Fatal().Msgf(msg, args...) } -func (l *Logger) Errorf(msg string, args ...any) { +func (l *Logger) Errorf(msg string, args ...interface{}) { l.log.Error().Msgf(msg, args...) } -func (l *Logger) Warningf(msg string, args ...any) { +func (l *Logger) Warningf(msg string, args ...interface{}) { l.log.Warn().Msgf(msg, args...) } -func (l *Logger) Infof(msg string, args ...any) { +func (l *Logger) Infof(msg string, args ...interface{}) { l.log.Info().Msgf(msg, args...) } -func (l *Logger) Debugf(msg string, args ...any) { +func (l *Logger) Debugf(msg string, args ...interface{}) { l.log.Debug().Msgf(msg, args...) } diff --git a/tools/structwrite/go.mod b/tools/structwrite/go.mod index d261b68c8bf..b5165189ee5 100644 --- a/tools/structwrite/go.mod +++ b/tools/structwrite/go.mod @@ -1,6 +1,6 @@ module github.com/onflow/flow-go/tools/structwrite -go 1.26.0 +go 1.25.0 require ( github.com/golangci/plugin-module-register v0.1.1 diff --git a/tools/test_monitor/common/utility.go b/tools/test_monitor/common/utility.go index 4f3ebf5a445..d7f53d0d050 100644 --- a/tools/test_monitor/common/utility.go +++ b/tools/test_monitor/common/utility.go @@ -111,7 +111,7 @@ func DirExists(path string) bool { } // SaveToFile save test run/summary to local JSON file. -func SaveToFile(fileName string, testSummary any) { +func SaveToFile(fileName string, testSummary interface{}) { testSummaryBytes, err := json.MarshalIndent(testSummary, "", " ") AssertNoError(err, "error marshalling json") @@ -123,7 +123,7 @@ func SaveToFile(fileName string, testSummary any) { AssertNoError(err, "error saving test summary to file") } -func SaveLinesToFile(fileName string, list any) { +func SaveLinesToFile(fileName string, list interface{}) { sliceType := reflect.TypeOf(list) if sliceType.Kind() != reflect.Slice && sliceType.Kind() != reflect.Array { panic("argument must be an array or slice") diff --git a/tools/test_monitor/level1/process_summary1_results.go b/tools/test_monitor/level1/process_summary1_results.go index 4e07281d466..2e315256c26 100644 --- a/tools/test_monitor/level1/process_summary1_results.go +++ b/tools/test_monitor/level1/process_summary1_results.go @@ -96,7 +96,10 @@ func processTestRunLineByLine(scanner *bufio.Scanner) map[string][]*common.Level continue } - lastTestResultIndex := max(len(testResultMap[testResultMapKey])-1, 0) + lastTestResultIndex := len(testResultMap[testResultMapKey]) - 1 + if lastTestResultIndex < 0 { + lastTestResultIndex = 0 + } testResults, ok := testResultMap[testResultMapKey] if !ok { diff --git a/tools/test_monitor/level2/process_summary2_results.go b/tools/test_monitor/level2/process_summary2_results.go index 90d7c849b7c..8d40c2cb711 100644 --- a/tools/test_monitor/level2/process_summary2_results.go +++ b/tools/test_monitor/level2/process_summary2_results.go @@ -26,7 +26,7 @@ func generateLevel2SummaryFromStructs(level1Summaries []common.Level1Summary) co level2Summary.TestResultsMap = make(map[string]*common.Level2TestResult) // go through all level 1 test runs create level 2 summary - for i := range level1Summaries { + for i := 0; i < len(level1Summaries); i++ { for _, level1TestResultRow := range level1Summaries[i] { // check if already started collecting summary for this test level2TestResultsMapKey := level1TestResultRow.Package + "/" + level1TestResultRow.Test @@ -81,7 +81,7 @@ func buildLevel1SummariesFromJSON(level1Directory string) []common.Level1Summary dirEntries, err := os.ReadDir(filepath.Join(level1Directory)) common.AssertNoError(err, "error reading level 1 directory") - for i := range dirEntries { + for i := 0; i < len(dirEntries); i++ { // read in each level 1 summary var level1Summary common.Level1Summary diff --git a/utils/binstat/binstat_external_test.go b/utils/binstat/binstat_external_test.go index 5feec8c4536..10f8b911ff9 100644 --- a/utils/binstat/binstat_external_test.go +++ b/utils/binstat/binstat_external_test.go @@ -83,7 +83,7 @@ func run(t *testing.T, loop int, try int, gomaxprocs int) { f := func(outerFuncName string) time.Duration { bs := binstat.EnterTime(outerFuncName) var sum int - for i := range 10000000 { + for i := 0; i < 10000000; i++ { sum -= i / 2 sum *= i sum /= i/3 + 1 @@ -131,7 +131,7 @@ func run(t *testing.T, loop int, try int, gomaxprocs int) { require.Condition(t, func() bool { return actual >= atLeast }, "Unexpectedly few regex results on pprof output") // add the regex matches to a table of elapsed times - for i := range matches { + for i := 0; i < len(matches); i++ { //debug zlog.Debug().Msgf("test: matches[%d][1]=%s matches[%d][2]=%s", i, matches[i][1], i, matches[i][2]) fi, err := strconv.Atoi(matches[i][2]) // 0-5 instead of 1-6 require.NoError(t, err) @@ -159,13 +159,13 @@ func TestWithPprof(t *testing.T) { backTicks(t, "ls -al ./binstat.test.pid-*.binstat.txt* ./*gomaxprocs*.pprof.txt ; rm -f ./binstat.test.pid-*.binstat.txt* ./*gomaxprocs*.pprof.txt") // run the test; loops of several tries running groups of go-routines - for loop := range loops { + for loop := 0; loop < loops; loop++ { gomaxprocs := 8 if 0 == loop { gomaxprocs = 1 } bs := binstat.EnterTime(fmt.Sprintf("loop-%d", loop)) - for try := range tries { + for try := 0; try < tries; try++ { zlog.Debug().Msgf("test: loop=%d try=%d; running 6 identical functions with gomaxprocs=%d", loop, try+1, gomaxprocs) run(t, loop, try, gomaxprocs) } @@ -191,11 +191,11 @@ func TestWithPprof(t *testing.T) { - 0.07 0.07 0.07 0.09 0.06 0.07 // f5() seconds; loop=1 gomaxprocs=8 - 0.07 0.07 0.07 0.04 0.10 0.03 // f6() seconds; loop=1 gomaxprocs=8 */ - for loop := range loops { + for loop := 0; loop < loops; loop++ { zlog.Debug().Msg("test: binstat------- pprof---------") l1 := "test:" - for range 2 { - for try := range tries { + for r := 0; r < 2; r++ { + for try := 0; try < tries; try++ { l1 = l1 + fmt.Sprintf(" try%d", try+1) } } @@ -204,10 +204,10 @@ func TestWithPprof(t *testing.T) { if 0 == loop { gomaxprocs = 1 } - for i := range funcs { + for i := 0; i < funcs; i++ { l2 := "test:" - for mech := range mechs { - for try := range tries { + for mech := 0; mech < mechs; mech++ { + for try := 0; try < tries; try++ { l2 = l2 + fmt.Sprintf(" %s", el[loop][try][mech][i]) } } diff --git a/utils/dsl/dsl.go b/utils/dsl/dsl.go index a7985a7d70f..48bd3e7855e 100644 --- a/utils/dsl/dsl.go +++ b/utils/dsl/dsl.go @@ -77,11 +77,11 @@ func (i Import) ToCadence() string { type Imports []Import func (i Imports) ToCadence() string { - var imports strings.Builder + imports := "" for _, imp := range i { - imports.WriteString(imp.ToCadence()) + imports += imp.ToCadence() } - return imports.String() + return imports } type SetAccountCode struct { diff --git a/utils/grpcutils/grpc.go b/utils/grpcutils/grpc.go index 5cfecf9ba9b..76d56b10b1b 100644 --- a/utils/grpcutils/grpc.go +++ b/utils/grpcutils/grpc.go @@ -84,7 +84,7 @@ type ServerAuthError struct { } // newServerAuthError constructs a new ServerAuthError -func newServerAuthError(msg string, args ...any) *ServerAuthError { +func newServerAuthError(msg string, args ...interface{}) *ServerAuthError { return &ServerAuthError{message: fmt.Sprintf(msg, args...)} } @@ -133,7 +133,7 @@ func verifyPeerCertificateFunc(expectedPublicKey crypto.PublicKey) (func(rawCert verifyFunc := func(rawCerts [][]byte, _ [][]*x509.Certificate) error { chain := make([]*x509.Certificate, len(rawCerts)) - for i := range rawCerts { + for i := 0; i < len(rawCerts); i++ { cert, err := x509.ParseCertificate(rawCerts[i]) if err != nil { return newServerAuthError("failed to parse certificate: %s", err.Error()) diff --git a/utils/helpers.go b/utils/helpers.go index 4665241e37a..9538a227411 100644 --- a/utils/helpers.go +++ b/utils/helpers.go @@ -10,7 +10,7 @@ func IsNil(v any) bool { } rv := reflect.ValueOf(v) switch rv.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return rv.IsNil() default: return false diff --git a/utils/io/filelock_test.go b/utils/io/filelock_test.go index 5d082dd5b5d..0312be47d6d 100644 --- a/utils/io/filelock_test.go +++ b/utils/io/filelock_test.go @@ -77,7 +77,7 @@ func TestFileLock(t *testing.T) { require.NoError(t, err) // Acquire and release multiple times - for i := range 3 { + for i := 0; i < 3; i++ { err := lock.Lock() require.NoError(t, err, "iteration %d", i) @@ -103,7 +103,7 @@ func TestFileLock(t *testing.T) { require.NoError(t, err) // Start multiple goroutines trying to acquire the same lock - for range numGoroutines { + for i := 0; i < numGoroutines; i++ { wg.Add(1) lockHeld.Add(1) go func() { diff --git a/utils/io/write.go b/utils/io/write.go index 47869207b92..831a7970b91 100644 --- a/utils/io/write.go +++ b/utils/io/write.go @@ -36,7 +36,7 @@ func WriteText(path string, data []byte) error { } // WriteJSON marshals the given interface into JSON and writes it to the given path -func WriteJSON(path string, data any) error { +func WriteJSON(path string, data interface{}) error { bz, err := json.MarshalIndent(data, "", " ") if err != nil { return fmt.Errorf("could not marshal json: %w", err) diff --git a/utils/unittest/cluster.go b/utils/unittest/cluster.go index 96b8bfff32d..d36237a5f3c 100644 --- a/utils/unittest/cluster.go +++ b/utils/unittest/cluster.go @@ -25,7 +25,7 @@ func TransactionForCluster(clusters flow.ClusterList, target flow.IdentitySkelet func AlterTransactionForCluster(tx flow.TransactionBody, clusters flow.ClusterList, target flow.IdentitySkeletonList, after func(tx *flow.TransactionBody)) flow.TransactionBody { // Bound to avoid infinite loop in case the routing algorithm is broken - for range 10000 { + for i := 0; i < 10000; i++ { tx.Script = append(tx.Script, '/', '/') if after != nil { diff --git a/utils/unittest/encoding.go b/utils/unittest/encoding.go index b9fb987bb71..b2ab5fd0fa3 100644 --- a/utils/unittest/encoding.go +++ b/utils/unittest/encoding.go @@ -24,8 +24,6 @@ func EncodeDecodeDifferentVersions(t *testing.T, src, dst any) { // PtrTo returns a pointer to the input. Useful for concisely constructing // a reference-typed argument to a function or similar. -// -//go:fix inline func PtrTo[T any](target T) *T { - return new(target) + return &target } diff --git a/utils/unittest/entity.go b/utils/unittest/entity.go index 05911be0725..b18a5810c67 100644 --- a/utils/unittest/entity.go +++ b/utils/unittest/entity.go @@ -86,7 +86,7 @@ type MalleabilityCheckerOpt func(*MalleabilityChecker) // ATTENTION: In order for the MalleabilityChecker to work properly, two calls of the generator should produce two different values. func WithTypeGenerator[T any](generator func() T) MalleabilityCheckerOpt { return func(mc *MalleabilityChecker) { - mc.typeGenerator[reflect.TypeFor[T]()] = func() reflect.Value { + mc.typeGenerator[reflect.TypeOf((*T)(nil)).Elem()] = func() reflect.Value { return reflect.ValueOf(generator()) } } @@ -174,7 +174,7 @@ func (mc *MalleabilityChecker) Check(model any, hashModel func() flow.Identifier if !v.IsValid() { return fmt.Errorf("input is not a valid entity") } - if v.Kind() != reflect.Pointer { + if v.Kind() != reflect.Ptr { // If it is not a pointer type, we may not be able to set fields to test malleability, since the model may not be addressable return fmt.Errorf("entity is not a pointer type (try checking a reference to it), entity: %v %v", v.Kind(), v.Type()) } @@ -227,7 +227,7 @@ func (mc *MalleabilityChecker) isModelMalleable(modelOrField reflect.Value, stru } } - if modelOrField.Kind() == reflect.Pointer { + if modelOrField.Kind() == reflect.Ptr { if modelOrField.IsNil() { modelOrField.Set(reflect.New(modelOrField.Type().Elem())) } @@ -332,7 +332,7 @@ func (mc *MalleabilityChecker) generateRandomReflectValue(field reflect.Value) e return err } field.SetMapIndex(key, val) - case reflect.Pointer: + case reflect.Ptr: if field.IsNil() { field.Set(reflect.New(field.Type().Elem())) } @@ -341,7 +341,8 @@ func (mc *MalleabilityChecker) generateRandomReflectValue(field reflect.Value) e // if we are dealing with a struct, we need to go through all fields and generate random values for them // if the field is another struct, we will deal with it recursively. // at the end of the recursion, we must encounter a primitive type, which we can generate a random value for, otherwise an error is returned. - for _, structField := range field.Fields() { + for i := 0; i < field.NumField(); i++ { + structField := field.Field(i) err := mc.generateRandomReflectValue(structField) if err != nil { return fmt.Errorf("cannot generate random value for struct field: %s", field.Type().String()) @@ -362,7 +363,7 @@ func (mc *MalleabilityChecker) generateRandomReflectValue(field reflect.Value) e // generateInterfaceFlowValue generates a random value for the field of the struct that is an interface. // This can be extended for types that are broadly used in the code base. func generateInterfaceFlowValue(field reflect.Value) any { - if field.Type().Implements(reflect.TypeFor[crypto.PublicKey]()) { + if field.Type().Implements(reflect.TypeOf((*crypto.PublicKey)(nil)).Elem()) { return KeyFixture(crypto.ECDSAP256).PublicKey() } return nil diff --git a/utils/unittest/epoch_builder.go b/utils/unittest/epoch_builder.go index 63e923dc15d..76ff23b4d46 100644 --- a/utils/unittest/epoch_builder.go +++ b/utils/unittest/epoch_builder.go @@ -390,7 +390,7 @@ func (builder *EpochBuilder) addBlock(block *flow.Block) { // receipt for the highest block in state to the given block before adding it to the state. // NOTE: This func should only be used after BuildEpoch to extend the commit phase func (builder *EpochBuilder) AddBlocksWithSeals(n int, counter uint64) *EpochBuilder { - for range n { + for i := 0; i < n; i++ { // Given the last 2 blocks in state A <- B when we add block C it will contain the following. // - seal for A // - execution result for B diff --git a/utils/unittest/events.go b/utils/unittest/events.go index 2afee936c85..1f236470c1f 100644 --- a/utils/unittest/events.go +++ b/utils/unittest/events.go @@ -127,7 +127,7 @@ func (e *eventGeneratorFactory) WithEncoding(encoding entities.EventEncodingVers func (e *eventGeneratorFactory) GetEventsWithEncoding(n int, version entities.EventEncodingVersion) []flow.Event { eventGenerator := NewEventGenerator(EventGenerator.WithEncoding(version)) events := make([]flow.Event, 0, n) - for range n { + for i := 0; i < n; i++ { events = append(events, eventGenerator.New()) } return events @@ -258,7 +258,7 @@ func EventsFixture( ) []flow.Event { events := make([]flow.Event, n) g := NewEventGenerator(EventGenerator.WithEncoding(entities.EventEncodingVersion_CCF_V0)) - for i := range n { + for i := 0; i < n; i++ { events[i] = g.New( Event.WithTransactionIndex(0), Event.WithEventIndex(uint32(i)), diff --git a/utils/unittest/fixtures.go b/utils/unittest/fixtures.go index b27e8ab93ce..fad9543eb5c 100644 --- a/utils/unittest/fixtures.go +++ b/utils/unittest/fixtures.go @@ -202,7 +202,7 @@ func AccountFixture() (*flow.Account, error) { func ChainBlockFixtureWithRoot(root *flow.Header, n int) []*flow.Block { bs := make([]*flow.Block, 0, n) parent := root - for range n { + for i := 0; i < n; i++ { b := BlockWithParentFixture(parent) bs = append(bs, b) parent = b.ToHeader() @@ -255,7 +255,7 @@ func ProposalFixture() *flow.Proposal { func BlockResponseFixture(count int) *flow.BlockResponse { blocks := make([]flow.Proposal, count) - for i := range count { + for i := 0; i < count; i++ { blocks[i] = *ProposalFixture() } return &flow.BlockResponse{ @@ -270,7 +270,7 @@ func ClusterProposalFixture() *cluster.Proposal { func ClusterBlockResponseFixture(count int) *cluster.BlockResponse { blocks := make([]cluster.Proposal, count) - for i := range count { + for i := 0; i < count; i++ { blocks[i] = *ClusterProposalFixture() } return &cluster.BlockResponse{ @@ -346,7 +346,7 @@ func PayloadFixture(options ...func(*flow.Payload)) flow.Payload { func WithAllTheFixins(payload *flow.Payload) { payload.Seals = Seal.Fixtures(3) payload.Guarantees = CollectionGuaranteesFixture(4) - for range 10 { + for i := 0; i < 10; i++ { receipt := ExecutionReceiptFixture( WithResult(ExecutionResultFixture(WithServiceEvents(3))), WithSpocks(SignaturesFixture(3)), @@ -691,7 +691,7 @@ func ClusterBlockFixtures(n int) []*cluster.Block { parent := ClusterBlockFixture() - for range n { + for i := 0; i < n; i++ { block := ClusterBlockFixture( ClusterBlock.WithParent(parent), ) @@ -739,7 +739,7 @@ func CollectionGuaranteeFixture(options ...func(*flow.CollectionGuarantee)) *flo func CollectionGuaranteesWithCollectionIDFixture(collections []*flow.Collection) []*flow.CollectionGuarantee { guarantees := make([]*flow.CollectionGuarantee, 0, len(collections)) - for i := range collections { + for i := 0; i < len(collections); i++ { guarantee := CollectionGuaranteeFixture(WithCollection(collections[i])) guarantees = append(guarantees, guarantee) } @@ -760,7 +760,7 @@ func CollectionGuaranteesFixture( func BlockSealsFixture(n int) []*flow.Seal { seals := make([]*flow.Seal, 0, n) - for range n { + for i := 0; i < n; i++ { seal := Seal.Fixture() seals = append(seals, seal) } @@ -769,7 +769,7 @@ func BlockSealsFixture(n int) []*flow.Seal { func CollectionListFixture(n int, options ...func(*flow.Collection)) []*flow.Collection { collections := make([]*flow.Collection, n) - for i := range n { + for i := 0; i < n; i++ { collection := CollectionFixture(1, options...) collections[i] = &collection } @@ -779,7 +779,7 @@ func CollectionListFixture(n int, options ...func(*flow.Collection)) []*flow.Col func CollectionFixture(n int, options ...func(*flow.Collection)) flow.Collection { transactions := make([]*flow.TransactionBody, 0, n) - for range n { + for i := 0; i < n; i++ { tx := TransactionFixture() transactions = append(transactions, &tx) } @@ -994,7 +994,7 @@ func ExecutionResultListFixture( opts ...func(*flow.ExecutionResult), ) []*flow.ExecutionResult { results := make([]*flow.ExecutionResult, 0, n) - for range n { + for i := 0; i < n; i++ { results = append(results, ExecutionResultFixture(opts...)) } @@ -1020,7 +1020,7 @@ func WithServiceEvents(n int) func(result *flow.ExecutionResult) { return func(result *flow.ExecutionResult) { result.ServiceEvents = ServiceEventsFixture(n) // randomly assign service events to chunks - for range n { + for i := 0; i < n; i++ { chunkIndex := rand.Intn(result.Chunks.Len()) result.Chunks[chunkIndex].ServiceEventCount++ } @@ -1036,7 +1036,7 @@ func WithExecutionDataID(id flow.Identifier) func(result *flow.ExecutionResult) func ServiceEventsFixture(n int) flow.ServiceEventList { sel := make(flow.ServiceEventList, n) - for i := range n { + for i := 0; i < n; i++ { switch i % 3 { case 0: sel[i] = EpochCommitFixture().ServiceEvent() @@ -1141,7 +1141,7 @@ func StateCommitmentPointerFixture() *flow.StateCommitment { func HashFixture(size int) hash.Hash { hash := make(hash.Hash, size) - for i := range size { + for i := 0; i < size; i++ { hash[i] = byte(i) } return hash @@ -1149,7 +1149,7 @@ func HashFixture(size int) hash.Hash { func IdentifierListFixture(n int) flow.IdentifierList { list := make([]flow.Identifier, n) - for i := range n { + for i := 0; i < n; i++ { list[i] = IdentifierFixture() } return list @@ -1163,7 +1163,7 @@ func IdentifierFixture() flow.Identifier { func SignerIndicesFixture(n int) []byte { indices := bitutils.MakeBitVector(10) - for i := range n { + for i := 0; i < n; i++ { bitutils.SetBit(indices, i) } return indices @@ -1402,7 +1402,7 @@ func CompleteIdentitySet(identities ...*flow.Identity) flow.IdentityList { func IdentityListFixture(n int, opts ...func(*flow.Identity)) flow.IdentityList { identities := make(flow.IdentityList, 0, n) - for range n { + for i := 0; i < n; i++ { identity := IdentityFixture() identity.Address = fmt.Sprintf("%x@flow.com:1234", identity.NodeID) for _, opt := range opts { @@ -1432,7 +1432,7 @@ func DynamicIdentityEntryFixture(opts ...func(*flow.DynamicIdentityEntry)) *flow // DynamicIdentityEntryListFixture returns a list of DynamicIdentityEntry objects. func DynamicIdentityEntryListFixture(n int, opts ...func(*flow.DynamicIdentityEntry)) flow.DynamicIdentityEntryList { list := make(flow.DynamicIdentityEntryList, n) - for i := range n { + for i := 0; i < n; i++ { list[i] = DynamicIdentityEntryFixture(opts...) } return list @@ -1583,7 +1583,7 @@ func SignatureFixture() crypto.Signature { func SignaturesFixture(n int) []crypto.Signature { var sigs []crypto.Signature - for range n { + for i := 0; i < n; i++ { sigs = append(sigs, SignatureFixture()) } return sigs @@ -1591,7 +1591,7 @@ func SignaturesFixture(n int) []crypto.Signature { func RandomSourcesFixture(n int) [][]byte { var sigs [][]byte - for range n { + for i := 0; i < n; i++ { sigs = append(sigs, SignatureFixture()) } return sigs @@ -1622,7 +1622,7 @@ func TransactionBodyFixture(opts ...func(*flow.TransactionBody)) flow.Transactio func TransactionBodyListFixture(n int) []flow.TransactionBody { l := make([]flow.TransactionBody, n) - for i := range n { + for i := 0; i < n; i++ { l[i] = TransactionFixture() } @@ -1778,7 +1778,7 @@ func ChunkDataPackRequestListFixture( opts ...func(*verification.ChunkDataPackRequest), ) verification.ChunkDataPackRequestList { lst := make([]*verification.ChunkDataPackRequest, 0, n) - for range n { + for i := 0; i < n; i++ { lst = append(lst, ChunkDataPackRequestFixture(opts...)) } return lst @@ -1901,7 +1901,7 @@ func ChunkDataPacksFixture( opts ...func(*flow.ChunkDataPack), ) []*flow.ChunkDataPack { chunkDataPacks := make([]*flow.ChunkDataPack, count) - for i := range count { + for i := 0; i < count; i++ { chunkDataPacks[i] = ChunkDataPackFixture(IdentifierFixture()) } @@ -2029,7 +2029,7 @@ func KeyFixture(algo crypto.SigningAlgorithm) crypto.PrivateKey { func KeysFixture(n int, algo crypto.SigningAlgorithm) []crypto.PrivateKey { keys := make([]crypto.PrivateKey, 0, n) - for range n { + for i := 0; i < n; i++ { keys = append(keys, KeyFixture(algo)) } return keys @@ -2507,7 +2507,7 @@ func ChainFixture(nonGenesisCount int) ( func ChainFixtureFrom(count int, parent *flow.Header) []*flow.Block { blocks := make([]*flow.Block, 0, count) - for range count { + for i := 0; i < count; i++ { block := BlockWithParentFixture(parent) blocks = append(blocks, block) parent = block.ToHeader() @@ -2670,7 +2670,7 @@ func MachineAccountFixture(t *testing.T) ( func TransactionResultsFixture(n int) []flow.TransactionResult { results := make([]flow.TransactionResult, 0, n) - for range n { + for i := 0; i < n; i++ { results = append(results, flow.TransactionResult{ TransactionID: IdentifierFixture(), ErrorMessage: "whatever", @@ -2682,7 +2682,7 @@ func TransactionResultsFixture(n int) []flow.TransactionResult { func LightTransactionResultsFixture(n int) []flow.LightTransactionResult { results := make([]flow.LightTransactionResult, 0, n) - for i := range n { + for i := 0; i < n; i++ { results = append(results, flow.LightTransactionResult{ TransactionID: IdentifierFixture(), Failed: i%2 == 0, @@ -2739,7 +2739,7 @@ func EngineMessageFixture() *engine.Message { func EngineMessageFixtures(count int) []*engine.Message { messages := make([]*engine.Message, 0, count) - for range count { + for i := 0; i < count; i++ { messages = append(messages, EngineMessageFixture()) } return messages @@ -2749,7 +2749,7 @@ func EngineMessageFixtures(count int) []*engine.Message { func GetFlowProtocolEventID( t *testing.T, channel channels.Channel, - event any, + event interface{}, ) flow.Identifier { payload, err := NetworkCodec().Encode(event) require.NoError(t, err) @@ -2790,7 +2790,7 @@ func BlockExecutionDatEntityFixture(opts ...func(*execution_data.BlockExecutionD func BlockExecutionDatEntityListFixture(n int) []*execution_data.BlockExecutionDataEntity { l := make([]*execution_data.BlockExecutionDataEntity, n) - for i := range n { + for i := 0; i < n; i++ { l[i] = BlockExecutionDatEntityFixture() } @@ -2900,7 +2900,7 @@ func TransactionResultErrorMessagesFixture(n int) []flow.TransactionResultErrorM txResErrMsgs := make([]flow.TransactionResultErrorMessage, 0, n) executorID := IdentifierFixture() - for i := range n { + for i := 0; i < n; i++ { txResErrMsgs = append(txResErrMsgs, TransactionResultErrorMessageFixture( WithTxResultErrorMessageIndex(uint32(i)), WithTxResultErrorMessageTxMsg(fmt.Sprintf("transaction result error %d", i)), @@ -3138,31 +3138,31 @@ func EpochProtocolStateEntryFixture(tentativePhase flow.EpochPhase, efmTriggered return entry } -func CreateSendTxHttpPayload(tx flow.TransactionBody) map[string]any { +func CreateSendTxHttpPayload(tx flow.TransactionBody) map[string]interface{} { tx.Arguments = [][]uint8{} // fix how fixture creates nil values auth := make([]string, len(tx.Authorizers)) for i, a := range tx.Authorizers { auth[i] = a.String() } - return map[string]any{ + return map[string]interface{}{ "script": util.ToBase64(tx.Script), "arguments": tx.Arguments, "reference_block_id": tx.ReferenceBlockID.String(), "gas_limit": fmt.Sprintf("%d", tx.GasLimit), "payer": tx.Payer.String(), - "proposal_key": map[string]any{ + "proposal_key": map[string]interface{}{ "address": tx.ProposalKey.Address.String(), "key_index": fmt.Sprintf("%d", tx.ProposalKey.KeyIndex), "sequence_number": fmt.Sprintf("%d", tx.ProposalKey.SequenceNumber), }, "authorizers": auth, - "payload_signatures": []map[string]any{{ + "payload_signatures": []map[string]interface{}{{ "address": tx.PayloadSignatures[0].Address.String(), "key_index": fmt.Sprintf("%d", tx.PayloadSignatures[0].KeyIndex), "signature": util.ToBase64(tx.PayloadSignatures[0].Signature), }}, - "envelope_signatures": []map[string]any{{ + "envelope_signatures": []map[string]interface{}{{ "address": tx.EnvelopeSignatures[0].Address.String(), "key_index": fmt.Sprintf("%d", tx.EnvelopeSignatures[0].KeyIndex), "signature": util.ToBase64(tx.EnvelopeSignatures[0].Signature), @@ -3174,7 +3174,7 @@ func CreateSendTxHttpPayload(tx flow.TransactionBody) map[string]any { func P2PRPCGraftFixtures(topics ...string) []*pubsub_pb.ControlGraft { n := len(topics) grafts := make([]*pubsub_pb.ControlGraft, n) - for i := range n { + for i := 0; i < n; i++ { grafts[i] = P2PRPCGraftFixture(&topics[i]) } return grafts @@ -3191,7 +3191,7 @@ func P2PRPCGraftFixture(topic *string) *pubsub_pb.ControlGraft { func P2PRPCPruneFixtures(topics ...string) []*pubsub_pb.ControlPrune { n := len(topics) prunes := make([]*pubsub_pb.ControlPrune, n) - for i := range n { + for i := 0; i < n; i++ { prunes[i] = P2PRPCPruneFixture(&topics[i]) } return prunes @@ -3208,7 +3208,7 @@ func P2PRPCPruneFixture(topic *string) *pubsub_pb.ControlPrune { func P2PRPCIHaveFixtures(m int, topics ...string) []*pubsub_pb.ControlIHave { n := len(topics) ihaves := make([]*pubsub_pb.ControlIHave, n) - for i := range n { + for i := 0; i < n; i++ { ihaves[i] = P2PRPCIHaveFixture(&topics[i], IdentifierListFixture(m).Strings()...) } return ihaves @@ -3225,7 +3225,7 @@ func P2PRPCIHaveFixture(topic *string, messageIds ...string) *pubsub_pb.ControlI // P2PRPCIWantFixtures returns n number of control message rpc iWant fixtures with m number of message ids each. func P2PRPCIWantFixtures(n, m int) []*pubsub_pb.ControlIWant { iwants := make([]*pubsub_pb.ControlIWant, n) - for i := range n { + for i := 0; i < n; i++ { iwants[i] = P2PRPCIWantFixture(IdentifierListFixture(m).Strings()...) } return iwants @@ -3316,7 +3316,7 @@ func GossipSubMessageFixture(s string, opts ...func(*pubsub_pb.Message)) *pubsub // GossipSubMessageFixtures returns a list of gossipsub message fixtures. func GossipSubMessageFixtures(n int, topic string, opts ...func(*pubsub_pb.Message)) []*pubsub_pb.Message { msgs := make([]*pubsub_pb.Message, n) - for i := range n { + for i := 0; i < n; i++ { msgs[i] = GossipSubMessageFixture(topic, opts...) } return msgs diff --git a/utils/unittest/fixtures/collection_guarantee.go b/utils/unittest/fixtures/collection_guarantee.go index c6c0e77e91e..091d5fd85b9 100644 --- a/utils/unittest/fixtures/collection_guarantee.go +++ b/utils/unittest/fixtures/collection_guarantee.go @@ -97,7 +97,7 @@ func (g *CollectionGuaranteeGenerator) Fixture(opts ...CollectionGuaranteeOption // List generates a list of [flow.CollectionGuarantee] with random data. func (g *CollectionGuaranteeGenerator) List(n int, opts ...CollectionGuaranteeOption) []*flow.CollectionGuarantee { guarantees := make([]*flow.CollectionGuarantee, 0, n) - for range n { + for i := 0; i < n; i++ { guarantees = append(guarantees, g.Fixture(opts...)) } return guarantees diff --git a/utils/unittest/fixtures/service_event.go b/utils/unittest/fixtures/service_event.go index 227aa0c1bf5..1bda29e3a05 100644 --- a/utils/unittest/fixtures/service_event.go +++ b/utils/unittest/fixtures/service_event.go @@ -19,7 +19,7 @@ func (f serviceEventFactory) WithType(eventType flow.ServiceEventType) ServiceEv } // WithEvent is an option that sets the `Event` data of the service event. -func (f serviceEventFactory) WithEvent(eventData any) ServiceEventOption { +func (f serviceEventFactory) WithEvent(eventData interface{}) ServiceEventOption { return func(g *ServiceEventGenerator, event *flow.ServiceEvent) { event.Event = eventData } diff --git a/utils/unittest/fixtures/service_event_epoch_setup.go b/utils/unittest/fixtures/service_event_epoch_setup.go index fadc1e530ef..127dac376ee 100644 --- a/utils/unittest/fixtures/service_event_epoch_setup.go +++ b/utils/unittest/fixtures/service_event_epoch_setup.go @@ -99,7 +99,13 @@ func NewEpochSetupGenerator(random *RandomGenerator, timeGen *TimeGenerator, ide // Fixture generates a [flow.EpochSetup] with random data based on the provided options. func (g *EpochSetupGenerator) Fixture(opts ...EpochSetupOption) *flow.EpochSetup { baseView := uint64(g.random.Uint32()) - finalView := max(max(uint64(g.random.Uint32()), baseView), baseView+1000) + finalView := uint64(g.random.Uint32()) + if finalView < baseView { + finalView = baseView + } + if finalView < baseView+1000 { + finalView = baseView + 1000 + } participants := g.identities.List(5, g.identities.WithAllRoles()) participants = participants.Sort(flow.Canonical[flow.Identity]) diff --git a/utils/unittest/incorporated_results_seals.go b/utils/unittest/incorporated_results_seals.go index d755da03a8b..b92bd93ccae 100644 --- a/utils/unittest/incorporated_results_seals.go +++ b/utils/unittest/incorporated_results_seals.go @@ -31,7 +31,7 @@ func (f *incorporatedResultSealFactory) Fixture(opts ...func(*flow.IncorporatedR func (f *incorporatedResultSealFactory) Fixtures(n int) []*flow.IncorporatedResultSeal { seals := make([]*flow.IncorporatedResultSeal, 0, n) - for range n { + for i := 0; i < n; i++ { seals = append(seals, IncorporatedResultSeal.Fixture()) } return seals diff --git a/utils/unittest/keys.go b/utils/unittest/keys.go index f8c4b30a5bc..adf300948e6 100644 --- a/utils/unittest/keys.go +++ b/utils/unittest/keys.go @@ -11,7 +11,7 @@ import ( func NetworkingKeys(n int) []crypto.PrivateKey { keys := make([]crypto.PrivateKey, 0, n) - for range n { + for i := 0; i < n; i++ { key := NetworkingPrivKeyFixture() keys = append(keys, key) } @@ -22,7 +22,7 @@ func NetworkingKeys(n int) []crypto.PrivateKey { func StakingKeys(n int) []crypto.PrivateKey { keys := make([]crypto.PrivateKey, 0, n) - for range n { + for i := 0; i < n; i++ { key := StakingPrivKeyFixture() keys = append(keys, key) } diff --git a/utils/unittest/lifecycle.go b/utils/unittest/lifecycle.go index 7eadb2afbdf..bb8abf0d5ae 100644 --- a/utils/unittest/lifecycle.go +++ b/utils/unittest/lifecycle.go @@ -6,10 +6,10 @@ import ( // ReadyDoneify sets up a generated mock to respond to Ready and Done // lifecycle methods. Any mock type generated by mockery can be used. -func ReadyDoneify(toMock any) { +func ReadyDoneify(toMock interface{}) { mockable, ok := toMock.(interface { - On(string, ...any) *mock.Call + On(string, ...interface{}) *mock.Call }) if !ok { panic("attempted to mock invalid type") diff --git a/utils/unittest/locks.go b/utils/unittest/locks.go index c1902d6b915..a7387bdd31b 100644 --- a/utils/unittest/locks.go +++ b/utils/unittest/locks.go @@ -30,7 +30,7 @@ type StorageLockAcquisitionError struct { err error } -func NewStorageLockAcquisitionErrorf(msg string, args ...any) error { +func NewStorageLockAcquisitionErrorf(msg string, args ...interface{}) error { return StorageLockAcquisitionError{ err: fmt.Errorf(msg, args...), } diff --git a/utils/unittest/math.go b/utils/unittest/math.go index 26f67ed0484..eb44762247d 100644 --- a/utils/unittest/math.go +++ b/utils/unittest/math.go @@ -25,7 +25,7 @@ import ( // t: the testing.TB instance // a: the first float // b: the second float -func RequireNumericallyClose(t testing.TB, a, b float64, epsilon float64, msgAndArgs ...any) { +func RequireNumericallyClose(t testing.TB, a, b float64, epsilon float64, msgAndArgs ...interface{}) { require.True(t, AreNumericallyClose(a, b, epsilon), msgAndArgs...) } diff --git a/utils/unittest/seals.go b/utils/unittest/seals.go index 90d73c8cf4f..3e69b4ee69e 100644 --- a/utils/unittest/seals.go +++ b/utils/unittest/seals.go @@ -21,7 +21,7 @@ func (f *sealFactory) Fixture(opts ...func(*flow.Seal)) *flow.Seal { func (f *sealFactory) Fixtures(n int) []*flow.Seal { seals := make([]*flow.Seal, 0, n) - for range n { + for i := 0; i < n; i++ { seal := Seal.Fixture() seals = append(seals, seal) } diff --git a/utils/unittest/unittest.go b/utils/unittest/unittest.go index 1065c5a39a9..e74c3ff37a5 100644 --- a/utils/unittest/unittest.go +++ b/utils/unittest/unittest.go @@ -128,7 +128,7 @@ func SkipBenchmarkUnless(b *testing.B, reason SkipBenchmarkReason, message strin // AssertReturnsBefore asserts that the given function returns before the // duration expires. -func AssertReturnsBefore(t *testing.T, f func(), duration time.Duration, msgAndArgs ...any) bool { +func AssertReturnsBefore(t *testing.T, f func(), duration time.Duration, msgAndArgs ...interface{}) bool { done := make(chan struct{}) go func() { @@ -155,7 +155,7 @@ func ClosedChannel() <-chan struct{} { // AssertClosesBefore asserts that the given channel closes before the // duration expires. -func AssertClosesBefore(t assert.TestingT, done <-chan struct{}, duration time.Duration, msgAndArgs ...any) { +func AssertClosesBefore(t assert.TestingT, done <-chan struct{}, duration time.Duration, msgAndArgs ...interface{}) { select { case <-time.After(duration): assert.Fail(t, "channel did not return in time", msgAndArgs...) @@ -172,7 +172,7 @@ func AssertFloatEqual(t *testing.T, expected, actual float64, message string) { } // AssertNotClosesBefore asserts that the given channel does not close before the duration expires. -func AssertNotClosesBefore(t assert.TestingT, done <-chan struct{}, duration time.Duration, msgAndArgs ...any) { +func AssertNotClosesBefore(t assert.TestingT, done <-chan struct{}, duration time.Duration, msgAndArgs ...interface{}) { select { case <-time.After(duration): return @@ -232,10 +232,12 @@ func RequireClosed(t *testing.T, ch <-chan struct{}, message string) { // and requires all invocations to return within duration. func RequireConcurrentCallsReturnBefore(t *testing.T, f func(), count int, duration time.Duration, message string) { wg := &sync.WaitGroup{} - for range count { - wg.Go(func() { + for i := 0; i < count; i++ { + wg.Add(1) + go func() { f() - }) + wg.Done() + }() } RequireReturnsBefore(t, wg.Wait, duration, message) @@ -454,7 +456,7 @@ func RunWithTypedPebbleDB( func Concurrently(n int, f func(int)) { var wg sync.WaitGroup - for i := range n { + for i := 0; i < n; i++ { wg.Add(1) go func(i int) { f(i) @@ -566,7 +568,7 @@ func generateNetworkingKey(s flow.Identifier) (crypto.PrivateKey, error) { // PeerIdFixtures creates random and unique peer IDs (libp2p node IDs). func PeerIdFixtures(t *testing.T, n int) []peer.ID { peerIDs := make([]peer.ID, n) - for i := range n { + for i := 0; i < n; i++ { peerIDs[i] = PeerIdFixture(t) } return peerIDs diff --git a/utils/unittest/utils.go b/utils/unittest/utils.go index 7153b82b859..e76b7e63f30 100644 --- a/utils/unittest/utils.go +++ b/utils/unittest/utils.go @@ -11,7 +11,7 @@ import ( ) // VerifyCdcArguments verifies that the actual slice of Go values match the expected set of Cadence values. -func VerifyCdcArguments(t *testing.T, expected []cadence.Value, actual []any) { +func VerifyCdcArguments(t *testing.T, expected []cadence.Value, actual []interface{}) { for index, arg := range actual { // marshal to bytes bz, err := json.Marshal(arg) @@ -26,7 +26,7 @@ func VerifyCdcArguments(t *testing.T, expected []cadence.Value, actual []any) { } // InterfaceToCdcValues decodes jsoncdc encoded values from interface -> cadence value. -func InterfaceToCdcValues(t *testing.T, vals []any) []cadence.Value { +func InterfaceToCdcValues(t *testing.T, vals []interface{}) []cadence.Value { decoded := make([]cadence.Value, len(vals)) for index, val := range vals { // marshal to bytes