From 72d67ec313493bfb3a3e52e5784db9476a02514a Mon Sep 17 00:00:00 2001 From: FrancoGiachetta Date: Tue, 10 Dec 2024 15:37:08 -0300 Subject: [PATCH] format --- crates/blockifier/bench/blockifier_bench.rs | 2 +- .../resources/versioned_constants_0_13_4.json | 4 - crates/blockifier/src/abi/sierra_types.rs | 2 +- .../blockifier/src/blockifier/block_test.rs | 2 +- crates/blockifier/src/blockifier/config.rs | 2 +- .../src/blockifier/stateful_validator.rs | 2 +- .../src/blockifier/stateful_validator_test.rs | 9 +- .../src/blockifier/transaction_executor.rs | 2 +- .../blockifier/transaction_executor_test.rs | 23 +- crates/blockifier/src/bouncer.rs | 2 +- crates/blockifier/src/bouncer_test.rs | 2 +- .../src/concurrency/fee_utils_test.rs | 2 +- .../blockifier/src/concurrency/flow_test.rs | 4 +- .../blockifier/src/concurrency/scheduler.rs | 2 +- .../src/concurrency/scheduler_test.rs | 4 +- .../src/concurrency/versioned_state.rs | 2 +- .../src/concurrency/versioned_state_test.rs | 50 +- .../src/concurrency/versioned_storage_test.rs | 2 +- .../src/concurrency/worker_logic.rs | 2 +- .../src/concurrency/worker_logic_test.rs | 8 +- crates/blockifier/src/context.rs | 2 +- .../src/execution/contract_address_test.rs | 4 +- .../src/execution/contract_class.rs | 4 +- .../deprecated_entry_point_execution.rs | 2 +- .../deprecated_syscalls_test.rs | 30 +- .../deprecated_syscalls/hint_processor.rs | 17 +- .../src/execution/deprecated_syscalls/mod.rs | 8 +- .../blockifier/src/execution/entry_point.rs | 4 +- .../src/execution/entry_point_execution.rs | 4 +- .../src/execution/entry_point_test.rs | 9 +- .../src/execution/execution_utils.rs | 8 +- .../src/execution/native/syscall_handler.rs | 8 +- crates/blockifier/src/execution/secp.rs | 8 +- .../blockifier/src/execution/stack_trace.rs | 30 +- .../src/execution/stack_trace_test.rs | 71 +-- .../src/execution/syscalls/hint_processor.rs | 18 +- .../blockifier/src/execution/syscalls/mod.rs | 7 +- .../blockifier/src/execution/syscalls/secp.rs | 2 +- .../src/execution/syscalls/syscall_base.rs | 16 +- .../syscalls/syscall_tests/call_contract.rs | 26 +- .../syscalls/syscall_tests/deploy.rs | 64 ++- .../syscalls/syscall_tests/emit_event.rs | 15 +- .../syscalls/syscall_tests/failure_format.rs | 2 +- .../syscalls/syscall_tests/get_block_hash.rs | 10 +- .../syscall_tests/get_class_hash_at.rs | 17 +- .../syscall_tests/get_execution_info.rs | 8 +- .../syscalls/syscall_tests/keccak.rs | 2 +- .../syscalls/syscall_tests/library_call.rs | 42 +- .../syscalls/syscall_tests/out_of_gas.rs | 36 +- .../syscalls/syscall_tests/replace_class.rs | 29 +- .../execution/syscalls/syscall_tests/secp.rs | 2 +- .../syscall_tests/send_message_to_l1.rs | 4 +- .../syscalls/syscall_tests/sha256.rs | 2 +- .../syscall_tests/storage_read_write.rs | 15 +- crates/blockifier/src/fee/fee_checks.rs | 4 +- crates/blockifier/src/fee/fee_test.rs | 6 +- crates/blockifier/src/fee/gas_usage_test.rs | 18 +- crates/blockifier/src/fee/receipt_test.rs | 13 +- crates/blockifier/src/state/cached_state.rs | 6 +- .../blockifier/src/state/cached_state_test.rs | 100 ++-- .../src/state/contract_class_manager.rs | 4 +- crates/blockifier/src/state/errors.rs | 2 +- crates/blockifier/src/test_utils.rs | 2 +- crates/blockifier/src/test_utils/contracts.rs | 4 +- .../src/test_utils/initial_test_state.rs | 2 +- .../blockifier/src/test_utils/l1_handler.rs | 4 +- crates/blockifier/src/test_utils/prices.rs | 2 +- .../blockifier/src/test_utils/struct_impls.rs | 12 +- crates/blockifier/src/test_utils/syscall.rs | 2 +- .../src/test_utils/transfers_generator.rs | 6 +- .../src/transaction/account_transaction.rs | 12 +- .../transaction/account_transactions_test.rs | 490 ++++++++---------- crates/blockifier/src/transaction/errors.rs | 6 +- .../src/transaction/execution_flavors_test.rs | 101 ++-- crates/blockifier/src/transaction/objects.rs | 2 +- .../src/transaction/post_execution_test.rs | 190 +++---- .../blockifier/src/transaction/test_utils.rs | 12 +- .../src/transaction/transaction_execution.rs | 2 +- .../src/transaction/transactions.rs | 2 +- .../src/transaction/transactions_test.rs | 175 +++---- crates/blockifier/src/utils_test.rs | 2 +- crates/blockifier/src/versioned_constants.rs | 8 +- .../src/versioned_constants_test.rs | 2 +- .../feature_contracts_compatibility_test.rs | 4 +- crates/blockifier_reexecution/src/main.rs | 8 +- .../src/state_reader/offline_state_reader.rs | 2 +- .../src/state_reader/test_state_reader.rs | 36 +- .../committer_cli/benches/committer_bench.rs | 2 +- crates/committer_cli/src/commands.rs | 2 +- .../src/tests/utils/random_structs.rs | 2 +- crates/committer_cli/src/tracing_utils.rs | 2 +- crates/infra_utils/src/run_until.rs | 2 +- .../src/starknet_api_test_utils.rs | 6 +- crates/native_blockifier/src/lib.rs | 2 +- .../src/py_block_executor.rs | 4 +- crates/native_blockifier/src/py_declare.rs | 2 +- .../src/py_deploy_account.rs | 2 +- .../src/py_invoke_function.rs | 2 +- crates/native_blockifier/src/py_l1_handler.rs | 4 +- crates/native_blockifier/src/py_state_diff.rs | 2 +- crates/native_blockifier/src/py_test_utils.rs | 3 +- .../src/py_testing_wrappers.rs | 2 +- .../native_blockifier/src/py_transaction.rs | 2 +- crates/native_blockifier/src/py_validator.rs | 4 +- crates/native_blockifier/src/storage.rs | 4 +- .../papyrus_base_layer/src/base_layer_test.rs | 2 +- .../src/ethereum_base_layer_contract.rs | 2 +- crates/papyrus_base_layer/src/test_utils.rs | 2 +- crates/papyrus_common/src/python_json.rs | 12 +- crates/papyrus_config/src/command.rs | 4 +- crates/papyrus_config/src/config_test.rs | 41 +- crates/papyrus_config/src/dumping.rs | 19 +- crates/papyrus_config/src/loading.rs | 8 +- .../papyrus_execution/src/execution_test.rs | 184 +++---- .../papyrus_execution/src/execution_utils.rs | 2 +- crates/papyrus_execution/src/lib.rs | 6 +- crates/papyrus_execution/src/state_reader.rs | 2 +- .../src/state_reader_test.rs | 91 ++-- crates/papyrus_execution/src/test_utils.rs | 121 ++--- .../src/testing_instances.rs | 4 +- .../src/compare_endpoints.rs | 2 +- crates/papyrus_load_test/src/create_files.rs | 8 +- .../papyrus_load_test/src/create_request.rs | 2 +- crates/papyrus_load_test/src/lib.rs | 2 +- crates/papyrus_load_test/src/main.rs | 2 +- crates/papyrus_load_test/src/scenarios.rs | 6 +- crates/papyrus_load_test/src/transactions.rs | 4 +- .../src/gateway_test.rs | 6 +- crates/papyrus_monitoring_gateway/src/lib.rs | 6 +- crates/papyrus_network/src/bin_utils/mod.rs | 2 +- .../src/discovery/flow_test.rs | 2 +- .../src/discovery/identify_impl.rs | 2 +- crates/papyrus_network/src/discovery/mod.rs | 12 +- crates/papyrus_network/src/gossipsub_impl.rs | 2 +- crates/papyrus_network/src/lib.rs | 2 +- crates/papyrus_network/src/mixed_behaviour.rs | 17 +- .../src/network_manager/mod.rs | 8 +- .../src/network_manager/swarm_trait.rs | 2 +- .../src/network_manager/test.rs | 4 +- .../src/network_manager/test_utils.rs | 4 +- .../src/peer_manager/behaviour_impl.rs | 10 +- .../papyrus_network/src/peer_manager/mod.rs | 8 +- .../papyrus_network/src/peer_manager/test.rs | 9 +- crates/papyrus_network/src/sqmr/behaviour.rs | 2 +- crates/papyrus_network/src/sqmr/flow_test.rs | 2 +- crates/papyrus_network/src/sqmr/handler.rs | 2 +- .../src/sqmr/handler/inbound_session.rs | 4 +- .../papyrus_network/src/sqmr/handler_test.rs | 4 +- .../papyrus_network/src/sqmr/messages_test.rs | 6 +- crates/papyrus_network/src/sqmr/protocol.rs | 4 +- .../papyrus_network/src/sqmr/protocol_test.rs | 4 +- .../src/test_utils/get_stream.rs | 2 +- crates/papyrus_network/src/test_utils/mod.rs | 6 +- crates/papyrus_network/src/utils.rs | 4 +- .../papyrus_network_types/src/test_utils.rs | 2 +- .../examples/get_transaction_hash.rs | 16 +- .../src/bin/papyrus_dump_config.rs | 2 +- crates/papyrus_node/src/bin/run_consensus.rs | 2 +- crates/papyrus_node/src/config/config_test.rs | 4 +- crates/papyrus_node/src/config/mod.rs | 12 +- crates/papyrus_node/src/config/pointers.rs | 22 +- crates/papyrus_node/src/main.rs | 2 +- crates/papyrus_node/src/run.rs | 12 +- crates/papyrus_node/src/run_test.rs | 4 +- crates/papyrus_p2p_sync/src/client/class.rs | 2 +- .../papyrus_p2p_sync/src/client/class_test.rs | 6 +- crates/papyrus_p2p_sync/src/client/header.rs | 2 +- .../src/client/header_test.rs | 44 +- crates/papyrus_p2p_sync/src/client/mod.rs | 4 +- .../papyrus_p2p_sync/src/client/state_diff.rs | 2 +- .../src/client/state_diff_test.rs | 165 +++--- .../src/client/stream_builder.rs | 2 +- .../papyrus_p2p_sync/src/client/test_utils.rs | 8 +- .../src/client/transaction.rs | 2 +- .../src/client/transaction_test.rs | 6 +- crates/papyrus_p2p_sync/src/server/mod.rs | 2 +- crates/papyrus_p2p_sync/src/server/test.rs | 8 +- crates/papyrus_proc_macros/src/lib.rs | 6 +- crates/papyrus_protobuf/build.rs | 6 +- .../papyrus_protobuf/src/converters/class.rs | 2 +- .../src/converters/class_test.rs | 2 +- .../src/converters/consensus_test.rs | 2 +- .../src/converters/event_test.rs | 2 +- .../papyrus_protobuf/src/converters/header.rs | 4 +- .../src/converters/header_test.rs | 2 +- .../src/converters/receipt.rs | 2 +- .../src/converters/rpc_transaction_test.rs | 2 +- .../src/converters/state_diff.rs | 2 +- .../src/converters/state_diff_test.rs | 2 +- .../src/converters/test_instances.rs | 2 +- .../src/converters/transaction.rs | 4 +- .../src/converters/transaction_test.rs | 2 +- crates/papyrus_protobuf/src/sync.rs | 2 +- crates/papyrus_rpc/src/lib.rs | 6 +- crates/papyrus_rpc/src/middleware.rs | 2 +- crates/papyrus_rpc/src/rpc_metrics/mod.rs | 2 +- .../src/rpc_metrics/rpc_metrics_test.rs | 6 +- crates/papyrus_rpc/src/rpc_test.rs | 4 +- crates/papyrus_rpc/src/test_utils.rs | 8 +- crates/papyrus_rpc/src/v0_8/api/api_impl.rs | 54 +- crates/papyrus_rpc/src/v0_8/api/mod.rs | 8 +- crates/papyrus_rpc/src/v0_8/api/test.rs | 253 ++++----- crates/papyrus_rpc/src/v0_8/block.rs | 6 +- .../src/v0_8/broadcasted_transaction.rs | 2 +- .../src/v0_8/broadcasted_transaction_test.rs | 25 +- crates/papyrus_rpc/src/v0_8/execution_test.rs | 319 +++++------- crates/papyrus_rpc/src/v0_8/transaction.rs | 4 +- .../papyrus_rpc/src/v0_8/transaction_test.rs | 2 +- .../papyrus_rpc/src/v0_8/write_api_error.rs | 8 +- .../src/v0_8/write_api_error_test.rs | 2 +- .../src/v0_8/write_api_result_test.rs | 4 +- crates/papyrus_rpc/src/version_config_test.rs | 2 +- .../papyrus_state_reader/src/papyrus_state.rs | 2 +- .../src/papyrus_state_test.rs | 4 +- crates/papyrus_storage/src/base_layer.rs | 2 +- .../src/bin/storage_benchmark.rs | 4 +- crates/papyrus_storage/src/body/body_test.rs | 161 +++--- crates/papyrus_storage/src/body/events.rs | 4 +- .../papyrus_storage/src/body/events_test.rs | 42 +- crates/papyrus_storage/src/body/mod.rs | 12 +- crates/papyrus_storage/src/class.rs | 2 +- crates/papyrus_storage/src/class_test.rs | 34 +- crates/papyrus_storage/src/compiled_class.rs | 2 +- .../src/compiled_class_test.rs | 32 +- .../papyrus_storage/src/compression_utils.rs | 2 +- crates/papyrus_storage/src/db/db_test.rs | 2 +- crates/papyrus_storage/src/db/mod.rs | 2 +- .../src/db/table_types/dup_sort_tables.rs | 28 +- .../db/table_types/dup_sort_tables_test.rs | 4 +- .../papyrus_storage/src/db/table_types/mod.rs | 2 +- .../src/db/table_types/simple_table.rs | 4 +- .../src/db/table_types/simple_table_test.rs | 2 +- .../src/db/table_types/test_utils.rs | 6 +- crates/papyrus_storage/src/header.rs | 2 +- crates/papyrus_storage/src/header_test.rs | 34 +- crates/papyrus_storage/src/lib.rs | 8 +- crates/papyrus_storage/src/mmap_file/mod.rs | 4 +- .../src/serialization/serializers.rs | 8 +- .../src/serialization/serializers_test.rs | 2 +- crates/papyrus_storage/src/state/mod.rs | 4 +- .../papyrus_storage/src/state/state_test.rs | 114 ++-- crates/papyrus_storage/src/test_instances.rs | 2 +- crates/papyrus_storage/src/test_utils.rs | 4 +- crates/papyrus_storage/src/version.rs | 2 +- crates/papyrus_storage/src/version_test.rs | 26 +- crates/papyrus_sync/src/lib.rs | 12 +- crates/papyrus_sync/src/pending_sync.rs | 4 +- crates/papyrus_sync/src/sources/base_layer.rs | 8 +- crates/papyrus_sync/src/sources/central.rs | 4 +- .../sources/central/state_update_stream.rs | 2 +- .../papyrus_sync/src/sources/central_test.rs | 52 +- crates/papyrus_sync/src/sources/pending.rs | 2 +- crates/papyrus_sync/src/sync_test.rs | 78 ++- crates/papyrus_test_utils/src/lib.rs | 2 +- .../papyrus_consensus/src/config.rs | 2 +- .../papyrus_consensus/src/manager_test.rs | 75 ++- .../src/simulation_network_receiver_test.rs | 4 +- .../src/single_height_consensus.rs | 6 +- .../src/single_height_consensus_test.rs | 36 +- .../src/state_machine_test.rs | 2 +- .../papyrus_consensus/src/stream_handler.rs | 2 +- .../src/stream_handler_test.rs | 76 +-- .../papyrus_consensus/src/test_utils.rs | 2 +- .../src/papyrus_consensus_context.rs | 4 +- .../src/papyrus_consensus_context_test.rs | 8 +- .../src/sequencer_consensus_context.rs | 8 +- .../src/sequencer_consensus_context_test.rs | 34 +- crates/starknet_api/src/abi/abi_utils.rs | 2 +- crates/starknet_api/src/block.rs | 4 +- .../src/block_hash/block_hash_calculator.rs | 30 +- .../block_hash/block_hash_calculator_test.rs | 4 +- .../src/block_hash/event_commitment_test.rs | 2 +- .../src/block_hash/receipt_commitment_test.rs | 2 +- .../src/block_hash/state_diff_hash.rs | 2 +- .../src/block_hash/transaction_commitment.rs | 2 +- crates/starknet_api/src/block_test.rs | 8 +- crates/starknet_api/src/contract_class.rs | 2 +- crates/starknet_api/src/core.rs | 6 +- crates/starknet_api/src/core_test.rs | 4 +- crates/starknet_api/src/crypto/crypto_test.rs | 2 +- .../src/deprecated_contract_class.rs | 2 +- .../src/executable_transaction.rs | 4 +- crates/starknet_api/src/execution_utils.rs | 6 +- crates/starknet_api/src/rpc_transaction.rs | 4 +- .../starknet_api/src/rpc_transaction_test.rs | 2 +- crates/starknet_api/src/serde_utils.rs | 8 +- crates/starknet_api/src/serde_utils_test.rs | 33 +- crates/starknet_api/src/state.rs | 2 +- crates/starknet_api/src/state_test.rs | 74 +-- .../src/test_utils/deploy_account.rs | 2 +- crates/starknet_api/src/transaction.rs | 2 +- crates/starknet_api/src/transaction/fields.rs | 2 +- crates/starknet_api/src/transaction_hash.rs | 14 +- .../starknet_api/src/transaction_hash_test.rs | 4 +- crates/starknet_api/src/transaction_test.rs | 2 +- crates/starknet_batcher/src/batcher_test.rs | 23 +- crates/starknet_batcher/src/block_builder.rs | 2 +- .../src/block_builder_test.rs | 6 +- crates/starknet_batcher/src/config.rs | 2 +- crates/starknet_batcher/src/fee_market.rs | 2 +- .../starknet_batcher/src/fee_market_test.rs | 2 +- .../starknet_batcher/src/proposal_manager.rs | 2 +- crates/starknet_batcher/src/test_utils.rs | 2 +- .../src/transaction_provider_test.rs | 18 +- crates/starknet_client/src/reader/mod.rs | 2 +- .../src/reader/objects/block_test.rs | 2 +- .../src/reader/objects/test_utils.rs | 2 +- .../starknet_feeder_gateway_client_test.rs | 60 +-- crates/starknet_client/src/retry.rs | 2 +- crates/starknet_client/src/retry_test.rs | 6 +- .../src/starknet_client_test.rs | 2 +- .../src/writer/objects/test_utils.rs | 2 +- .../src/writer/objects/transaction.rs | 2 +- .../writer/starknet_gateway_client_test.rs | 2 +- .../src/forest/filled_forest.rs | 29 +- .../starknet_consensus_manager/src/config.rs | 2 +- crates/starknet_gateway/src/compilation.rs | 2 +- .../starknet_gateway/src/compilation_test.rs | 2 +- .../starknet_gateway/src/compiler_version.rs | 2 +- crates/starknet_gateway/src/config.rs | 2 +- crates/starknet_gateway/src/errors.rs | 2 +- crates/starknet_gateway/src/gateway.rs | 2 +- crates/starknet_gateway/src/gateway_test.rs | 4 +- .../starknet_gateway/src/rpc_state_reader.rs | 8 +- .../src/state_reader_test_utils.rs | 11 +- .../stateful_transaction_validator_test.rs | 6 +- .../src/stateless_transaction_validator.rs | 2 +- .../stateless_transaction_validator_test.rs | 6 +- crates/starknet_gateway/src/test_utils.rs | 2 +- crates/starknet_gateway_types/src/errors.rs | 8 +- crates/starknet_http_server/src/config.rs | 2 +- .../starknet_http_server/src/http_server.rs | 2 +- .../src/config_utils.rs | 2 +- .../src/flow_test_setup.rs | 2 +- .../src/integration_test_setup.rs | 4 +- .../src/state_reader.rs | 6 +- .../starknet_integration_tests/src/utils.rs | 4 +- .../tests/end_to_end_integration_test.rs | 2 +- .../tests/mempool_p2p_flow_test.rs | 4 +- .../src/l1_provider_tests.rs | 4 +- crates/starknet_mempool/src/mempool.rs | 2 +- crates/starknet_mempool/src/mempool_test.rs | 50 +- .../starknet_mempool/src/transaction_pool.rs | 2 +- .../starknet_mempool/src/transaction_queue.rs | 2 +- crates/starknet_mempool/tests/flow_test.rs | 115 ++-- crates/starknet_mempool_p2p/src/config.rs | 2 +- .../src/propagator/test.rs | 6 +- crates/starknet_mempool_p2p/src/runner/mod.rs | 2 +- .../starknet_mempool_p2p/src/runner/test.rs | 8 +- .../src/config.rs | 2 +- .../src/monitoring_endpoint.rs | 2 +- .../src/monitoring_endpoint_test.rs | 6 +- .../src/test_utils.rs | 2 +- .../external_test_utils.rs | 13 +- .../patricia_merkle_tree/filled_tree/tree.rs | 27 +- .../filled_tree/tree_test.rs | 56 +- .../patricia_merkle_tree/node_data/leaf.rs | 6 +- .../original_skeleton_tree/create_tree.rs | 2 +- .../create_tree_test.rs | 2 +- .../original_skeleton_tree/utils_test.rs | 4 +- .../src/patricia_merkle_tree/types_test.rs | 4 +- .../create_tree_helper_test.rs | 8 +- .../updated_skeleton_tree/tree_test.rs | 2 +- .../src/component_client/definitions.rs | 2 +- .../local_component_client.rs | 4 +- .../remote_component_client.rs | 4 +- .../src/component_definitions.rs | 2 +- .../remote_component_server.rs | 4 +- .../local_component_client_server_test.rs | 6 +- .../remote_component_client_server_test.rs | 14 +- .../src/trace_util.rs | 2 +- .../src/bin/sequencer_dump_config.rs | 2 +- .../src/communication.rs | 2 +- .../starknet_sequencer_node/src/components.rs | 10 +- .../src/config/component_config.rs | 2 +- .../src/config/component_execution_config.rs | 2 +- .../src/config/config_test.rs | 14 +- .../src/config/node_config.rs | 6 +- crates/starknet_sequencer_node/src/main.rs | 2 +- crates/starknet_sequencer_node/src/utils.rs | 4 +- .../src/command_line_compiler.rs | 6 +- .../src/compile_test.rs | 6 +- crates/starknet_sierra_compile/src/config.rs | 2 +- crates/starknet_state_sync/src/config.rs | 2 +- crates/starknet_state_sync/src/lib.rs | 2 +- crates/starknet_state_sync/src/runner/mod.rs | 6 +- 386 files changed, 2549 insertions(+), 3060 deletions(-) diff --git a/crates/blockifier/bench/blockifier_bench.rs b/crates/blockifier/bench/blockifier_bench.rs index a59d71d6c0..5b62bbd464 100644 --- a/crates/blockifier/bench/blockifier_bench.rs +++ b/crates/blockifier/bench/blockifier_bench.rs @@ -10,7 +10,7 @@ use blockifier::test_utils::transfers_generator::{ RecipientGeneratorType, TransfersGenerator, TransfersGeneratorConfig, }; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; pub fn transfers_benchmark(c: &mut Criterion) { let transfers_generator_config = TransfersGeneratorConfig { diff --git a/crates/blockifier/resources/versioned_constants_0_13_4.json b/crates/blockifier/resources/versioned_constants_0_13_4.json index 8bc5ae32c6..dbb15ca39d 100644 --- a/crates/blockifier/resources/versioned_constants_0_13_4.json +++ b/crates/blockifier/resources/versioned_constants_0_13_4.json @@ -10,7 +10,6 @@ }, "invoke_tx_max_n_steps": 10000000, "execute_max_sierra_gas": 1000000000, - "execute_max_sierra_gas": 1000000000, "deprecated_l2_resource_gas_costs": { "gas_per_data_felt": [ 128, @@ -42,7 +41,6 @@ "disable_cairo0_redeclaration": true, "enable_stateful_compression": true, "comprehensive_state_diff": true, - "comprehensive_state_diff": true, "allocation_cost": { "blob_cost": { "l1_gas": 0, @@ -95,7 +93,6 @@ }, "range_check_gas_cost": 70, "keccak_builtin_gas_cost": 136189, - "keccak_builtin_gas_cost": 136189, "pedersen_gas_cost": 4050, "bitwise_builtin_gas_cost": 583, "ecop_gas_cost": 4085, @@ -616,7 +613,6 @@ }, "validate_max_n_steps": 1000000, "validate_max_sierra_gas": 100000000, - "validate_max_sierra_gas": 100000000, "min_compiler_version_for_sierra_gas": "2.8.0", "vm_resource_fee_cost": { "builtins": { diff --git a/crates/blockifier/src/abi/sierra_types.rs b/crates/blockifier/src/abi/sierra_types.rs index 121a5b84b3..7c817cb4b9 100644 --- a/crates/blockifier/src/abi/sierra_types.rs +++ b/crates/blockifier/src/abi/sierra_types.rs @@ -4,9 +4,9 @@ use cairo_vm::vm::errors::memory_errors::MemoryError; use cairo_vm::vm::vm_core::VirtualMachine; use num_bigint::{BigUint, ToBigUint}; use num_traits::ToPrimitive; +use starknet_api::StarknetApiError; use starknet_api::core::ContractAddress; use starknet_api::state::StorageKey; -use starknet_api::StarknetApiError; use starknet_types_core::felt::Felt; use thiserror::Error; diff --git a/crates/blockifier/src/blockifier/block_test.rs b/crates/blockifier/src/blockifier/block_test.rs index 99c8010131..6c0cdc1a3a 100644 --- a/crates/blockifier/src/blockifier/block_test.rs +++ b/crates/blockifier/src/blockifier/block_test.rs @@ -8,7 +8,7 @@ use crate::context::ChainInfo; use crate::state::state_api::StateReader; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{CairoVersion, RunnableCairo1, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1}; use crate::versioned_constants::VersionedConstants; #[test] diff --git a/crates/blockifier/src/blockifier/config.rs b/crates/blockifier/src/blockifier/config.rs index bc8b5628ce..d69d5681e8 100644 --- a/crates/blockifier/src/blockifier/config.rs +++ b/crates/blockifier/src/blockifier/config.rs @@ -1,6 +1,6 @@ use std::collections::BTreeMap; -use papyrus_config::dumping::{append_sub_config_name, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use serde::{Deserialize, Serialize}; diff --git a/crates/blockifier/src/blockifier/stateful_validator.rs b/crates/blockifier/src/blockifier/stateful_validator.rs index b43a659c49..30c00324d9 100644 --- a/crates/blockifier/src/blockifier/stateful_validator.rs +++ b/crates/blockifier/src/blockifier/stateful_validator.rs @@ -6,7 +6,7 @@ use thiserror::Error; use crate::blockifier::config::TransactionExecutorConfig; use crate::blockifier::transaction_executor::{ - TransactionExecutor, TransactionExecutorError, BLOCK_STATE_ACCESS_ERR, + BLOCK_STATE_ACCESS_ERR, TransactionExecutor, TransactionExecutorError, }; use crate::context::{BlockContext, TransactionContext}; use crate::execution::call_info::CallInfo; diff --git a/crates/blockifier/src/blockifier/stateful_validator_test.rs b/crates/blockifier/src/blockifier/stateful_validator_test.rs index d1293b811d..d85a430b0a 100644 --- a/crates/blockifier/src/blockifier/stateful_validator_test.rs +++ b/crates/blockifier/src/blockifier/stateful_validator_test.rs @@ -1,17 +1,18 @@ use assert_matches::assert_matches; use rstest::rstest; use starknet_api::executable_transaction::AccountTransaction as Transaction; -use starknet_api::transaction::fields::ValidResourceBounds; use starknet_api::transaction::TransactionVersion; +use starknet_api::transaction::fields::ValidResourceBounds; use crate::blockifier::stateful_validator::StatefulValidator; use crate::context::BlockContext; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::{fund_account, test_state}; -use crate::test_utils::{CairoVersion, RunnableCairo1, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1}; use crate::transaction::test_utils::{ - block_context, create_account_tx_for_validate_test_nonce_0, default_all_resource_bounds, - default_l1_resource_bounds, FaultyAccountTxCreatorArgs, INVALID, VALID, + FaultyAccountTxCreatorArgs, INVALID, VALID, block_context, + create_account_tx_for_validate_test_nonce_0, default_all_resource_bounds, + default_l1_resource_bounds, }; use crate::transaction::transaction_types::TransactionType; diff --git a/crates/blockifier/src/blockifier/transaction_executor.rs b/crates/blockifier/src/blockifier/transaction_executor.rs index bec2bd5b8c..9c92ed890c 100644 --- a/crates/blockifier/src/blockifier/transaction_executor.rs +++ b/crates/blockifier/src/blockifier/transaction_executor.rs @@ -1,5 +1,5 @@ use std::collections::{HashMap, HashSet}; -use std::panic::{self, catch_unwind, AssertUnwindSafe}; +use std::panic::{self, AssertUnwindSafe, catch_unwind}; use std::sync::{Arc, Mutex}; use itertools::FoldWhile::{Continue, Done}; diff --git a/crates/blockifier/src/blockifier/transaction_executor_test.rs b/crates/blockifier/src/blockifier/transaction_executor_test.rs index 88c2845520..4ef425df7b 100644 --- a/crates/blockifier/src/blockifier/transaction_executor_test.rs +++ b/crates/blockifier/src/blockifier/transaction_executor_test.rs @@ -1,18 +1,18 @@ use assert_matches::assert_matches; use pretty_assertions::assert_eq; use rstest::rstest; +use starknet_api::test_utils::NonceManager; use starknet_api::test_utils::declare::executable_declare_tx; use starknet_api::test_utils::deploy_account::executable_deploy_account_tx; use starknet_api::test_utils::invoke::executable_invoke_tx; -use starknet_api::test_utils::NonceManager; -use starknet_api::transaction::fields::Fee; use starknet_api::transaction::TransactionVersion; +use starknet_api::transaction::fields::Fee; use starknet_api::{declare_tx_args, deploy_account_tx_args, felt, invoke_tx_args, nonce}; use starknet_types_core::felt::Felt; use crate::blockifier::config::TransactionExecutorConfig; use crate::blockifier::transaction_executor::{ - TransactionExecutor, TransactionExecutorError, BLOCK_STATE_ACCESS_ERR, + BLOCK_STATE_ACCESS_ERR, TransactionExecutor, TransactionExecutorError, }; use crate::bouncer::{Bouncer, BouncerWeights}; use crate::context::BlockContext; @@ -22,14 +22,14 @@ use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::l1_handler::l1handler_tx; use crate::test_utils::{ - create_calldata, maybe_dummy_block_hash_and_number, CairoVersion, RunnableCairo1, BALANCE, - DEFAULT_STRK_L1_GAS_PRICE, + BALANCE, CairoVersion, DEFAULT_STRK_L1_GAS_PRICE, RunnableCairo1, create_calldata, + maybe_dummy_block_hash_and_number, }; use crate::transaction::account_transaction::AccountTransaction; use crate::transaction::errors::TransactionExecutionError; use crate::transaction::test_utils::{ - block_context, calculate_class_info_for_testing, create_test_init_data, emit_n_events_tx, - l1_resource_bounds, TestInitData, + TestInitData, block_context, calculate_class_info_for_testing, create_test_init_data, + emit_n_events_tx, l1_resource_bounds, }; use crate::transaction::transaction_execution::Transaction; fn tx_executor_test_body( @@ -205,11 +205,10 @@ fn test_invoke( ) { let test_contract = FeatureContract::TestContract(cairo_version); let account_contract = FeatureContract::AccountWithoutValidations(cairo_version); - let state = test_state( - &block_context.chain_info, - BALANCE, - &[(test_contract, 1), (account_contract, 1)], - ); + let state = test_state(&block_context.chain_info, BALANCE, &[ + (test_contract, 1), + (account_contract, 1), + ]); let calldata = create_calldata(test_contract.get_instance_address(0), entry_point_name, &entry_point_args); diff --git a/crates/blockifier/src/bouncer.rs b/crates/blockifier/src/bouncer.rs index 86ed48ef87..97fe36949f 100644 --- a/crates/blockifier/src/bouncer.rs +++ b/crates/blockifier/src/bouncer.rs @@ -2,7 +2,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use cairo_vm::types::builtin_name::BuiltinName; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; -use papyrus_config::dumping::{append_sub_config_name, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use serde::{Deserialize, Serialize}; use starknet_api::core::ClassHash; diff --git a/crates/blockifier/src/bouncer_test.rs b/crates/blockifier/src/bouncer_test.rs index d00b1610ed..311baedf1f 100644 --- a/crates/blockifier/src/bouncer_test.rs +++ b/crates/blockifier/src/bouncer_test.rs @@ -11,7 +11,7 @@ use starknet_api::{class_hash, contract_address, storage_key}; use super::BouncerConfig; use crate::blockifier::transaction_executor::TransactionExecutorError; use crate::bouncer::{ - verify_tx_weights_within_max_capacity, Bouncer, BouncerWeights, BuiltinCount, + Bouncer, BouncerWeights, BuiltinCount, verify_tx_weights_within_max_capacity, }; use crate::context::BlockContext; use crate::execution::call_info::ExecutionSummary; diff --git a/crates/blockifier/src/concurrency/fee_utils_test.rs b/crates/blockifier/src/concurrency/fee_utils_test.rs index 26154ba4fb..2b6c87414f 100644 --- a/crates/blockifier/src/concurrency/fee_utils_test.rs +++ b/crates/blockifier/src/concurrency/fee_utils_test.rs @@ -12,7 +12,7 @@ use crate::fee::fee_utils::get_sequencer_balance_keys; use crate::state::state_api::StateReader; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::{fund_account, test_state, test_state_inner}; -use crate::test_utils::{create_trivial_calldata, CairoVersion, RunnableCairo1, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1, create_trivial_calldata}; use crate::transaction::test_utils::{ block_context, default_all_resource_bounds, invoke_tx_with_default_flags, }; diff --git a/crates/blockifier/src/concurrency/flow_test.rs b/crates/blockifier/src/concurrency/flow_test.rs index 5b828c3260..6724edb57d 100644 --- a/crates/blockifier/src/concurrency/flow_test.rs +++ b/crates/blockifier/src/concurrency/flow_test.rs @@ -1,13 +1,13 @@ use std::collections::HashMap; -use std::sync::atomic::Ordering; use std::sync::Arc; +use std::sync::atomic::Ordering; use rstest::rstest; use starknet_api::{contract_address, felt, storage_key}; use crate::abi::sierra_types::{SierraType, SierraU128}; use crate::concurrency::scheduler::{Scheduler, Task, TransactionStatus}; -use crate::concurrency::test_utils::{safe_versioned_state_for_testing, DEFAULT_CHUNK_SIZE}; +use crate::concurrency::test_utils::{DEFAULT_CHUNK_SIZE, safe_versioned_state_for_testing}; use crate::concurrency::versioned_state::ThreadSafeVersionedState; use crate::state::cached_state::{CachedState, ContractClassMapping, StateMaps}; use crate::state::state_api::UpdatableState; diff --git a/crates/blockifier/src/concurrency/scheduler.rs b/crates/blockifier/src/concurrency/scheduler.rs index b8301d2e59..21bd76da1d 100644 --- a/crates/blockifier/src/concurrency/scheduler.rs +++ b/crates/blockifier/src/concurrency/scheduler.rs @@ -2,8 +2,8 @@ use std::cmp::min; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Mutex, MutexGuard, TryLockError}; -use crate::concurrency::utils::lock_mutex_in_array; use crate::concurrency::TxIndex; +use crate::concurrency::utils::lock_mutex_in_array; #[cfg(test)] #[path = "scheduler_test.rs"] diff --git a/crates/blockifier/src/concurrency/scheduler_test.rs b/crates/blockifier/src/concurrency/scheduler_test.rs index 29499cba0c..981e8d99f2 100644 --- a/crates/blockifier/src/concurrency/scheduler_test.rs +++ b/crates/blockifier/src/concurrency/scheduler_test.rs @@ -1,13 +1,13 @@ use std::cmp::min; -use std::sync::atomic::Ordering; use std::sync::Arc; +use std::sync::atomic::Ordering; use pretty_assertions::assert_eq; use rstest::rstest; +use crate::concurrency::TxIndex; use crate::concurrency::scheduler::{Scheduler, Task, TransactionStatus}; use crate::concurrency::test_utils::DEFAULT_CHUNK_SIZE; -use crate::concurrency::TxIndex; use crate::default_scheduler; #[rstest] diff --git a/crates/blockifier/src/concurrency/versioned_state.rs b/crates/blockifier/src/concurrency/versioned_state.rs index 1d3c9a9270..d1d84f2b54 100644 --- a/crates/blockifier/src/concurrency/versioned_state.rs +++ b/crates/blockifier/src/concurrency/versioned_state.rs @@ -5,8 +5,8 @@ use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce}; use starknet_api::state::StorageKey; use starknet_types_core::felt::Felt; -use crate::concurrency::versioned_storage::VersionedStorage; use crate::concurrency::TxIndex; +use crate::concurrency::versioned_storage::VersionedStorage; use crate::execution::contract_class::RunnableCompiledClass; use crate::state::cached_state::{ContractClassMapping, StateMaps}; use crate::state::errors::StateError; diff --git a/crates/blockifier/src/concurrency/versioned_state_test.rs b/crates/blockifier/src/concurrency/versioned_state_test.rs index 7479478bee..dcb004f581 100644 --- a/crates/blockifier/src/concurrency/versioned_state_test.rs +++ b/crates/blockifier/src/concurrency/versioned_state_test.rs @@ -5,22 +5,22 @@ use std::thread; use assert_matches::assert_matches; use rstest::{fixture, rstest}; use starknet_api::abi::abi_utils::{get_fee_token_var_address, get_storage_var_address}; -use starknet_api::core::{calculate_contract_address, ClassHash, ContractAddress}; -use starknet_api::test_utils::deploy_account::executable_deploy_account_tx; +use starknet_api::core::{ClassHash, ContractAddress, calculate_contract_address}; use starknet_api::test_utils::NonceManager; +use starknet_api::test_utils::deploy_account::executable_deploy_account_tx; use starknet_api::transaction::fields::{ContractAddressSalt, ValidResourceBounds}; use starknet_api::{ calldata, class_hash, compiled_class_hash, contract_address, deploy_account_tx_args, felt, nonce, storage_key, }; +use crate::concurrency::TxIndex; use crate::concurrency::test_utils::{ class_hash, contract_address, safe_versioned_state_for_testing, }; use crate::concurrency::versioned_state::{ ThreadSafeVersionedState, VersionedState, VersionedStateProxy, }; -use crate::concurrency::TxIndex; use crate::context::BlockContext; use crate::state::cached_state::{ CachedState, ContractClassMapping, StateMaps, TransactionalState, @@ -30,7 +30,7 @@ use crate::state::state_api::{State, StateReader, UpdatableState}; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::dict_state_reader::DictStateReader; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{CairoVersion, RunnableCairo1, BALANCE, DEFAULT_STRK_L1_GAS_PRICE}; +use crate::test_utils::{BALANCE, CairoVersion, DEFAULT_STRK_L1_GAS_PRICE, RunnableCairo1}; use crate::transaction::account_transaction::AccountTransaction; use crate::transaction::objects::HasRelatedFeeType; use crate::transaction::test_utils::{default_all_resource_bounds, l1_resource_bounds}; @@ -91,11 +91,9 @@ fn test_versioned_state_proxy() { StateError::UndeclaredClassHash(class_hash) if another_class_hash == class_hash ); - assert!(!versioned_state_proxys[0] - .state() - .declared_contracts - .read(0, another_class_hash) - .unwrap()); + assert!( + !versioned_state_proxys[0].state().declared_contracts.read(0, another_class_hash).unwrap() + ); // Write to the state. let new_key = storage_key!(0x11_u8); @@ -165,16 +163,12 @@ fn test_versioned_state_proxy() { versioned_state_proxys[9].get_class_hash_at(contract_address).unwrap(), class_hash_v7 ); - assert!(!versioned_state_proxys[0] - .state() - .declared_contracts - .read(0, another_class_hash) - .unwrap()); - assert!(versioned_state_proxys[4] - .state() - .declared_contracts - .read(4, another_class_hash) - .unwrap()); + assert!( + !versioned_state_proxys[0].state().declared_contracts.read(0, another_class_hash).unwrap() + ); + assert!( + versioned_state_proxys[4].state().declared_contracts.read(4, another_class_hash).unwrap() + ); // Include the writes in the current transaction. assert_eq!( versioned_state_proxys[10].get_class_hash_at(contract_address).unwrap(), @@ -207,11 +201,11 @@ fn test_run_parallel_txs(default_all_resource_bounds: ValidResourceBounds) { FeatureContract::AccountWithoutValidations(CairoVersion::Cairo0); // Initiate States - let versioned_state = Arc::new(Mutex::new(VersionedState::new(test_state( - chain_info, - BALANCE, - &[(account_without_validation, 1), (grindy_account, 1)], - )))); + let versioned_state = + Arc::new(Mutex::new(VersionedState::new(test_state(chain_info, BALANCE, &[ + (account_without_validation, 1), + (grindy_account, 1), + ])))); let safe_versioned_state = ThreadSafeVersionedState(Arc::clone(&versioned_state)); let mut versioned_state_proxy_1 = safe_versioned_state.pin_version(1); @@ -324,9 +318,11 @@ fn test_validate_reads( assert_eq!(transactional_state.cache.borrow().initial_reads.declared_contracts.len(), 1); - assert!(safe_versioned_state - .pin_version(1) - .validate_reads(&transactional_state.cache.borrow().initial_reads)); + assert!( + safe_versioned_state + .pin_version(1) + .validate_reads(&transactional_state.cache.borrow().initial_reads) + ); } #[rstest] diff --git a/crates/blockifier/src/concurrency/versioned_storage_test.rs b/crates/blockifier/src/concurrency/versioned_storage_test.rs index 2f65fd71e3..693feca4c6 100644 --- a/crates/blockifier/src/concurrency/versioned_storage_test.rs +++ b/crates/blockifier/src/concurrency/versioned_storage_test.rs @@ -4,9 +4,9 @@ use pretty_assertions::assert_eq; use rstest::rstest; use starknet_api::core::{ClassHash, ContractAddress}; +use crate::concurrency::TxIndex; use crate::concurrency::test_utils::{class_hash, contract_address}; use crate::concurrency::versioned_storage::VersionedStorage; -use crate::concurrency::TxIndex; // TODO(barak, 01/07/2024): Split into test_read() and test_write(). #[test] diff --git a/crates/blockifier/src/concurrency/worker_logic.rs b/crates/blockifier/src/concurrency/worker_logic.rs index 851a462f31..8c53bf5028 100644 --- a/crates/blockifier/src/concurrency/worker_logic.rs +++ b/crates/blockifier/src/concurrency/worker_logic.rs @@ -9,11 +9,11 @@ use starknet_api::core::ClassHash; use super::versioned_state::VersionedState; use crate::blockifier::transaction_executor::TransactionExecutorError; use crate::bouncer::Bouncer; +use crate::concurrency::TxIndex; use crate::concurrency::fee_utils::complete_fee_transfer_flow; use crate::concurrency::scheduler::{Scheduler, Task}; use crate::concurrency::utils::lock_mutex_in_array; use crate::concurrency::versioned_state::ThreadSafeVersionedState; -use crate::concurrency::TxIndex; use crate::context::BlockContext; use crate::state::cached_state::{ContractClassMapping, StateMaps, TransactionalState}; use crate::state::state_api::{StateReader, UpdatableState}; diff --git a/crates/blockifier/src/concurrency/worker_logic_test.rs b/crates/blockifier/src/concurrency/worker_logic_test.rs index b5e067c5d8..8436653ddb 100644 --- a/crates/blockifier/src/concurrency/worker_logic_test.rs +++ b/crates/blockifier/src/concurrency/worker_logic_test.rs @@ -4,11 +4,11 @@ use std::sync::Mutex; use rstest::rstest; use starknet_api::abi::abi_utils::get_fee_token_var_address; use starknet_api::core::{ContractAddress, Nonce}; -use starknet_api::test_utils::declare::executable_declare_tx; use starknet_api::test_utils::NonceManager; +use starknet_api::test_utils::declare::executable_declare_tx; +use starknet_api::transaction::TransactionVersion; use starknet_api::transaction::constants::DEPLOY_CONTRACT_FUNCTION_ENTRY_POINT_NAME; use starknet_api::transaction::fields::{ContractAddressSalt, Fee, ValidResourceBounds}; -use starknet_api::transaction::TransactionVersion; use starknet_api::{contract_address, declare_tx_args, felt, invoke_tx_args, nonce, storage_key}; use starknet_types_core::felt::Felt; @@ -26,8 +26,8 @@ use crate::state::state_api::StateReader; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::{ - create_calldata, create_trivial_calldata, CairoVersion, RunnableCairo1, BALANCE, - TEST_ERC20_CONTRACT_ADDRESS2, + BALANCE, CairoVersion, RunnableCairo1, TEST_ERC20_CONTRACT_ADDRESS2, create_calldata, + create_trivial_calldata, }; use crate::transaction::account_transaction::AccountTransaction; use crate::transaction::objects::HasRelatedFeeType; diff --git a/crates/blockifier/src/context.rs b/crates/blockifier/src/context.rs index 007be96b31..952006fd87 100644 --- a/crates/blockifier/src/context.rs +++ b/crates/blockifier/src/context.rs @@ -1,6 +1,6 @@ use std::collections::BTreeMap; -use papyrus_config::dumping::{append_sub_config_name, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use serde::{Deserialize, Serialize}; use starknet_api::block::{BlockInfo, FeeType, GasPriceVector}; diff --git a/crates/blockifier/src/execution/contract_address_test.rs b/crates/blockifier/src/execution/contract_address_test.rs index 7c0959e817..e91ea84c00 100644 --- a/crates/blockifier/src/execution/contract_address_test.rs +++ b/crates/blockifier/src/execution/contract_address_test.rs @@ -1,6 +1,6 @@ use rstest::rstest; use starknet_api::abi::abi_utils::selector_from_name; -use starknet_api::core::{calculate_contract_address, ClassHash, ContractAddress}; +use starknet_api::core::{ClassHash, ContractAddress, calculate_contract_address}; use starknet_api::transaction::fields::{Calldata, ContractAddressSalt}; use starknet_api::{calldata, felt}; @@ -12,7 +12,7 @@ use crate::state::cached_state::CachedState; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::dict_state_reader::DictStateReader; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{CairoVersion, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion}; use crate::versioned_constants::VersionedConstants; #[rstest] diff --git a/crates/blockifier/src/execution/contract_class.rs b/crates/blockifier/src/execution/contract_class.rs index a70fdaf2f9..7516bbfa74 100644 --- a/crates/blockifier/src/execution/contract_class.rs +++ b/crates/blockifier/src/execution/contract_class.rs @@ -4,8 +4,8 @@ use std::sync::Arc; use cairo_lang_casm; use cairo_lang_casm::hints::Hint; -use cairo_lang_starknet_classes::casm_contract_class::{CasmContractClass, CasmContractEntryPoint}; use cairo_lang_starknet_classes::NestedIntList; +use cairo_lang_starknet_classes::casm_contract_class::{CasmContractClass, CasmContractEntryPoint}; use cairo_vm::serde::deserialize_program::{ ApTracking, FlowTrackingData, HintParams, ReferenceManager, }; @@ -182,7 +182,7 @@ impl CompiledClassV0 { + self.n_builtins() + self.bytecode_length() + 1; // Hinted class hash. - // The hashed data size is approximately the number of hashes (invoked in hash chains). + // The hashed data size is approximately the number of hashes (invoked in hash chains). let n_steps = constants::N_STEPS_PER_PEDERSEN * hashed_data_size; ExecutionResources { diff --git a/crates/blockifier/src/execution/deprecated_entry_point_execution.rs b/crates/blockifier/src/execution/deprecated_entry_point_execution.rs index d87e4e46e4..1c0a9f7d14 100644 --- a/crates/blockifier/src/execution/deprecated_entry_point_execution.rs +++ b/crates/blockifier/src/execution/deprecated_entry_point_execution.rs @@ -20,7 +20,7 @@ use crate::execution::entry_point::{ CallEntryPoint, EntryPointExecutionContext, EntryPointExecutionResult, }; use crate::execution::errors::{PostExecutionError, PreExecutionError}; -use crate::execution::execution_utils::{read_execution_retdata, Args, ReadOnlySegments}; +use crate::execution::execution_utils::{Args, ReadOnlySegments, read_execution_retdata}; use crate::state::state_api::State; pub struct VmExecutionContext<'a> { diff --git a/crates/blockifier/src/execution/deprecated_syscalls/deprecated_syscalls_test.rs b/crates/blockifier/src/execution/deprecated_syscalls/deprecated_syscalls_test.rs index 5d5e58a90c..0368264e03 100644 --- a/crates/blockifier/src/execution/deprecated_syscalls/deprecated_syscalls_test.rs +++ b/crates/blockifier/src/execution/deprecated_syscalls/deprecated_syscalls_test.rs @@ -5,11 +5,11 @@ use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use pretty_assertions::assert_eq; use rstest::rstest; use starknet_api::abi::abi_utils::selector_from_name; -use starknet_api::core::{calculate_contract_address, ChainId}; +use starknet_api::core::{ChainId, calculate_contract_address}; use starknet_api::state::StorageKey; use starknet_api::transaction::fields::{Calldata, ContractAddressSalt, Fee}; use starknet_api::transaction::{ - EventContent, EventData, EventKey, TransactionVersion, QUERY_VERSION_BASE, + EventContent, EventData, EventKey, QUERY_VERSION_BASE, TransactionVersion, }; use starknet_api::{calldata, felt, nonce, storage_key, tx_hash}; use starknet_types_core::felt::Felt; @@ -26,9 +26,9 @@ use crate::state::state_api::StateReader; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::{ + CURRENT_BLOCK_NUMBER, CURRENT_BLOCK_NUMBER_FOR_VALIDATE, CURRENT_BLOCK_TIMESTAMP, + CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE, CairoVersion, TEST_SEQUENCER_ADDRESS, calldata_for_deploy_test, get_syscall_resources, trivial_external_entry_point_new, - CairoVersion, CURRENT_BLOCK_NUMBER, CURRENT_BLOCK_NUMBER_FOR_VALIDATE, CURRENT_BLOCK_TIMESTAMP, - CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE, TEST_SEQUENCER_ADDRESS, }; use crate::transaction::objects::{ CommonAccountFields, DeprecatedTransactionInfo, TransactionInfo, @@ -334,11 +334,10 @@ fn test_deploy( ) { let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); let empty_contract = FeatureContract::Empty(CairoVersion::Cairo0); - let mut state = test_state( - &ChainInfo::create_for_testing(), - Fee(0), - &[(empty_contract, 0), (test_contract, 1)], - ); + let mut state = test_state(&ChainInfo::create_for_testing(), Fee(0), &[ + (empty_contract, 0), + (test_contract, 1), + ]); let class_hash = if constructor_exists { test_contract.get_class_hash() @@ -508,14 +507,11 @@ fn test_emit_event() { keys: keys.clone().into_iter().map(EventKey).collect(), data: EventData(data.clone()), }; - assert_eq!( - call_info.execution, - CallExecution { - events: vec![OrderedEvent { order: 0, event }], - gas_consumed: 0, // TODO why? - ..Default::default() - } - ); + assert_eq!(call_info.execution, CallExecution { + events: vec![OrderedEvent { order: 0, event }], + gas_consumed: 0, // TODO why? + ..Default::default() + }); // Negative flow, the data length exceeds the limit. let max_event_data_length = versioned_constants.tx_event_limits.max_data_length; diff --git a/crates/blockifier/src/execution/deprecated_syscalls/hint_processor.rs b/crates/blockifier/src/execution/deprecated_syscalls/hint_processor.rs index 02a0409e42..87a5d4f428 100644 --- a/crates/blockifier/src/execution/deprecated_syscalls/hint_processor.rs +++ b/crates/blockifier/src/execution/deprecated_syscalls/hint_processor.rs @@ -16,32 +16,31 @@ use cairo_vm::vm::errors::vm_errors::VirtualMachineError; use cairo_vm::vm::runners::cairo_runner::{ResourceTracker, RunResources}; use cairo_vm::vm::vm_core::VirtualMachine; use num_bigint::{BigUint, TryFromBigIntError}; +use starknet_api::StarknetApiError; use starknet_api::block::BlockInfo; use starknet_api::contract_class::EntryPointType; use starknet_api::core::{ClassHash, ContractAddress, EntryPointSelector}; use starknet_api::state::StorageKey; use starknet_api::transaction::fields::Calldata; -use starknet_api::StarknetApiError; use starknet_types_core::felt::{Felt, FromStrError}; use thiserror::Error; use crate::context::TransactionContext; use crate::execution::call_info::{CallInfo, OrderedEvent, OrderedL2ToL1Message}; use crate::execution::common_hints::{ - extended_builtin_hint_processor, ExecutionMode, HintExecutionResult, + ExecutionMode, HintExecutionResult, extended_builtin_hint_processor, }; use crate::execution::deprecated_syscalls::{ - call_contract, delegate_call, delegate_l1_handler, deploy, emit_event, get_block_number, - get_block_timestamp, get_caller_address, get_contract_address, get_sequencer_address, - get_tx_info, get_tx_signature, library_call, library_call_l1_handler, replace_class, - send_message_to_l1, storage_read, storage_write, DeprecatedSyscallResult, - DeprecatedSyscallSelector, StorageReadResponse, StorageWriteResponse, SyscallRequest, - SyscallResponse, + DeprecatedSyscallResult, DeprecatedSyscallSelector, StorageReadResponse, StorageWriteResponse, + SyscallRequest, SyscallResponse, call_contract, delegate_call, delegate_l1_handler, deploy, + emit_event, get_block_number, get_block_timestamp, get_caller_address, get_contract_address, + get_sequencer_address, get_tx_info, get_tx_signature, library_call, library_call_l1_handler, + replace_class, send_message_to_l1, storage_read, storage_write, }; use crate::execution::entry_point::{CallEntryPoint, CallType, EntryPointExecutionContext}; use crate::execution::errors::{ConstructorEntryPointExecutionError, EntryPointExecutionError}; use crate::execution::execution_utils::{ - felt_from_ptr, felt_range_from_ptr, ReadOnlySegment, ReadOnlySegments, + ReadOnlySegment, ReadOnlySegments, felt_from_ptr, felt_range_from_ptr, }; use crate::execution::hint_code; use crate::execution::syscalls::hint_processor::EmitEventError; diff --git a/crates/blockifier/src/execution/deprecated_syscalls/mod.rs b/crates/blockifier/src/execution/deprecated_syscalls/mod.rs index 4d3cf4c06a..793773f893 100644 --- a/crates/blockifier/src/execution/deprecated_syscalls/mod.rs +++ b/crates/blockifier/src/execution/deprecated_syscalls/mod.rs @@ -4,7 +4,7 @@ use serde::Deserialize; use starknet_api::block::{BlockNumber, BlockTimestamp}; use starknet_api::contract_class::EntryPointType; use starknet_api::core::{ - calculate_contract_address, ClassHash, ContractAddress, EntryPointSelector, EthAddress, + ClassHash, ContractAddress, EntryPointSelector, EthAddress, calculate_contract_address, }; use starknet_api::state::StorageKey; use starknet_api::transaction::fields::{Calldata, ContractAddressSalt}; @@ -13,15 +13,15 @@ use starknet_types_core::felt::Felt; use strum_macros::EnumIter; use self::hint_processor::{ - execute_inner_call, execute_library_call, felt_to_bool, read_call_params, read_calldata, - read_felt_array, DeprecatedSyscallExecutionError, DeprecatedSyscallHintProcessor, + DeprecatedSyscallExecutionError, DeprecatedSyscallHintProcessor, execute_inner_call, + execute_library_call, felt_to_bool, read_call_params, read_calldata, read_felt_array, }; use super::syscalls::exceeds_event_size_limit; use crate::execution::call_info::{MessageToL1, OrderedEvent, OrderedL2ToL1Message}; use crate::execution::common_hints::ExecutionMode; use crate::execution::entry_point::{CallEntryPoint, CallType, ConstructorContext}; use crate::execution::execution_utils::{ - execute_deployment, felt_from_ptr, write_felt, write_maybe_relocatable, ReadOnlySegment, + ReadOnlySegment, execute_deployment, felt_from_ptr, write_felt, write_maybe_relocatable, }; #[cfg(test)] diff --git a/crates/blockifier/src/execution/entry_point.rs b/crates/blockifier/src/execution/entry_point.rs index c7773ec403..8dbde307d5 100644 --- a/crates/blockifier/src/execution/entry_point.rs +++ b/crates/blockifier/src/execution/entry_point.rs @@ -11,10 +11,10 @@ use starknet_api::abi::constants::CONSTRUCTOR_ENTRY_POINT_NAME; use starknet_api::contract_class::EntryPointType; use starknet_api::core::{ClassHash, ContractAddress, EntryPointSelector}; use starknet_api::state::StorageKey; +use starknet_api::transaction::TransactionVersion; use starknet_api::transaction::fields::{ AllResourceBounds, Calldata, ResourceBounds, ValidResourceBounds, }; -use starknet_api::transaction::TransactionVersion; use starknet_types_core::felt::Felt; use crate::context::{BlockContext, TransactionContext}; @@ -25,7 +25,7 @@ use crate::execution::errors::{ ConstructorEntryPointExecutionError, EntryPointExecutionError, PreExecutionError, }; use crate::execution::execution_utils::execute_entry_point_call_wrapper; -use crate::execution::stack_trace::{extract_trailing_cairo1_revert_trace, Cairo1RevertHeader}; +use crate::execution::stack_trace::{Cairo1RevertHeader, extract_trailing_cairo1_revert_trace}; use crate::state::state_api::{State, StateResult}; use crate::transaction::objects::{HasRelatedFeeType, TransactionInfo}; use crate::transaction::transaction_types::TransactionType; diff --git a/crates/blockifier/src/execution/entry_point_execution.rs b/crates/blockifier/src/execution/entry_point_execution.rs index 57d118b4c6..b88e1f2d5f 100644 --- a/crates/blockifier/src/execution/entry_point_execution.rs +++ b/crates/blockifier/src/execution/entry_point_execution.rs @@ -20,8 +20,8 @@ use crate::execution::entry_point::{ }; use crate::execution::errors::{EntryPointExecutionError, PostExecutionError, PreExecutionError}; use crate::execution::execution_utils::{ - read_execution_retdata, write_felt, write_maybe_relocatable, Args, ReadOnlySegments, - SEGMENT_ARENA_BUILTIN_SIZE, + Args, ReadOnlySegments, SEGMENT_ARENA_BUILTIN_SIZE, read_execution_retdata, write_felt, + write_maybe_relocatable, }; use crate::execution::syscalls::hint_processor::SyscallHintProcessor; use crate::state::state_api::State; diff --git a/crates/blockifier/src/execution/entry_point_test.rs b/crates/blockifier/src/execution/entry_point_test.rs index 3983d7dbab..558b81967a 100644 --- a/crates/blockifier/src/execution/entry_point_test.rs +++ b/crates/blockifier/src/execution/entry_point_test.rs @@ -17,7 +17,7 @@ use crate::state::cached_state::CachedState; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::dict_state_reader::DictStateReader; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{trivial_external_entry_point_new, CairoVersion, RunnableCairo1, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1, trivial_external_entry_point_new}; use crate::versioned_constants::VersionedConstants; #[test] @@ -51,10 +51,9 @@ fn test_call_info_iteration() { for (i, call_info) in root.iter().enumerate() { // TODO(Ori, 1/2/2024): Write an indicative expect message explaining why the conversion // works. - assert_eq!( - call_info.call.calldata, - calldata![felt!(u64::try_from(i).expect("Failed to convert usize to u64."))] - ); + assert_eq!(call_info.call.calldata, calldata![felt!( + u64::try_from(i).expect("Failed to convert usize to u64.") + )]); } } diff --git a/crates/blockifier/src/execution/execution_utils.rs b/crates/blockifier/src/execution/execution_utils.rs index c3a05f8cfe..0025b3c22a 100644 --- a/crates/blockifier/src/execution/execution_utils.rs +++ b/crates/blockifier/src/execution/execution_utils.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use cairo_vm::serde::deserialize_program::{ - deserialize_array_of_bigint_hex, Attribute, HintParams, Identifier, ReferenceManager, + Attribute, HintParams, Identifier, ReferenceManager, deserialize_array_of_bigint_hex, }; use cairo_vm::types::builtin_name::BuiltinName; use cairo_vm::types::errors::program_errors::ProgramError; @@ -20,8 +20,8 @@ use starknet_types_core::felt::Felt; use crate::execution::call_info::{CallExecution, CallInfo, Retdata}; use crate::execution::contract_class::{RunnableCompiledClass, TrackedResource}; use crate::execution::entry_point::{ - execute_constructor_entry_point, CallEntryPoint, ConstructorContext, - ConstructorEntryPointExecutionResult, EntryPointExecutionContext, EntryPointExecutionResult, + CallEntryPoint, ConstructorContext, ConstructorEntryPointExecutionResult, + EntryPointExecutionContext, EntryPointExecutionResult, execute_constructor_entry_point, }; use crate::execution::errors::{ ConstructorEntryPointExecutionError, EntryPointExecutionError, PostExecutionError, @@ -29,7 +29,7 @@ use crate::execution::errors::{ }; #[cfg(feature = "cairo_native")] use crate::execution::native::entry_point_execution as native_entry_point_execution; -use crate::execution::stack_trace::{extract_trailing_cairo1_revert_trace, Cairo1RevertHeader}; +use crate::execution::stack_trace::{Cairo1RevertHeader, extract_trailing_cairo1_revert_trace}; use crate::execution::syscalls::hint_processor::ENTRYPOINT_NOT_FOUND_ERROR; use crate::execution::{deprecated_entry_point_execution, entry_point_execution}; use crate::state::errors::StateError; diff --git a/crates/blockifier/src/execution/native/syscall_handler.rs b/crates/blockifier/src/execution/native/syscall_handler.rs index b02d0348cd..e56c4e612f 100644 --- a/crates/blockifier/src/execution/native/syscall_handler.rs +++ b/crates/blockifier/src/execution/native/syscall_handler.rs @@ -22,7 +22,7 @@ use crate::execution::entry_point::{CallEntryPoint, CallType, EntryPointExecutio use crate::execution::errors::EntryPointExecutionError; use crate::execution::native::utils::{calculate_resource_bounds, default_tx_v2_info}; use crate::execution::secp; -use crate::execution::syscalls::hint_processor::{SyscallExecutionError, OUT_OF_GAS_ERROR}; +use crate::execution::syscalls::hint_processor::{OUT_OF_GAS_ERROR, SyscallExecutionError}; use crate::execution::syscalls::syscall_base::SyscallHandlerBase; use crate::state::state_api::State; use crate::transaction::objects::TransactionInfo; @@ -81,8 +81,10 @@ impl<'state> NativeSyscallHandler<'state> { if *remaining_gas < required_gas { // Out of gas failure. - return Err(vec![Felt::from_hex(OUT_OF_GAS_ERROR) - .expect("Failed to parse OUT_OF_GAS_ERROR hex string")]); + return Err(vec![ + Felt::from_hex(OUT_OF_GAS_ERROR) + .expect("Failed to parse OUT_OF_GAS_ERROR hex string"), + ]); } *remaining_gas -= required_gas; diff --git a/crates/blockifier/src/execution/secp.rs b/crates/blockifier/src/execution/secp.rs index d37d54f018..ab2c54fbd6 100644 --- a/crates/blockifier/src/execution/secp.rs +++ b/crates/blockifier/src/execution/secp.rs @@ -2,7 +2,7 @@ use ark_ec::short_weierstrass::{Affine, SWCurveConfig}; use ark_ff::{BigInteger, PrimeField, Zero}; use starknet_types_core::felt::Felt; -use super::syscalls::hint_processor::{SyscallExecutionError, INVALID_ARGUMENT}; +use super::syscalls::hint_processor::{INVALID_ARGUMENT, SyscallExecutionError}; pub fn get_point_from_x( x: num_bigint::BigUint, @@ -17,11 +17,7 @@ where let maybe_ec_point = Affine::::get_ys_from_x_unchecked(x) .map(|(smaller, greater)| { // Return the correct y coordinate based on the parity. - if smaller.into_bigint().is_odd() == y_parity { - smaller - } else { - greater - } + if smaller.into_bigint().is_odd() == y_parity { smaller } else { greater } }) .map(|y| Affine::::new_unchecked(x, y)) .filter(|p| p.is_in_correct_subgroup_assuming_on_curve()); diff --git a/crates/blockifier/src/execution/stack_trace.rs b/crates/blockifier/src/execution/stack_trace.rs index 1b90caad70..f67af2c0ac 100644 --- a/crates/blockifier/src/execution/stack_trace.rs +++ b/crates/blockifier/src/execution/stack_trace.rs @@ -13,7 +13,7 @@ use starknet_types_core::felt::Felt; use crate::execution::call_info::{CallInfo, Retdata}; use crate::execution::deprecated_syscalls::hint_processor::DeprecatedSyscallExecutionError; use crate::execution::errors::{ConstructorEntryPointExecutionError, EntryPointExecutionError}; -use crate::execution::syscalls::hint_processor::{SyscallExecutionError, ENTRYPOINT_FAILED_ERROR}; +use crate::execution::syscalls::hint_processor::{ENTRYPOINT_FAILED_ERROR, SyscallExecutionError}; use crate::transaction::errors::TransactionExecutionError; #[cfg(test)] @@ -135,16 +135,12 @@ pub enum ErrorStackHeader { impl Display for ErrorStackHeader { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!( - f, - "{}", - match self { - Self::Constructor => "Contract constructor execution has failed:\n", - Self::Execution => "Transaction execution has failed:\n", - Self::Validation => "Transaction validation has failed:\n", - Self::None => "", - } - ) + write!(f, "{}", match self { + Self::Constructor => "Contract constructor execution has failed:\n", + Self::Execution => "Transaction execution has failed:\n", + Self::Validation => "Transaction validation has failed:\n", + Self::None => "", + }) } } @@ -231,14 +227,10 @@ pub enum Cairo1RevertHeader { impl Display for Cairo1RevertHeader { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!( - f, - "{}", - match self { - Self::Execution => "Execution failed. Failure reason:", - Self::Validation => "The `validate` entry point panicked with:", - } - ) + write!(f, "{}", match self { + Self::Execution => "Execution failed. Failure reason:", + Self::Validation => "The `validate` entry point panicked with:", + }) } } diff --git a/crates/blockifier/src/execution/stack_trace_test.rs b/crates/blockifier/src/execution/stack_trace_test.rs index 5d400e46c0..7444d33eb3 100644 --- a/crates/blockifier/src/execution/stack_trace_test.rs +++ b/crates/blockifier/src/execution/stack_trace_test.rs @@ -5,9 +5,10 @@ use rstest::rstest; use starknet_api::abi::abi_utils::selector_from_name; use starknet_api::abi::constants::CONSTRUCTOR_ENTRY_POINT_NAME; use starknet_api::core::{ - calculate_contract_address, ClassHash, ContractAddress, EntryPointSelector, Nonce, + ClassHash, ContractAddress, EntryPointSelector, Nonce, calculate_contract_address, }; use starknet_api::executable_transaction::AccountTransaction as Transaction; +use starknet_api::transaction::TransactionVersion; use starknet_api::transaction::constants::{ DEPLOY_CONTRACT_FUNCTION_ENTRY_POINT_NAME, EXECUTE_ENTRY_POINT_NAME, FELT_TRUE, VALIDATE_DECLARE_ENTRY_POINT_NAME, VALIDATE_DEPLOY_ENTRY_POINT_NAME, VALIDATE_ENTRY_POINT_NAME, @@ -15,7 +16,6 @@ use starknet_api::transaction::constants::{ use starknet_api::transaction::fields::{ ContractAddressSalt, Fee, TransactionSignature, ValidResourceBounds, }; -use starknet_api::transaction::TransactionVersion; use starknet_api::{calldata, felt, invoke_tx_args}; use starknet_types_core::felt::Felt; @@ -24,17 +24,18 @@ use crate::execution::call_info::{CallExecution, CallInfo, Retdata}; use crate::execution::entry_point::CallEntryPoint; use crate::execution::errors::EntryPointExecutionError; use crate::execution::stack_trace::{ - extract_trailing_cairo1_revert_trace, Cairo1RevertHeader, Cairo1RevertSummary, - MIN_CAIRO1_FRAME_LENGTH, TRACE_LENGTH_CAP, + Cairo1RevertHeader, Cairo1RevertSummary, MIN_CAIRO1_FRAME_LENGTH, TRACE_LENGTH_CAP, + extract_trailing_cairo1_revert_trace, }; use crate::execution::syscalls::hint_processor::ENTRYPOINT_FAILED_ERROR; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::{fund_account, test_state}; -use crate::test_utils::{create_calldata, CairoVersion, RunnableCairo1, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1, create_calldata}; use crate::transaction::account_transaction::{AccountTransaction, ExecutionFlags}; use crate::transaction::test_utils::{ - block_context, create_account_tx_for_validate_test_nonce_0, default_all_resource_bounds, - invoke_tx_with_default_flags, run_invoke_tx, FaultyAccountTxCreatorArgs, INVALID, + FaultyAccountTxCreatorArgs, INVALID, block_context, + create_account_tx_for_validate_test_nonce_0, default_all_resource_bounds, + invoke_tx_with_default_flags, run_invoke_tx, }; use crate::transaction::transaction_types::TransactionType; use crate::transaction::transactions::ExecutableTransaction; @@ -67,15 +68,11 @@ fn test_stack_trace_with_inner_error_msg(block_context: BlockContext) { ], ); - let tx_execution_error = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - sender_address: account_address, - calldata, - version: TransactionVersion::ZERO, - }, - ) + let tx_execution_error = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + sender_address: account_address, + calldata, + version: TransactionVersion::ZERO, + }) .unwrap_err(); // Fetch PC locations from the compiled contract to compute the expected PC locations in the @@ -157,15 +154,11 @@ fn test_stack_trace( ], ); - let tx_execution_error = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - sender_address: account_address, - calldata, - version: TransactionVersion::ZERO, - }, - ) + let tx_execution_error = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + sender_address: account_address, + calldata, + version: TransactionVersion::ZERO, + }) .unwrap_err(); // Fetch PC locations from the compiled contract to compute the expected PC locations in the @@ -285,15 +278,11 @@ fn test_trace_callchain_ends_with_regular_call( ], ); - let tx_execution_error = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - sender_address: account_address, - calldata, - version: TransactionVersion::ZERO, - }, - ) + let tx_execution_error = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + sender_address: account_address, + calldata, + version: TransactionVersion::ZERO, + }) .unwrap_err(); let account_entry_point_offset = @@ -426,15 +415,11 @@ fn test_trace_call_chain_with_syscalls( &raw_calldata, ); - let tx_execution_error = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - sender_address: account_address, - calldata, - version: TransactionVersion::ZERO, - }, - ) + let tx_execution_error = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + sender_address: account_address, + calldata, + version: TransactionVersion::ZERO, + }) .unwrap_err(); let account_entry_point_offset = diff --git a/crates/blockifier/src/execution/syscalls/hint_processor.rs b/crates/blockifier/src/execution/syscalls/hint_processor.rs index 99b3bbca66..579386bf40 100644 --- a/crates/blockifier/src/execution/syscalls/hint_processor.rs +++ b/crates/blockifier/src/execution/syscalls/hint_processor.rs @@ -13,11 +13,11 @@ use cairo_vm::vm::errors::memory_errors::MemoryError; use cairo_vm::vm::errors::vm_errors::VirtualMachineError; use cairo_vm::vm::runners::cairo_runner::{ResourceTracker, RunResources}; use cairo_vm::vm::vm_core::VirtualMachine; +use starknet_api::StarknetApiError; use starknet_api::core::{ClassHash, ContractAddress, EntryPointSelector}; use starknet_api::transaction::fields::{ AllResourceBounds, Calldata, Resource, ValidResourceBounds, }; -use starknet_api::StarknetApiError; use starknet_types_core::felt::{Felt, FromStrError}; use thiserror::Error; @@ -26,19 +26,19 @@ use crate::execution::common_hints::{ExecutionMode, HintExecutionResult}; use crate::execution::entry_point::{CallEntryPoint, EntryPointExecutionContext}; use crate::execution::errors::{ConstructorEntryPointExecutionError, EntryPointExecutionError}; use crate::execution::execution_utils::{ - felt_from_ptr, felt_range_from_ptr, write_maybe_relocatable, ReadOnlySegment, ReadOnlySegments, + ReadOnlySegment, ReadOnlySegments, felt_from_ptr, felt_range_from_ptr, write_maybe_relocatable, }; use crate::execution::syscalls::secp::{ - secp256k1_add, secp256k1_get_point_from_x, secp256k1_get_xy, secp256k1_mul, secp256k1_new, - secp256r1_add, secp256r1_get_point_from_x, secp256r1_get_xy, secp256r1_mul, secp256r1_new, - SecpHintProcessor, + SecpHintProcessor, secp256k1_add, secp256k1_get_point_from_x, secp256k1_get_xy, secp256k1_mul, + secp256k1_new, secp256r1_add, secp256r1_get_point_from_x, secp256r1_get_xy, secp256r1_mul, + secp256r1_new, }; use crate::execution::syscalls::syscall_base::SyscallHandlerBase; use crate::execution::syscalls::{ - call_contract, deploy, emit_event, get_block_hash, get_class_hash_at, get_execution_info, - keccak, library_call, replace_class, send_message_to_l1, sha_256_process_block, storage_read, - storage_write, SyscallRequest, SyscallRequestWrapper, SyscallResponse, SyscallResponseWrapper, - SyscallResult, SyscallSelector, + SyscallRequest, SyscallRequestWrapper, SyscallResponse, SyscallResponseWrapper, SyscallResult, + SyscallSelector, call_contract, deploy, emit_event, get_block_hash, get_class_hash_at, + get_execution_info, keccak, library_call, replace_class, send_message_to_l1, + sha_256_process_block, storage_read, storage_write, }; use crate::state::errors::StateError; use crate::state::state_api::State; diff --git a/crates/blockifier/src/execution/syscalls/mod.rs b/crates/blockifier/src/execution/syscalls/mod.rs index 76d73531d5..ae022536e4 100644 --- a/crates/blockifier/src/execution/syscalls/mod.rs +++ b/crates/blockifier/src/execution/syscalls/mod.rs @@ -10,14 +10,15 @@ use starknet_api::transaction::{EventContent, EventData, EventKey, L2ToL1Payload use starknet_types_core::felt::Felt; use self::hint_processor::{ - create_retdata_segment, execute_inner_call, felt_to_bool, read_call_params, read_calldata, - read_felt_array, write_segment, EmitEventError, SyscallExecutionError, SyscallHintProcessor, + EmitEventError, SyscallExecutionError, SyscallHintProcessor, create_retdata_segment, + execute_inner_call, felt_to_bool, read_call_params, read_calldata, read_felt_array, + write_segment, }; use crate::execution::call_info::MessageToL1; use crate::execution::deprecated_syscalls::DeprecatedSyscallSelector; use crate::execution::entry_point::{CallEntryPoint, CallType}; use crate::execution::execution_utils::{ - felt_from_ptr, write_felt, write_maybe_relocatable, ReadOnlySegment, + ReadOnlySegment, felt_from_ptr, write_felt, write_maybe_relocatable, }; use crate::execution::syscalls::syscall_base::SyscallResult; use crate::versioned_constants::{EventLimits, VersionedConstants}; diff --git a/crates/blockifier/src/execution/syscalls/secp.rs b/crates/blockifier/src/execution/syscalls/secp.rs index f42c2033f9..5b8ed20f3d 100644 --- a/crates/blockifier/src/execution/syscalls/secp.rs +++ b/crates/blockifier/src/execution/syscalls/secp.rs @@ -9,7 +9,7 @@ use starknet_types_core::felt::Felt; use crate::abi::sierra_types::{SierraType, SierraU256}; use crate::execution::execution_utils::{felt_from_ptr, write_maybe_relocatable, write_u256}; use crate::execution::secp::new_affine; -use crate::execution::syscalls::hint_processor::{felt_to_bool, SyscallHintProcessor}; +use crate::execution::syscalls::hint_processor::{SyscallHintProcessor, felt_to_bool}; use crate::execution::syscalls::{ SyscallExecutionError, SyscallRequest, SyscallResponse, SyscallResult, WriteResponseResult, }; diff --git a/crates/blockifier/src/execution/syscalls/syscall_base.rs b/crates/blockifier/src/execution/syscalls/syscall_base.rs index 14c021beb3..6b09cb5869 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_base.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_base.rs @@ -1,11 +1,11 @@ /// This file is for sharing common logic between Native and VM syscall implementations. -use std::collections::{hash_map, HashMap, HashSet}; +use std::collections::{HashMap, HashSet, hash_map}; use std::convert::From; -use starknet_api::core::{calculate_contract_address, ClassHash, ContractAddress}; +use starknet_api::core::{ClassHash, ContractAddress, calculate_contract_address}; use starknet_api::state::StorageKey; -use starknet_api::transaction::fields::{Calldata, ContractAddressSalt}; use starknet_api::transaction::EventContent; +use starknet_api::transaction::fields::{Calldata, ContractAddressSalt}; use starknet_types_core::felt::Felt; use super::exceeds_event_size_limit; @@ -17,8 +17,8 @@ use crate::execution::entry_point::{ }; use crate::execution::execution_utils::execute_deployment; use crate::execution::syscalls::hint_processor::{ - SyscallExecutionError, BLOCK_NUMBER_OUT_OF_RANGE_ERROR, ENTRYPOINT_FAILED_ERROR, - INVALID_INPUT_LENGTH_ERROR, OUT_OF_GAS_ERROR, + BLOCK_NUMBER_OUT_OF_RANGE_ERROR, ENTRYPOINT_FAILED_ERROR, INVALID_INPUT_LENGTH_ERROR, + OUT_OF_GAS_ERROR, SyscallExecutionError, }; use crate::state::state_api::State; use crate::transaction::account_transaction::is_cairo1; @@ -264,8 +264,10 @@ impl<'state> SyscallHandlerBase<'state> { if remainder != 0 { return Err(SyscallExecutionError::SyscallError { - error_data: vec![Felt::from_hex(INVALID_INPUT_LENGTH_ERROR) - .expect("Failed to parse INVALID_INPUT_LENGTH_ERROR hex string")], + error_data: vec![ + Felt::from_hex(INVALID_INPUT_LENGTH_ERROR) + .expect("Failed to parse INVALID_INPUT_LENGTH_ERROR hex string"), + ], }); } // TODO(Ori, 1/2/2024): Write an indicative expect message explaining why the conversion diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/call_contract.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/call_contract.rs index c8fce38c7b..ba750f38d6 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/call_contract.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/call_contract.rs @@ -20,8 +20,8 @@ use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::syscall::build_recurse_calldata; use crate::test_utils::{ - create_calldata, trivial_external_entry_point_new, CairoVersion, CompilerBasedVersion, - RunnableCairo1, BALANCE, + BALANCE, CairoVersion, CompilerBasedVersion, RunnableCairo1, create_calldata, + trivial_external_entry_point_new, }; #[cfg_attr(feature = "cairo_native", test_case(RunnableCairo1::Native; "Native"))] @@ -84,28 +84,22 @@ fn test_call_contract(outer_contract: FeatureContract, inner_contract: FeatureCo let mut state = test_state(chain_info, BALANCE, &[(outer_contract, 1), (inner_contract, 1)]); let outer_entry_point_selector = selector_from_name("test_call_contract"); - let calldata = create_calldata( - inner_contract.get_instance_address(0), - "test_storage_read_write", - &[ + let calldata = + create_calldata(inner_contract.get_instance_address(0), "test_storage_read_write", &[ felt!(405_u16), // Calldata: storage address. felt!(48_u8), // Calldata: value. - ], - ); + ]); let entry_point_call = CallEntryPoint { entry_point_selector: outer_entry_point_selector, calldata, ..trivial_external_entry_point_new(outer_contract) }; - assert_eq!( - entry_point_call.execute_directly(&mut state).unwrap().execution, - CallExecution { - retdata: retdata![felt!(48_u8)], - gas_consumed: REQUIRED_GAS_CALL_CONTRACT_TEST, - ..CallExecution::default() - } - ); + assert_eq!(entry_point_call.execute_directly(&mut state).unwrap().execution, CallExecution { + retdata: retdata![felt!(48_u8)], + gas_consumed: REQUIRED_GAS_CALL_CONTRACT_TEST, + ..CallExecution::default() + }); } /// Cairo0 / Old Cairo1 / Cairo1 / Native calls to Cairo0 / Old Cairo1 / Cairo1 / Native. diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/deploy.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/deploy.rs index 3eba4267e9..52d61a3f16 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/deploy.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/deploy.rs @@ -13,7 +13,7 @@ use crate::state::state_api::StateReader; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::{ - calldata_for_deploy_test, trivial_external_entry_point_new, CairoVersion, RunnableCairo1, + CairoVersion, RunnableCairo1, calldata_for_deploy_test, trivial_external_entry_point_new, }; #[test_case(RunnableCairo1::Casm;"VM")] @@ -24,11 +24,10 @@ fn no_constructor(runnable_version: RunnableCairo1) { let empty_contract = FeatureContract::Empty(CairoVersion::Cairo1(runnable_version)); let class_hash = empty_contract.get_class_hash(); - let mut state = test_state( - &ChainInfo::create_for_testing(), - Fee(0), - &[(deployer_contract, 1), (empty_contract, 0)], - ); + let mut state = test_state(&ChainInfo::create_for_testing(), Fee(0), &[ + (deployer_contract, 1), + (empty_contract, 0), + ]); let calldata = calldata_for_deploy_test(class_hash, &[], true); let entry_point_call = CallEntryPoint { @@ -38,10 +37,11 @@ fn no_constructor(runnable_version: RunnableCairo1) { }; let deploy_call = &entry_point_call.execute_directly(&mut state).unwrap(); - assert_eq!( - deploy_call.execution, - CallExecution { retdata: retdata![], gas_consumed: 155200, ..CallExecution::default() } - ); + assert_eq!(deploy_call.execution, CallExecution { + retdata: retdata![], + gas_consumed: 155200, + ..CallExecution::default() + }); let deployed_contract_address = calculate_contract_address( ContractAddressSalt::default(), @@ -54,10 +54,11 @@ fn no_constructor(runnable_version: RunnableCairo1) { let constructor_call = &deploy_call.inner_calls[0]; assert_eq!(constructor_call.call.storage_address, deployed_contract_address); - assert_eq!( - constructor_call.execution, - CallExecution { retdata: retdata![], gas_consumed: 0, ..CallExecution::default() } - ); + assert_eq!(constructor_call.execution, CallExecution { + retdata: retdata![], + gas_consumed: 0, + ..CallExecution::default() + }); assert_eq!(state.get_class_hash_at(deployed_contract_address).unwrap(), class_hash); } @@ -68,11 +69,10 @@ fn no_constructor_nonempty_calldata(runnable_version: RunnableCairo1) { let empty_contract = FeatureContract::Empty(CairoVersion::Cairo1(runnable_version)); let class_hash = empty_contract.get_class_hash(); - let mut state = test_state( - &ChainInfo::create_for_testing(), - Fee(0), - &[(deployer_contract, 1), (empty_contract, 0)], - ); + let mut state = test_state(&ChainInfo::create_for_testing(), Fee(0), &[ + (deployer_contract, 1), + (empty_contract, 0), + ]); let calldata = calldata_for_deploy_test(class_hash, &[felt!(1_u8), felt!(1_u8)], true); @@ -119,24 +119,22 @@ fn with_constructor(runnable_version: RunnableCairo1) { .unwrap(); let deploy_call = &entry_point_call.execute_directly(&mut state).unwrap(); - assert_eq!( - deploy_call.execution, - CallExecution { retdata: retdata![], gas_consumed: 164550, ..CallExecution::default() } - ); + assert_eq!(deploy_call.execution, CallExecution { + retdata: retdata![], + gas_consumed: 164550, + ..CallExecution::default() + }); let constructor_call = &deploy_call.inner_calls[0]; assert_eq!(constructor_call.call.storage_address, contract_address); - assert_eq!( - constructor_call.execution, - CallExecution { - // The test contract constructor returns its first argument. - retdata: retdata![constructor_calldata[0]], - // This reflects the gas cost of storage write syscall. - gas_consumed: 4610, - ..CallExecution::default() - } - ); + assert_eq!(constructor_call.execution, CallExecution { + // The test contract constructor returns its first argument. + retdata: retdata![constructor_calldata[0]], + // This reflects the gas cost of storage write syscall. + gas_consumed: 4610, + ..CallExecution::default() + }); assert_eq!(state.get_class_hash_at(contract_address).unwrap(), class_hash); } diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/emit_event.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/emit_event.rs index f45e9aa257..54c524658d 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/emit_event.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/emit_event.rs @@ -15,7 +15,7 @@ use crate::execution::errors::EntryPointExecutionError; use crate::execution::syscalls::hint_processor::EmitEventError; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{trivial_external_entry_point_new, CairoVersion, RunnableCairo1, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1, trivial_external_entry_point_new}; use crate::versioned_constants::VersionedConstants; const KEYS: [Felt; 2] = [Felt::from_hex_unchecked("0x2019"), Felt::from_hex_unchecked("0x2020")]; @@ -37,14 +37,11 @@ fn positive_flow(runnable_version: RunnableCairo1) { data: EventData(DATA.to_vec()), }; - assert_eq!( - call_info.execution, - CallExecution { - events: vec![OrderedEvent { order: 0, event }], - gas_consumed: 47330, - ..Default::default() - } - ); + assert_eq!(call_info.execution, CallExecution { + events: vec![OrderedEvent { order: 0, event }], + gas_consumed: 47330, + ..Default::default() + }); } #[cfg_attr(feature = "cairo_native", test_case(RunnableCairo1::Native;"Native"))] diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/failure_format.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/failure_format.rs index 022555e141..0e8aa4fe12 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/failure_format.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/failure_format.rs @@ -3,7 +3,7 @@ use starknet_api::felt; use crate::execution::call_info::{CallExecution, CallInfo, Retdata}; use crate::execution::errors::EntryPointExecutionError; -use crate::execution::stack_trace::{extract_trailing_cairo1_revert_trace, Cairo1RevertHeader}; +use crate::execution::stack_trace::{Cairo1RevertHeader, extract_trailing_cairo1_revert_trace}; #[test] fn test_syscall_failure_format() { diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/get_block_hash.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/get_block_hash.rs index 2265d7148a..f05e324539 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/get_block_hash.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/get_block_hash.rs @@ -16,7 +16,7 @@ use crate::test_utils::contracts::FeatureContract; use crate::test_utils::dict_state_reader::DictStateReader; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::{ - trivial_external_entry_point_new, CairoVersion, RunnableCairo1, BALANCE, CURRENT_BLOCK_NUMBER, + BALANCE, CURRENT_BLOCK_NUMBER, CairoVersion, RunnableCairo1, trivial_external_entry_point_new, }; use crate::versioned_constants::VersionedConstants; use crate::{check_entry_point_execution_error_for_custom_hint, retdata}; @@ -77,9 +77,11 @@ fn negative_flow_execution_mode_validate(runnable_version: RunnableCairo1) { test_contract, FeatureContract::TestContract(CairoVersion::Cairo1(RunnableCairo1::Native)) ) { - assert!(error - .to_string() - .contains("Unauthorized syscall get_block_hash in execution mode Validate.")); + assert!( + error + .to_string() + .contains("Unauthorized syscall get_block_hash in execution mode Validate.") + ); } else { check_entry_point_execution_error_for_custom_hint!( &error, diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/get_class_hash_at.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/get_class_hash_at.rs index 11322694a9..029b8582c3 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/get_class_hash_at.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/get_class_hash_at.rs @@ -9,7 +9,7 @@ use crate::execution::syscalls::syscall_tests::constants::REQUIRED_GAS_GET_CLASS use crate::retdata; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{trivial_external_entry_point_new, CairoVersion, RunnableCairo1, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1, trivial_external_entry_point_new}; /// Tests the `get_class_hash_at` syscall, ensuring that: /// 1. `accessed_contract_addresses` contains `address` for a valid entry. @@ -36,15 +36,12 @@ fn test_get_class_hash_at(runnable_version: RunnableCairo1) { let positive_call_info = positive_entry_point_call.execute_directly(&mut state).unwrap(); assert!(positive_call_info.accessed_contract_addresses.contains(&address)); assert!(positive_call_info.read_class_hash_values[0] == class_hash); - assert_eq!( - positive_call_info.execution, - CallExecution { - retdata: retdata!(), - gas_consumed: REQUIRED_GAS_GET_CLASS_HASH_AT_TEST, - failed: false, - ..CallExecution::default() - } - ); + assert_eq!(positive_call_info.execution, CallExecution { + retdata: retdata!(), + gas_consumed: REQUIRED_GAS_GET_CLASS_HASH_AT_TEST, + failed: false, + ..CallExecution::default() + }); // Test undeployed contract - should return class_hash = 0 and succeed. let non_existing_address = felt!("0x333"); let class_hash_of_undeployed_contract = felt!("0x0"); diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/get_execution_info.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/get_execution_info.rs index 5cd981b518..1eead9e1c4 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/get_execution_info.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/get_execution_info.rs @@ -7,7 +7,7 @@ use starknet_api::transaction::fields::{ AccountDeploymentData, Calldata, Fee, PaymasterData, Resource, ResourceBounds, Tip, ValidResourceBounds, }; -use starknet_api::transaction::{TransactionVersion, QUERY_VERSION_BASE}; +use starknet_api::transaction::{QUERY_VERSION_BASE, TransactionVersion}; use starknet_api::{felt, nonce, tx_hash}; use starknet_types_core::felt::Felt; use test_case::test_case; @@ -18,9 +18,9 @@ use crate::execution::entry_point::CallEntryPoint; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::{ - trivial_external_entry_point_with_address, CairoVersion, RunnableCairo1, BALANCE, - CURRENT_BLOCK_NUMBER, CURRENT_BLOCK_NUMBER_FOR_VALIDATE, CURRENT_BLOCK_TIMESTAMP, - CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE, TEST_SEQUENCER_ADDRESS, + BALANCE, CURRENT_BLOCK_NUMBER, CURRENT_BLOCK_NUMBER_FOR_VALIDATE, CURRENT_BLOCK_TIMESTAMP, + CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE, CairoVersion, RunnableCairo1, TEST_SEQUENCER_ADDRESS, + trivial_external_entry_point_with_address, }; use crate::transaction::objects::{ CommonAccountFields, CurrentTransactionInfo, DeprecatedTransactionInfo, TransactionInfo, diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/keccak.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/keccak.rs index f69db51517..035e049236 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/keccak.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/keccak.rs @@ -8,7 +8,7 @@ use crate::execution::entry_point::CallEntryPoint; use crate::retdata; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{trivial_external_entry_point_new, CairoVersion, RunnableCairo1, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1, trivial_external_entry_point_new}; #[test_case(RunnableCairo1::Casm; "VM")] #[cfg_attr(feature = "cairo_native", test_case(RunnableCairo1::Native; "Native"))] diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/library_call.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/library_call.rs index e73da1deb5..ca8afe7c80 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/library_call.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/library_call.rs @@ -11,15 +11,15 @@ use test_case::test_case; use crate::context::ChainInfo; use crate::execution::call_info::{CallExecution, CallInfo, ChargedResources, Retdata}; use crate::execution::entry_point::{CallEntryPoint, CallType}; +use crate::execution::syscalls::SyscallSelector; use crate::execution::syscalls::syscall_tests::constants::{ REQUIRED_GAS_LIBRARY_CALL_TEST, REQUIRED_GAS_STORAGE_READ_WRITE_TEST, }; -use crate::execution::syscalls::SyscallSelector; use crate::retdata; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::{ - get_syscall_resources, trivial_external_entry_point_new, CairoVersion, RunnableCairo1, BALANCE, + BALANCE, CairoVersion, RunnableCairo1, get_syscall_resources, trivial_external_entry_point_new, }; use crate::versioned_constants::VersionedConstants; @@ -46,14 +46,11 @@ fn test_library_call(runnable_version: RunnableCairo1) { ..trivial_external_entry_point_new(test_contract) }; - assert_eq!( - entry_point_call.execute_directly(&mut state).unwrap().execution, - CallExecution { - retdata: retdata![felt!(91_u16)], - gas_consumed: REQUIRED_GAS_LIBRARY_CALL_TEST, - ..Default::default() - } - ); + assert_eq!(entry_point_call.execute_directly(&mut state).unwrap().execution, CallExecution { + retdata: retdata![felt!(91_u16)], + gas_consumed: REQUIRED_GAS_LIBRARY_CALL_TEST, + ..Default::default() + }); } #[cfg_attr(feature = "cairo_native", test_case(RunnableCairo1::Native; "Native"))] @@ -79,20 +76,17 @@ fn test_library_call_assert_fails(runnable_version: RunnableCairo1) { }; let call_info = entry_point_call.execute_directly(&mut state).unwrap(); - assert_eq!( - call_info.execution, - CallExecution { - retdata: Retdata(vec![ - // 'x != y'. - felt!("0x7820213d2079"), - // 'ENTRYPOINT_FAILED'. - felt!("0x454e545259504f494e545f4641494c4544") - ]), - gas_consumed: 100980, - failed: true, - ..Default::default() - } - ); + assert_eq!(call_info.execution, CallExecution { + retdata: Retdata(vec![ + // 'x != y'. + felt!("0x7820213d2079"), + // 'ENTRYPOINT_FAILED'. + felt!("0x454e545259504f494e545f4641494c4544") + ]), + gas_consumed: 100980, + failed: true, + ..Default::default() + }); } #[cfg_attr(feature = "cairo_native", test_case(RunnableCairo1::Native; "Native"))] diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/out_of_gas.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/out_of_gas.rs index f61213fe16..c6511e3f12 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/out_of_gas.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/out_of_gas.rs @@ -11,7 +11,7 @@ use crate::execution::syscalls::syscall_tests::constants::REQUIRED_GAS_STORAGE_R use crate::retdata; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{trivial_external_entry_point_new, CairoVersion, RunnableCairo1, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1, trivial_external_entry_point_new}; #[cfg_attr(feature = "cairo_native", test_case(RunnableCairo1::Native; "Native"))] #[test_case(RunnableCairo1::Casm; "VM")] @@ -29,16 +29,13 @@ fn test_out_of_gas(runnable_version: RunnableCairo1) { ..trivial_external_entry_point_new(test_contract) }; let call_info = entry_point_call.execute_directly(&mut state).unwrap(); - assert_eq!( - call_info.execution, - CallExecution { - // 'Out of gas' - retdata: retdata![felt!["0x4f7574206f6620676173"]], - gas_consumed: REQUIRED_GAS_STORAGE_READ_WRITE_TEST - 70, - failed: true, - ..Default::default() - } - ); + assert_eq!(call_info.execution, CallExecution { + // 'Out of gas' + retdata: retdata![felt!["0x4f7574206f6620676173"]], + gas_consumed: REQUIRED_GAS_STORAGE_READ_WRITE_TEST - 70, + failed: true, + ..Default::default() + }); } #[cfg(feature = "cairo_native")] @@ -62,14 +59,11 @@ fn test_stack_overflow() { ..trivial_external_entry_point_new(test_contract) }; let call_info = entry_point_call.execute_directly(&mut state).unwrap(); - assert_eq!( - call_info.execution, - CallExecution { - // 'Out of gas' - retdata: retdata![felt!["0x4f7574206f6620676173"]], - gas_consumed: MAX_POSSIBLE_SIERRA_GAS - 6590, - failed: true, - ..Default::default() - } - ); + assert_eq!(call_info.execution, CallExecution { + // 'Out of gas' + retdata: retdata![felt!["0x4f7574206f6620676173"]], + gas_consumed: MAX_POSSIBLE_SIERRA_GAS - 6590, + failed: true, + ..Default::default() + }); } diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/replace_class.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/replace_class.rs index b0932025f9..a6cab5e248 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/replace_class.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/replace_class.rs @@ -9,7 +9,7 @@ use crate::execution::entry_point::CallEntryPoint; use crate::state::state_api::StateReader; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{trivial_external_entry_point_new, CairoVersion, RunnableCairo1, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1, trivial_external_entry_point_new}; #[cfg_attr(feature = "cairo_native", test_case(RunnableCairo1::Native; "Native"))] #[test_case(RunnableCairo1::Casm; "VM")] @@ -32,11 +32,10 @@ fn undeclared_class_hash(runnable_version: RunnableCairo1) { fn cairo0_class_hash(runnable_version: RunnableCairo1) { let test_contract = FeatureContract::TestContract(CairoVersion::Cairo1(runnable_version)); let empty_contract_cairo0 = FeatureContract::Empty(CairoVersion::Cairo0); - let mut state = test_state( - &ChainInfo::create_for_testing(), - BALANCE, - &[(test_contract, 1), (empty_contract_cairo0, 0)], - ); + let mut state = test_state(&ChainInfo::create_for_testing(), BALANCE, &[ + (test_contract, 1), + (empty_contract_cairo0, 0), + ]); // Replace with Cairo 0 class hash. let v0_class_hash = empty_contract_cairo0.get_class_hash(); @@ -57,11 +56,11 @@ fn positive_flow(runnable_version: RunnableCairo1) { let test_contract = FeatureContract::TestContract(CairoVersion::Cairo1(runnable_version)); let empty_contract = FeatureContract::Empty(CairoVersion::Cairo1(runnable_version)); let empty_contract_cairo0 = FeatureContract::Empty(CairoVersion::Cairo0); - let mut state = test_state( - &ChainInfo::create_for_testing(), - BALANCE, - &[(test_contract, 1), (empty_contract, 0), (empty_contract_cairo0, 0)], - ); + let mut state = test_state(&ChainInfo::create_for_testing(), BALANCE, &[ + (test_contract, 1), + (empty_contract, 0), + (empty_contract_cairo0, 0), + ]); let contract_address = test_contract.get_instance_address(0); let old_class_hash = test_contract.get_class_hash(); @@ -72,9 +71,9 @@ fn positive_flow(runnable_version: RunnableCairo1) { entry_point_selector: selector_from_name("test_replace_class"), ..trivial_external_entry_point_new(test_contract) }; - assert_eq!( - entry_point_call.execute_directly(&mut state).unwrap().execution, - CallExecution { gas_consumed: 5220, ..Default::default() } - ); + assert_eq!(entry_point_call.execute_directly(&mut state).unwrap().execution, CallExecution { + gas_consumed: 5220, + ..Default::default() + }); assert_eq!(state.get_class_hash_at(contract_address).unwrap(), new_class_hash); } diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/secp.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/secp.rs index 4cad09570d..199a65e624 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/secp.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/secp.rs @@ -7,7 +7,7 @@ use crate::execution::call_info::CallExecution; use crate::execution::entry_point::CallEntryPoint; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{trivial_external_entry_point_new, CairoVersion, RunnableCairo1, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1, trivial_external_entry_point_new}; #[cfg_attr(feature = "cairo_native", test_case(RunnableCairo1::Native; "Native"))] #[test_case(RunnableCairo1::Casm; "VM")] diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/send_message_to_l1.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/send_message_to_l1.rs index c0569e2bd6..3456d0d388 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/send_message_to_l1.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/send_message_to_l1.rs @@ -2,8 +2,8 @@ use itertools::concat; use starknet_api::abi::abi_utils::selector_from_name; use starknet_api::core::EthAddress; use starknet_api::felt; -use starknet_api::transaction::fields::Calldata; use starknet_api::transaction::L2ToL1Payload; +use starknet_api::transaction::fields::Calldata; use test_case::test_case; use crate::context::ChainInfo; @@ -11,7 +11,7 @@ use crate::execution::call_info::{CallExecution, MessageToL1, OrderedL2ToL1Messa use crate::execution::entry_point::CallEntryPoint; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{trivial_external_entry_point_new, CairoVersion, RunnableCairo1, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1, trivial_external_entry_point_new}; #[cfg_attr(feature = "cairo_native", test_case(RunnableCairo1::Native; "Native"))] #[test_case(RunnableCairo1::Casm; "VM")] diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/sha256.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/sha256.rs index bf9b9cd36f..f058029c94 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/sha256.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/sha256.rs @@ -8,7 +8,7 @@ use crate::execution::entry_point::CallEntryPoint; use crate::retdata; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{trivial_external_entry_point_new, CairoVersion, RunnableCairo1, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1, trivial_external_entry_point_new}; #[cfg_attr(feature = "cairo_native", test_case(RunnableCairo1::Native; "Native"))] #[test_case(RunnableCairo1::Casm; "VM")] diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/storage_read_write.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/storage_read_write.rs index cfc09de5f3..972b70590c 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/storage_read_write.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/storage_read_write.rs @@ -11,7 +11,7 @@ use crate::retdata; use crate::state::state_api::StateReader; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{trivial_external_entry_point_new, CairoVersion, RunnableCairo1, BALANCE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1, trivial_external_entry_point_new}; #[cfg_attr(feature = "cairo_native", test_case(RunnableCairo1::Native; "Native"))] #[test_case(RunnableCairo1::Casm; "VM")] @@ -29,14 +29,11 @@ fn test_storage_read_write(runnable_version: RunnableCairo1) { ..trivial_external_entry_point_new(test_contract) }; let storage_address = entry_point_call.storage_address; - assert_eq!( - entry_point_call.execute_directly(&mut state).unwrap().execution, - CallExecution { - retdata: retdata![value], - gas_consumed: REQUIRED_GAS_STORAGE_READ_WRITE_TEST, - ..CallExecution::default() - } - ); + assert_eq!(entry_point_call.execute_directly(&mut state).unwrap().execution, CallExecution { + retdata: retdata![value], + gas_consumed: REQUIRED_GAS_STORAGE_READ_WRITE_TEST, + ..CallExecution::default() + }); // Verify that the state has changed. let value_from_state = diff --git a/crates/blockifier/src/fee/fee_checks.rs b/crates/blockifier/src/fee/fee_checks.rs index 830fc97530..64954bd5e7 100644 --- a/crates/blockifier/src/fee/fee_checks.rs +++ b/crates/blockifier/src/fee/fee_checks.rs @@ -17,9 +17,7 @@ use crate::transaction::objects::{TransactionExecutionResult, TransactionInfo}; #[cfg_attr(feature = "transaction_serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Error, PartialEq)] pub enum FeeCheckError { - #[error( - "Insufficient max {resource}: max amount: {max_amount}, actual used: {actual_amount}." - )] + #[error("Insufficient max {resource}: max amount: {max_amount}, actual used: {actual_amount}.")] MaxGasAmountExceeded { resource: Resource, max_amount: GasAmount, actual_amount: GasAmount }, #[error("Insufficient max fee: max fee: {}, actual fee: {}.", max_fee.0, actual_fee.0)] MaxFeeExceeded { max_fee: Fee, actual_fee: Fee }, diff --git a/crates/blockifier/src/fee/fee_test.rs b/crates/blockifier/src/fee/fee_test.rs index c57d274ea9..bd251068a4 100644 --- a/crates/blockifier/src/fee/fee_test.rs +++ b/crates/blockifier/src/fee/fee_test.rs @@ -16,9 +16,9 @@ use crate::fee::receipt::TransactionReceipt; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::{ - gas_vector_from_vm_usage, get_vm_resource_usage, CairoVersion, BALANCE, - DEFAULT_ETH_L1_DATA_GAS_PRICE, DEFAULT_ETH_L1_GAS_PRICE, DEFAULT_L1_DATA_GAS_MAX_AMOUNT, - DEFAULT_L1_GAS_AMOUNT, DEFAULT_L2_GAS_MAX_AMOUNT, DEFAULT_STRK_L1_GAS_PRICE, + BALANCE, CairoVersion, DEFAULT_ETH_L1_DATA_GAS_PRICE, DEFAULT_ETH_L1_GAS_PRICE, + DEFAULT_L1_DATA_GAS_MAX_AMOUNT, DEFAULT_L1_GAS_AMOUNT, DEFAULT_L2_GAS_MAX_AMOUNT, + DEFAULT_STRK_L1_GAS_PRICE, gas_vector_from_vm_usage, get_vm_resource_usage, }; use crate::transaction::test_utils::{ all_resource_bounds, block_context, invoke_tx_with_default_flags, l1_resource_bounds, diff --git a/crates/blockifier/src/fee/gas_usage_test.rs b/crates/blockifier/src/fee/gas_usage_test.rs index 3ab516967a..cbc87c5e7b 100644 --- a/crates/blockifier/src/fee/gas_usage_test.rs +++ b/crates/blockifier/src/fee/gas_usage_test.rs @@ -21,7 +21,7 @@ use crate::fee::resources::{ }; use crate::state::cached_state::StateChangesCount; use crate::test_utils::{ - get_vm_resource_usage, DEFAULT_ETH_L1_DATA_GAS_PRICE, DEFAULT_ETH_L1_GAS_PRICE, + DEFAULT_ETH_L1_DATA_GAS_PRICE, DEFAULT_ETH_L1_GAS_PRICE, get_vm_resource_usage, }; use crate::transaction::test_utils::invoke_tx_with_default_flags; use crate::utils::u64_from_usize; @@ -124,14 +124,16 @@ fn test_get_event_gas_cost( events: vec![create_event_for_testing(0, 1)], ..Default::default() }, - inner_calls: vec![CallInfo { - execution: CallExecution { - events: vec![create_event_for_testing(5, 5)], + inner_calls: vec![ + CallInfo { + execution: CallExecution { + events: vec![create_event_for_testing(5, 5)], + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - } - .with_some_class_hash()], + } + .with_some_class_hash(), + ], ..Default::default() }; let call_infos: Vec = vec![call_info_1, call_info_2, call_info_3] diff --git a/crates/blockifier/src/fee/receipt_test.rs b/crates/blockifier/src/fee/receipt_test.rs index 4dd7ea0db2..f039d688c6 100644 --- a/crates/blockifier/src/fee/receipt_test.rs +++ b/crates/blockifier/src/fee/receipt_test.rs @@ -1,7 +1,7 @@ use rstest::{fixture, rstest}; use starknet_api::execution_resources::GasVector; use starknet_api::transaction::fields::GasVectorComputationMode; -use starknet_api::transaction::{constants, L2ToL1Payload}; +use starknet_api::transaction::{L2ToL1Payload, constants}; use starknet_api::{invoke_tx_args, nonce}; use starknet_types_core::felt::Felt; @@ -19,7 +19,7 @@ use crate::state::cached_state::StateChangesCount; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::{ - create_calldata, create_trivial_calldata, CairoVersion, RunnableCairo1, BALANCE, + BALANCE, CairoVersion, RunnableCairo1, create_calldata, create_trivial_calldata, }; use crate::transaction::objects::HasRelatedFeeType; use crate::transaction::test_utils::{ @@ -413,15 +413,12 @@ fn test_calculate_tx_gas_usage( // A tx that changes the account and some other balance in execute. let some_other_account_address = account_contract.get_instance_address(17); - let execute_calldata = create_calldata( - fee_token_address, - constants::TRANSFER_ENTRY_POINT_NAME, - &[ + let execute_calldata = + create_calldata(fee_token_address, constants::TRANSFER_ENTRY_POINT_NAME, &[ *some_other_account_address.0.key(), // Calldata: recipient. Felt::TWO, // Calldata: lsb amount. Felt::ZERO, // Calldata: msb amount. - ], - ); + ]); let account_tx = invoke_tx_with_default_flags(invoke_tx_args! { resource_bounds: max_resource_bounds, diff --git a/crates/blockifier/src/state/cached_state.rs b/crates/blockifier/src/state/cached_state.rs index 8dc40ca38d..f7b2a6b9b6 100644 --- a/crates/blockifier/src/state/cached_state.rs +++ b/crates/blockifier/src/state/cached_state.rs @@ -741,11 +741,7 @@ impl AllocatedKeys { .iter() .filter_map(|(k, v)| { let base_value = base_storage.get(k).unwrap_or(&Felt::ZERO); - if *v != Felt::ZERO && *base_value == Felt::ZERO { - Some(*k) - } else { - None - } + if *v != Felt::ZERO && *base_value == Felt::ZERO { Some(*k) } else { None } }) .collect(), ) diff --git a/crates/blockifier/src/state/cached_state_test.rs b/crates/blockifier/src/state/cached_state_test.rs index ad11c331ae..456faec459 100644 --- a/crates/blockifier/src/state/cached_state_test.rs +++ b/crates/blockifier/src/state/cached_state_test.rs @@ -14,8 +14,8 @@ use crate::state::cached_state::*; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::dict_state_reader::DictStateReader; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{create_calldata, CairoVersion, RunnableCairo1, BALANCE}; -use crate::transaction::test_utils::{default_all_resource_bounds, run_invoke_tx, STORAGE_WRITE}; +use crate::test_utils::{BALANCE, CairoVersion, RunnableCairo1, create_calldata}; +use crate::transaction::test_utils::{STORAGE_WRITE, default_all_resource_bounds, run_invoke_tx}; const CONTRACT_ADDRESS: &str = "0x100"; fn set_initial_state_values( @@ -530,16 +530,12 @@ fn test_write_at_validate_and_execute( let signature = TransactionSignature(vec![Felt::from(STORAGE_WRITE), validate_value, execute_value]); - let tx_execution_info = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - signature, - sender_address: contract_address, - resource_bounds: default_all_resource_bounds, - calldata: create_calldata(contract_address, "foo", &[]), - }, - ) + let tx_execution_info = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + signature, + sender_address: contract_address, + resource_bounds: default_all_resource_bounds, + calldata: create_calldata(contract_address, "foo", &[]), + }) .unwrap(); let n_allocated_keys = tx_execution_info .receipt @@ -648,15 +644,12 @@ fn test_state_changes_keys() { assert_eq!(keys0, keys0.difference(&empty_keys)); assert_eq!(empty_keys, keys0.difference(&keys0)); assert_eq!(empty_keys.count(), StateChangesCount::default()); - assert_eq!( - keys0.count(), - StateChangesCount { - n_storage_updates: 2, - n_class_hash_updates: 1, - n_compiled_class_hash_updates: 2, - n_modified_contracts: 2 - } - ); + assert_eq!(keys0.count(), StateChangesCount { + n_storage_updates: 2, + n_class_hash_updates: 1, + n_compiled_class_hash_updates: 2, + n_modified_contracts: 2 + }); let mut keys0_copy = keys0.clone(); let mut empty_keys_copy = empty_keys.clone(); @@ -675,48 +668,39 @@ fn test_state_changes_keys() { modified_contracts: HashSet::from([contract_address1, contract_address3]), }; - assert_eq!( - keys0.difference(&keys1), - StateChangesKeys { - nonce_keys: HashSet::from([contract_address0]), - class_hash_keys: HashSet::new(), - storage_keys: HashSet::from([(contract_address2, storage_key!(0x200_u16),)]), - compiled_class_hash_keys: HashSet::from([class_hash1]), - modified_contracts: HashSet::from([contract_address2]), - } - ); - assert_eq!( - keys1.difference(&keys0), - StateChangesKeys { - nonce_keys: HashSet::from([contract_address1]), - class_hash_keys: HashSet::from([contract_address2]), - storage_keys: HashSet::new(), - compiled_class_hash_keys: HashSet::new(), - modified_contracts: HashSet::from([contract_address3]), - } - ); + assert_eq!(keys0.difference(&keys1), StateChangesKeys { + nonce_keys: HashSet::from([contract_address0]), + class_hash_keys: HashSet::new(), + storage_keys: HashSet::from([(contract_address2, storage_key!(0x200_u16),)]), + compiled_class_hash_keys: HashSet::from([class_hash1]), + modified_contracts: HashSet::from([contract_address2]), + }); + assert_eq!(keys1.difference(&keys0), StateChangesKeys { + nonce_keys: HashSet::from([contract_address1]), + class_hash_keys: HashSet::from([contract_address2]), + storage_keys: HashSet::new(), + compiled_class_hash_keys: HashSet::new(), + modified_contracts: HashSet::from([contract_address3]), + }); let keys1_copy = keys1.clone(); keys1.extend(&keys0); keys0.extend(&keys1_copy); assert_eq!(keys0, keys1); - assert_eq!( - keys0, - StateChangesKeys { - nonce_keys: HashSet::from([contract_address0, contract_address1]), - class_hash_keys: HashSet::from([contract_address1, contract_address2]), - storage_keys: HashSet::from([ - (contract_address2, storage_key!(0x300_u16)), - (contract_address2, storage_key!(0x200_u16)), - ]), - compiled_class_hash_keys: HashSet::from([class_hash0, class_hash1]), - modified_contracts: HashSet::from([ - contract_address1, - contract_address2, - contract_address3 - ]), - } - ) + assert_eq!(keys0, StateChangesKeys { + nonce_keys: HashSet::from([contract_address0, contract_address1]), + class_hash_keys: HashSet::from([contract_address1, contract_address2]), + storage_keys: HashSet::from([ + (contract_address2, storage_key!(0x300_u16)), + (contract_address2, storage_key!(0x200_u16)), + ]), + compiled_class_hash_keys: HashSet::from([class_hash0, class_hash1]), + modified_contracts: HashSet::from([ + contract_address1, + contract_address2, + contract_address3 + ]), + }) } #[rstest] diff --git a/crates/blockifier/src/state/contract_class_manager.rs b/crates/blockifier/src/state/contract_class_manager.rs index 6fcac067c1..0b1ed951e3 100644 --- a/crates/blockifier/src/state/contract_class_manager.rs +++ b/crates/blockifier/src/state/contract_class_manager.rs @@ -1,13 +1,13 @@ -use std::sync::mpsc::{sync_channel, Receiver, SyncSender, TrySendError}; use std::sync::Arc; +use std::sync::mpsc::{Receiver, SyncSender, TrySendError, sync_channel}; use log::{error, info}; use starknet_api::core::ClassHash; use starknet_api::state::SierraContractClass; +use starknet_sierra_compile::SierraToNativeCompiler; use starknet_sierra_compile::command_line_compiler::CommandLineCompiler; use starknet_sierra_compile::config::SierraToCasmCompilationConfig; use starknet_sierra_compile::utils::into_contract_class_for_compilation; -use starknet_sierra_compile::SierraToNativeCompiler; use crate::execution::contract_class::{CompiledClassV1, RunnableCompiledClass}; use crate::execution::native::contract_class::NativeCompiledClassV1; diff --git a/crates/blockifier/src/state/errors.rs b/crates/blockifier/src/state/errors.rs index 1eba9b18bf..2aaf2be679 100644 --- a/crates/blockifier/src/state/errors.rs +++ b/crates/blockifier/src/state/errors.rs @@ -1,7 +1,7 @@ use cairo_vm::types::errors::program_errors::ProgramError; use num_bigint::{BigUint, TryFromBigIntError}; -use starknet_api::core::{ClassHash, ContractAddress}; use starknet_api::StarknetApiError; +use starknet_api::core::{ClassHash, ContractAddress}; use thiserror::Error; use crate::abi::constants; diff --git a/crates/blockifier/src/test_utils.rs b/crates/blockifier/src/test_utils.rs index 978a1c4dbb..82e786a950 100644 --- a/crates/blockifier/src/test_utils.rs +++ b/crates/blockifier/src/test_utils.rs @@ -20,10 +20,10 @@ use starknet_api::core::{ClassHash, ContractAddress}; use starknet_api::execution_resources::{GasAmount, GasVector}; use starknet_api::hash::StarkHash; use starknet_api::state::StorageKey; +use starknet_api::transaction::TransactionVersion; use starknet_api::transaction::fields::{ Calldata, ContractAddressSalt, Fee, GasVectorComputationMode, }; -use starknet_api::transaction::TransactionVersion; use starknet_api::{contract_address, felt}; use starknet_types_core::felt::Felt; diff --git a/crates/blockifier/src/test_utils/contracts.rs b/crates/blockifier/src/test_utils/contracts.rs index 5e7c924edf..6e55ffe22d 100644 --- a/crates/blockifier/src/test_utils/contracts.rs +++ b/crates/blockifier/src/test_utils/contracts.rs @@ -20,9 +20,9 @@ use crate::execution::contract_class::RunnableCompiledClass; use crate::execution::entry_point::CallEntryPoint; #[cfg(feature = "cairo_native")] use crate::execution::native::contract_class::NativeCompiledClassV1; -use crate::test_utils::cairo_compile::{cairo0_compile, cairo1_compile, CompilationArtifacts}; +use crate::test_utils::cairo_compile::{CompilationArtifacts, cairo0_compile, cairo1_compile}; use crate::test_utils::struct_impls::LoadContractFromFile; -use crate::test_utils::{get_raw_contract_class, CairoVersion, RunnableCairo1}; +use crate::test_utils::{CairoVersion, RunnableCairo1, get_raw_contract_class}; pub const CAIRO1_FEATURE_CONTRACTS_DIR: &str = "feature_contracts/cairo1"; pub const SIERRA_CONTRACTS_SUBDIR: &str = "sierra"; diff --git a/crates/blockifier/src/test_utils/initial_test_state.rs b/crates/blockifier/src/test_utils/initial_test_state.rs index 0beeb1a36d..aaca05d93a 100644 --- a/crates/blockifier/src/test_utils/initial_test_state.rs +++ b/crates/blockifier/src/test_utils/initial_test_state.rs @@ -9,9 +9,9 @@ use strum::IntoEnumIterator; use crate::context::ChainInfo; use crate::state::cached_state::CachedState; +use crate::test_utils::CairoVersion; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::dict_state_reader::DictStateReader; -use crate::test_utils::CairoVersion; /// Utility to fund an account. pub fn fund_account( diff --git a/crates/blockifier/src/test_utils/l1_handler.rs b/crates/blockifier/src/test_utils/l1_handler.rs index a57d08b8b6..403ecdffaa 100644 --- a/crates/blockifier/src/test_utils/l1_handler.rs +++ b/crates/blockifier/src/test_utils/l1_handler.rs @@ -2,9 +2,9 @@ use starknet_api::abi::abi_utils::selector_from_name; use starknet_api::calldata; use starknet_api::core::ContractAddress; use starknet_api::executable_transaction::L1HandlerTransaction; -use starknet_api::test_utils::l1_handler::{executable_l1_handler_tx, L1HandlerTxArgs}; -use starknet_api::transaction::fields::Fee; +use starknet_api::test_utils::l1_handler::{L1HandlerTxArgs, executable_l1_handler_tx}; use starknet_api::transaction::TransactionVersion; +use starknet_api::transaction::fields::Fee; use starknet_types_core::felt::Felt; pub fn l1handler_tx(l1_fee: Fee, contract_address: ContractAddress) -> L1HandlerTransaction { diff --git a/crates/blockifier/src/test_utils/prices.rs b/crates/blockifier/src/test_utils/prices.rs index 0184474f69..60533ce729 100644 --- a/crates/blockifier/src/test_utils/prices.rs +++ b/crates/blockifier/src/test_utils/prices.rs @@ -13,8 +13,8 @@ use crate::context::BlockContext; use crate::execution::common_hints::ExecutionMode; use crate::execution::entry_point::{CallEntryPoint, EntryPointExecutionContext}; use crate::state::state_api::State; -use crate::test_utils::initial_test_state::test_state; use crate::test_utils::BALANCE; +use crate::test_utils::initial_test_state::test_state; use crate::transaction::test_utils::invoke_tx_with_default_flags; /// Enum for all resource costs. diff --git a/crates/blockifier/src/test_utils/struct_impls.rs b/crates/blockifier/src/test_utils/struct_impls.rs index 8995be676b..7e661742e2 100644 --- a/crates/blockifier/src/test_utils/struct_impls.rs +++ b/crates/blockifier/src/test_utils/struct_impls.rs @@ -16,8 +16,8 @@ use starknet_api::core::{ChainId, ClassHash}; use starknet_api::deprecated_contract_class::ContractClass as DeprecatedContractClass; use super::{ - update_json_value, TEST_ERC20_CONTRACT_ADDRESS, TEST_ERC20_CONTRACT_ADDRESS2, - TEST_SEQUENCER_ADDRESS, + TEST_ERC20_CONTRACT_ADDRESS, TEST_ERC20_CONTRACT_ADDRESS2, TEST_SEQUENCER_ADDRESS, + update_json_value, }; use crate::blockifier::block::validated_gas_prices; use crate::bouncer::{BouncerConfig, BouncerWeights, BuiltinCount}; @@ -33,15 +33,15 @@ use crate::execution::entry_point::{ use crate::execution::native::contract_class::NativeCompiledClassV1; use crate::state::state_api::State; use crate::test_utils::{ - get_raw_contract_class, CURRENT_BLOCK_NUMBER, CURRENT_BLOCK_TIMESTAMP, - DEFAULT_ETH_L1_DATA_GAS_PRICE, DEFAULT_ETH_L1_GAS_PRICE, DEFAULT_STRK_L1_DATA_GAS_PRICE, - DEFAULT_STRK_L1_GAS_PRICE, + CURRENT_BLOCK_NUMBER, CURRENT_BLOCK_TIMESTAMP, DEFAULT_ETH_L1_DATA_GAS_PRICE, + DEFAULT_ETH_L1_GAS_PRICE, DEFAULT_STRK_L1_DATA_GAS_PRICE, DEFAULT_STRK_L1_GAS_PRICE, + get_raw_contract_class, }; use crate::transaction::objects::{ CurrentTransactionInfo, DeprecatedTransactionInfo, TransactionInfo, }; use crate::versioned_constants::{ - GasCosts, OsConstants, VersionedConstants, VERSIONED_CONSTANTS_LATEST_JSON, + GasCosts, OsConstants, VERSIONED_CONSTANTS_LATEST_JSON, VersionedConstants, }; impl CallEntryPoint { diff --git a/crates/blockifier/src/test_utils/syscall.rs b/crates/blockifier/src/test_utils/syscall.rs index 81db2822d6..e60d294069 100644 --- a/crates/blockifier/src/test_utils/syscall.rs +++ b/crates/blockifier/src/test_utils/syscall.rs @@ -1,7 +1,7 @@ use starknet_api::felt; use starknet_api::transaction::fields::Calldata; -use crate::test_utils::{create_calldata, CompilerBasedVersion}; +use crate::test_utils::{CompilerBasedVersion, create_calldata}; /// Returns the calldata for N recursive call contract syscalls, where N is the length of versions. /// versions determines the cairo version of the called contract in each recursive call. Final call diff --git a/crates/blockifier/src/test_utils/transfers_generator.rs b/crates/blockifier/src/test_utils/transfers_generator.rs index 954caa75d0..f294e11aec 100644 --- a/crates/blockifier/src/test_utils/transfers_generator.rs +++ b/crates/blockifier/src/test_utils/transfers_generator.rs @@ -3,11 +3,11 @@ use rand::{Rng, SeedableRng}; use starknet_api::abi::abi_utils::selector_from_name; use starknet_api::core::ContractAddress; use starknet_api::executable_transaction::AccountTransaction as ApiExecutableTransaction; -use starknet_api::test_utils::invoke::executable_invoke_tx; use starknet_api::test_utils::NonceManager; +use starknet_api::test_utils::invoke::executable_invoke_tx; +use starknet_api::transaction::TransactionVersion; use starknet_api::transaction::constants::TRANSFER_ENTRY_POINT_NAME; use starknet_api::transaction::fields::Fee; -use starknet_api::transaction::TransactionVersion; use starknet_api::{calldata, felt, invoke_tx_args}; use starknet_types_core::felt::Felt; @@ -17,7 +17,7 @@ use crate::context::{BlockContext, ChainInfo}; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::dict_state_reader::DictStateReader; use crate::test_utils::initial_test_state::test_state; -use crate::test_utils::{CairoVersion, BALANCE, MAX_FEE}; +use crate::test_utils::{BALANCE, CairoVersion, MAX_FEE}; use crate::transaction::account_transaction::AccountTransaction; use crate::transaction::transaction_execution::Transaction; const N_ACCOUNTS: u16 = 10000; diff --git a/crates/blockifier/src/transaction/account_transaction.rs b/crates/blockifier/src/transaction/account_transaction.rs index 3082cc0918..e0d6c363d0 100644 --- a/crates/blockifier/src/transaction/account_transaction.rs +++ b/crates/blockifier/src/transaction/account_transaction.rs @@ -12,7 +12,7 @@ use starknet_api::transaction::fields::{ AccountDeploymentData, AllResourceBounds, Calldata, Fee, PaymasterData, Tip, TransactionSignature, ValidResourceBounds, }; -use starknet_api::transaction::{constants, TransactionHash, TransactionVersion}; +use starknet_api::transaction::{TransactionHash, TransactionVersion, constants}; use starknet_types_core::felt::Felt; use crate::context::{BlockContext, TransactionContext}; @@ -20,7 +20,7 @@ use crate::execution::call_info::CallInfo; use crate::execution::contract_class::RunnableCompiledClass; use crate::execution::entry_point::{CallEntryPoint, CallType, EntryPointExecutionContext}; use crate::execution::stack_trace::{ - extract_trailing_cairo1_revert_trace, gen_tx_execution_error_trace, Cairo1RevertHeader, + Cairo1RevertHeader, extract_trailing_cairo1_revert_trace, gen_tx_execution_error_trace, }; use crate::fee::fee_checks::{FeeCheckReportFields, PostExecutionReport}; use crate::fee::fee_utils::{ @@ -41,7 +41,7 @@ use crate::transaction::objects::{ }; use crate::transaction::transaction_types::TransactionType; use crate::transaction::transactions::{ - enforce_fee, Executable, ExecutableTransaction, ValidatableTransaction, + Executable, ExecutableTransaction, ValidatableTransaction, enforce_fee, }; #[cfg(test)] @@ -676,11 +676,7 @@ impl AccountTransaction { /// Returns 0 on non-declare transactions; for declare transactions, returns the class code /// size. pub(crate) fn declare_code_size(&self) -> usize { - if let Transaction::Declare(tx) = &self.tx { - tx.class_info.code_size() - } else { - 0 - } + if let Transaction::Declare(tx) = &self.tx { tx.class_info.code_size() } else { 0 } } fn is_non_revertible(&self, tx_info: &TransactionInfo) -> bool { diff --git a/crates/blockifier/src/transaction/account_transactions_test.rs b/crates/blockifier/src/transaction/account_transactions_test.rs index 2c8874cbae..8f9cd2e56f 100644 --- a/crates/blockifier/src/transaction/account_transactions_test.rs +++ b/crates/blockifier/src/transaction/account_transactions_test.rs @@ -10,7 +10,7 @@ use starknet_api::abi::abi_utils::{ get_fee_token_var_address, get_storage_var_address, selector_from_name, }; use starknet_api::block::{FeeType, GasPrice}; -use starknet_api::core::{calculate_contract_address, ClassHash, ContractAddress}; +use starknet_api::core::{ClassHash, ContractAddress, calculate_contract_address}; use starknet_api::executable_transaction::{ AccountTransaction as ApiExecutableTransaction, DeclareTransaction as ApiExecutableDeclareTransaction, @@ -18,10 +18,10 @@ use starknet_api::executable_transaction::{ use starknet_api::execution_resources::GasAmount; use starknet_api::hash::StarkHash; use starknet_api::state::StorageKey; +use starknet_api::test_utils::NonceManager; use starknet_api::test_utils::declare::executable_declare_tx; use starknet_api::test_utils::deploy_account::executable_deploy_account_tx; -use starknet_api::test_utils::invoke::{executable_invoke_tx, InvokeTxArgs}; -use starknet_api::test_utils::NonceManager; +use starknet_api::test_utils::invoke::{InvokeTxArgs, executable_invoke_tx}; use starknet_api::transaction::constants::TRANSFER_ENTRY_POINT_NAME; use starknet_api::transaction::fields::{ AllResourceBounds, Calldata, ContractAddressSalt, Fee, GasVectorComputationMode, Resource, @@ -50,21 +50,21 @@ use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::{fund_account, test_state}; use crate::test_utils::syscall::build_recurse_calldata; use crate::test_utils::{ - create_calldata, create_trivial_calldata, get_syscall_resources, get_tx_resources, - CairoVersion, CompilerBasedVersion, RunnableCairo1, BALANCE, DEFAULT_L1_DATA_GAS_MAX_AMOUNT, + BALANCE, CairoVersion, CompilerBasedVersion, DEFAULT_L1_DATA_GAS_MAX_AMOUNT, DEFAULT_L1_GAS_AMOUNT, DEFAULT_L2_GAS_MAX_AMOUNT, DEFAULT_STRK_L1_DATA_GAS_PRICE, - DEFAULT_STRK_L1_GAS_PRICE, DEFAULT_STRK_L2_GAS_PRICE, MAX_FEE, + DEFAULT_STRK_L1_GAS_PRICE, DEFAULT_STRK_L2_GAS_PRICE, MAX_FEE, RunnableCairo1, create_calldata, + create_trivial_calldata, get_syscall_resources, get_tx_resources, }; use crate::transaction::account_transaction::{ AccountTransaction, ExecutionFlags as AccountExecutionFlags, }; use crate::transaction::objects::{HasRelatedFeeType, TransactionInfoCreator}; use crate::transaction::test_utils::{ - all_resource_bounds, block_context, calculate_class_info_for_testing, - create_account_tx_for_validate_test_nonce_0, create_all_resource_bounds, create_test_init_data, - default_all_resource_bounds, default_l1_resource_bounds, deploy_and_fund_account, - invoke_tx_with_default_flags, l1_resource_bounds, max_fee, run_invoke_tx, - FaultyAccountTxCreatorArgs, TestInitData, INVALID, + FaultyAccountTxCreatorArgs, INVALID, TestInitData, all_resource_bounds, block_context, + calculate_class_info_for_testing, create_account_tx_for_validate_test_nonce_0, + create_all_resource_bounds, create_test_init_data, default_all_resource_bounds, + default_l1_resource_bounds, deploy_and_fund_account, invoke_tx_with_default_flags, + l1_resource_bounds, max_fee, run_invoke_tx, }; use crate::transaction::transaction_types::TransactionType; use crate::transaction::transactions::ExecutableTransaction; @@ -91,14 +91,10 @@ fn test_circuit(block_context: BlockContext, default_all_resource_bounds: ValidR ), nonce: nonce_manager.next(account_address) }; - let tx_execution_info = run_invoke_tx( - state, - &block_context, - invoke_tx_args! { - resource_bounds: default_all_resource_bounds, - ..tx_args - }, - ) + let tx_execution_info = run_invoke_tx(state, &block_context, invoke_tx_args! { + resource_bounds: default_all_resource_bounds, + ..tx_args + }) .unwrap(); assert!(tx_execution_info.revert_error.is_none()); @@ -125,14 +121,10 @@ fn test_rc96_holes(block_context: BlockContext, default_all_resource_bounds: Val ), nonce: nonce_manager.next(account_address) }; - let tx_execution_info = run_invoke_tx( - state, - &block_context, - invoke_tx_args! { - resource_bounds: default_all_resource_bounds, - ..tx_args - }, - ) + let tx_execution_info = run_invoke_tx(state, &block_context, invoke_tx_args! { + resource_bounds: default_all_resource_bounds, + ..tx_args + }) .unwrap(); assert!(!tx_execution_info.is_reverted()); @@ -275,18 +267,14 @@ fn test_account_flow_test( create_test_init_data(&block_context.chain_info, CairoVersion::Cairo0); // Invoke a function from the newly deployed contract. - run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - max_fee, - sender_address: account_address, - calldata: create_trivial_calldata(contract_address), - version: tx_version, - resource_bounds, - nonce: nonce_manager.next(account_address), - }, - ) + run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + max_fee, + sender_address: account_address, + calldata: create_trivial_calldata(contract_address), + version: tx_version, + resource_bounds, + nonce: nonce_manager.next(account_address), + }) .unwrap(); } @@ -307,23 +295,19 @@ fn test_invoke_tx_from_non_deployed_account( let non_deployed_contract_address = StarkHash::TWO; - let tx_result = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - max_fee, - sender_address: account_address, - calldata: calldata![ - non_deployed_contract_address, // Contract address. - entry_point_selector.0, // EP selector. - felt!(1_u8), // Calldata length. - felt!(2_u8) // Calldata: num. - ], - resource_bounds: default_all_resource_bounds, - version: tx_version, - nonce: nonce_manager.next(account_address), - }, - ); + let tx_result = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + max_fee, + sender_address: account_address, + calldata: calldata![ + non_deployed_contract_address, // Contract address. + entry_point_selector.0, // EP selector. + felt!(1_u8), // Calldata length. + felt!(2_u8) // Calldata: num. + ], + resource_bounds: default_all_resource_bounds, + version: tx_version, + nonce: nonce_manager.next(account_address), + }); let expected_error = "is not deployed."; match tx_result { Ok(info) => { @@ -360,36 +344,30 @@ fn test_infinite_recursion( let execute_calldata = if normal_recurse { create_calldata(contract_address, "recurse", &[felt!(recursion_depth)]) } else { - create_calldata( - contract_address, - "recursive_syscall", - &[ - *contract_address.0.key(), // Calldata: raw contract address. - selector_from_name("recursive_syscall").0, // Calldata: raw selector - felt!(recursion_depth), - ], - ) + create_calldata(contract_address, "recursive_syscall", &[ + *contract_address.0.key(), // Calldata: raw contract address. + selector_from_name("recursive_syscall").0, // Calldata: raw selector + felt!(recursion_depth), + ]) }; - let tx_execution_info = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - resource_bounds, - sender_address: account_address, - calldata: execute_calldata, - nonce: nonce_manager.next(account_address), - }, - ) + let tx_execution_info = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + resource_bounds, + sender_address: account_address, + calldata: execute_calldata, + nonce: nonce_manager.next(account_address), + }) .unwrap(); if success { assert!(tx_execution_info.revert_error.is_none()); } else { - assert!(tx_execution_info - .revert_error - .unwrap() - .to_string() - .contains("RunResources has no remaining steps.")); + assert!( + tx_execution_info + .revert_error + .unwrap() + .to_string() + .contains("RunResources has no remaining steps.") + ); } } @@ -492,41 +470,37 @@ fn test_max_fee_limit_validate( // Make sure the resource bounds are the limiting factor by blowing up the block bounds. let old_validate_max_n_steps = block_context.versioned_constants.validate_max_n_steps; block_context.versioned_constants.validate_max_n_steps = u32::MAX; - let error_trace = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - max_fee: estimated_min_fee, - resource_bounds: match resource_bounds.get_gas_vector_computation_mode() { - GasVectorComputationMode::NoL2Gas => { - // If KZG DA mode is active, the L1 gas amount in the minimal fee estimate does - // not include DA. To cover minimal cost with only an L1 gas bound, need to - // convert the L1 data gas to L1 gas. - let tx_context = TransactionContext { - block_context: block_context.clone(), - tx_info: account_tx.create_tx_info(), - }; - let gas_prices = tx_context.get_gas_prices(); - l1_resource_bounds( - estimated_min_gas_usage_vector.to_discounted_l1_gas(gas_prices), - gas_prices.l1_gas_price.into(), - ) - } - GasVectorComputationMode::All => create_all_resource_bounds( - estimated_min_gas_usage_vector.l1_gas, - block_info.gas_prices - .l1_gas_price(&account_tx.fee_type()).into(), - estimated_min_gas_usage_vector.l2_gas, - block_info.gas_prices - .l2_gas_price(&account_tx.fee_type()).into(), - estimated_min_gas_usage_vector.l1_data_gas, - block_info.gas_prices - .l1_data_gas_price(&account_tx.fee_type()).into(), - ), - }, - ..tx_args + let error_trace = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + max_fee: estimated_min_fee, + resource_bounds: match resource_bounds.get_gas_vector_computation_mode() { + GasVectorComputationMode::NoL2Gas => { + // If KZG DA mode is active, the L1 gas amount in the minimal fee estimate does + // not include DA. To cover minimal cost with only an L1 gas bound, need to + // convert the L1 data gas to L1 gas. + let tx_context = TransactionContext { + block_context: block_context.clone(), + tx_info: account_tx.create_tx_info(), + }; + let gas_prices = tx_context.get_gas_prices(); + l1_resource_bounds( + estimated_min_gas_usage_vector.to_discounted_l1_gas(gas_prices), + gas_prices.l1_gas_price.into(), + ) + } + GasVectorComputationMode::All => create_all_resource_bounds( + estimated_min_gas_usage_vector.l1_gas, + block_info.gas_prices + .l1_gas_price(&account_tx.fee_type()).into(), + estimated_min_gas_usage_vector.l2_gas, + block_info.gas_prices + .l2_gas_price(&account_tx.fee_type()).into(), + estimated_min_gas_usage_vector.l1_data_gas, + block_info.gas_prices + .l1_data_gas_price(&account_tx.fee_type()).into(), + ), }, - ) + ..tx_args + }) .unwrap_err() .to_string(); block_context.versioned_constants.validate_max_n_steps = old_validate_max_n_steps; @@ -562,15 +536,11 @@ fn test_recursion_depth_exceeded( .expect("Failed to convert usize to u8."); let recursive_syscall_entry_point_name = "recursive_syscall"; - let calldata = create_calldata( - contract_address, - recursive_syscall_entry_point_name, - &[ - *contract_address.0.key(), // Calldata: raw contract address. - selector_from_name(recursive_syscall_entry_point_name).0, // Calldata: raw selector. - felt!(max_inner_recursion_depth), - ], - ); + let calldata = create_calldata(contract_address, recursive_syscall_entry_point_name, &[ + *contract_address.0.key(), // Calldata: raw contract address. + selector_from_name(recursive_syscall_entry_point_name).0, // Calldata: raw selector. + felt!(max_inner_recursion_depth), + ]); let invoke_args = invoke_tx_args! { max_fee, sender_address: account_address, @@ -587,25 +557,23 @@ fn test_recursion_depth_exceeded( let exceeding_recursion_depth = max_inner_recursion_depth + 1; - let calldata = create_calldata( - contract_address, - recursive_syscall_entry_point_name, - &[ - *contract_address.0.key(), // Calldata: raw contract address. - selector_from_name(recursive_syscall_entry_point_name).0, // Calldata: raw selector. - felt!(exceeding_recursion_depth), - ], - ); + let calldata = create_calldata(contract_address, recursive_syscall_entry_point_name, &[ + *contract_address.0.key(), // Calldata: raw contract address. + selector_from_name(recursive_syscall_entry_point_name).0, // Calldata: raw selector. + felt!(exceeding_recursion_depth), + ]); let invoke_args = InvokeTxArgs { calldata, nonce: nonce_manager.next(account_address), ..invoke_args }; let tx_execution_info = run_invoke_tx(&mut state, &block_context, invoke_args); - assert!(tx_execution_info - .unwrap() - .revert_error - .unwrap() - .to_string() - .contains("recursion depth exceeded")); + assert!( + tx_execution_info + .unwrap() + .revert_error + .unwrap() + .to_string() + .contains("recursion depth exceeded") + ); } #[rstest] @@ -630,23 +598,19 @@ fn test_revert_invoke( // Invoke a function that changes the state and reverts. let storage_key = felt!(9_u8); - let tx_execution_info = run_invoke_tx( - state, - &block_context, - invoke_tx_args! { - max_fee, - resource_bounds: all_resource_bounds, - sender_address: account_address, - calldata: create_calldata( - test_contract_address, - "write_and_revert", - // Write some non-zero value. - &[storage_key, felt!(99_u8)] - ), - version: transaction_version, - nonce: nonce_manager.next(account_address), - }, - ) + let tx_execution_info = run_invoke_tx(state, &block_context, invoke_tx_args! { + max_fee, + resource_bounds: all_resource_bounds, + sender_address: account_address, + calldata: create_calldata( + test_contract_address, + "write_and_revert", + // Write some non-zero value. + &[storage_key, felt!(99_u8)] + ), + version: transaction_version, + nonce: nonce_manager.next(account_address), + }) .unwrap(); // TODO(Dori, 1/7/2023): Verify that the actual fee collected is exactly the fee computed for @@ -812,15 +776,11 @@ fn test_reverted_reach_steps_limit( }; // Invoke the `recurse` function with 0 iterations. This call should succeed. - let result = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - nonce: nonce_manager.next(account_address), - calldata: recursive_function_calldata(&contract_address, 0, false), - ..recursion_base_args.clone() - }, - ) + let result = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + nonce: nonce_manager.next(account_address), + calldata: recursive_function_calldata(&contract_address, 0, false), + ..recursion_base_args.clone() + }) .unwrap(); let n_steps_0 = result.receipt.resources.computation.total_charged_steps(); let actual_fee_0 = result.receipt.fee.0; @@ -828,15 +788,11 @@ fn test_reverted_reach_steps_limit( assert!(!result.is_reverted()); // Invoke the `recurse` function with 1 iteration. This call should succeed. - let result = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - nonce: nonce_manager.next(account_address), - calldata: recursive_function_calldata(&contract_address, 1, false), - ..recursion_base_args.clone() - }, - ) + let result = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + nonce: nonce_manager.next(account_address), + calldata: recursive_function_calldata(&contract_address, 1, false), + ..recursion_base_args.clone() + }) .unwrap(); let n_steps_1 = result.receipt.resources.computation.total_charged_steps(); let actual_fee_1 = result.receipt.fee.0; @@ -855,15 +811,11 @@ fn test_reverted_reach_steps_limit( let fail_depth = block_context.versioned_constants.invoke_tx_max_n_steps / steps_diff_as_u32; // Invoke the `recurse` function with `fail_depth` iterations. This call should fail. - let result = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - nonce: nonce_manager.next(account_address), - calldata: recursive_function_calldata(&contract_address, fail_depth, false), - ..recursion_base_args.clone() - }, - ) + let result = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + nonce: nonce_manager.next(account_address), + calldata: recursive_function_calldata(&contract_address, fail_depth, false), + ..recursion_base_args.clone() + }) .unwrap(); let n_steps_fail = result.receipt.resources.computation.total_charged_steps(); let actual_fee_fail: u128 = result.receipt.fee.0; @@ -878,15 +830,11 @@ fn test_reverted_reach_steps_limit( assert!(actual_fee_fail > actual_fee_1); // Invoke the `recurse` function with `fail_depth`+1 iterations. This call should fail. - let result = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - nonce: nonce_manager.next(account_address), - calldata: recursive_function_calldata(&contract_address, fail_depth + 1, false), - ..recursion_base_args - }, - ) + let result = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + nonce: nonce_manager.next(account_address), + calldata: recursive_function_calldata(&contract_address, fail_depth + 1, false), + ..recursion_base_args + }) .unwrap(); let n_steps_fail_next = result.receipt.resources.computation.total_charged_steps(); let actual_fee_fail_next: u128 = result.receipt.fee.0; @@ -917,15 +865,11 @@ fn test_n_reverted_steps( }; // Invoke the `recursive_fail` function with 0 iterations. This call should fail. - let result = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - nonce: nonce_manager.next(account_address), - calldata: recursive_function_calldata(&contract_address, 0, true), - ..recursion_base_args.clone() - }, - ) + let result = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + nonce: nonce_manager.next(account_address), + calldata: recursive_function_calldata(&contract_address, 0, true), + ..recursion_base_args.clone() + }) .unwrap(); // Ensure the transaction was reverted. assert!(result.is_reverted()); @@ -934,15 +878,11 @@ fn test_n_reverted_steps( let actual_fee_0 = result.receipt.fee.0; // Invoke the `recursive_fail` function with 1 iterations. This call should fail. - let result = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - nonce: nonce_manager.next(account_address), - calldata: recursive_function_calldata(&contract_address, 1, true), - ..recursion_base_args.clone() - }, - ) + let result = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + nonce: nonce_manager.next(account_address), + calldata: recursive_function_calldata(&contract_address, 1, true), + ..recursion_base_args.clone() + }) .unwrap(); // Ensure the transaction was reverted. assert!(result.is_reverted()); @@ -951,15 +891,11 @@ fn test_n_reverted_steps( let actual_fee_1 = result.receipt.fee.0; // Invoke the `recursive_fail` function with 2 iterations. This call should fail. - let result = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - nonce: nonce_manager.next(account_address), - calldata: recursive_function_calldata(&contract_address, 2, true), - ..recursion_base_args.clone() - }, - ) + let result = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + nonce: nonce_manager.next(account_address), + calldata: recursive_function_calldata(&contract_address, 2, true), + ..recursion_base_args.clone() + }) .unwrap(); let n_steps_2 = result.receipt.resources.computation.total_charged_steps(); let actual_fee_2 = result.receipt.fee.0; @@ -983,15 +919,11 @@ fn test_n_reverted_steps( actual_resources_0.vm_resources.n_steps = n_steps_0; // Invoke the `recursive_fail` function with 100 iterations. This call should fail. - let result = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - nonce: nonce_manager.next(account_address), - calldata: recursive_function_calldata(&contract_address, 100, true), - ..recursion_base_args - }, - ) + let result = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + nonce: nonce_manager.next(account_address), + calldata: recursive_function_calldata(&contract_address, 100, true), + ..recursion_base_args + }) .unwrap(); let n_steps_100 = result.receipt.resources.computation.total_charged_steps(); let actual_fee_100 = result.receipt.fee.0; @@ -1156,16 +1088,12 @@ fn test_insufficient_max_fee_reverts( }; // Invoke the `recurse` function with depth 1 and MAX_FEE. This call should succeed. - let tx_execution_info1 = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - resource_bounds, - nonce: nonce_manager.next(account_address), - calldata: recursive_function_calldata(&contract_address, 1, false), - ..recursion_base_args.clone() - }, - ) + let tx_execution_info1 = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + resource_bounds, + nonce: nonce_manager.next(account_address), + calldata: recursive_function_calldata(&contract_address, 1, false), + ..recursion_base_args.clone() + }) .unwrap(); assert!(!tx_execution_info1.is_reverted()); @@ -1183,16 +1111,12 @@ fn test_insufficient_max_fee_reverts( &block_context.block_info.gas_prices.strk_gas_prices, ), }; - let tx_execution_info2 = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - resource_bounds: resource_used_depth1, - nonce: nonce_manager.next(account_address), - calldata: recursive_function_calldata(&contract_address, 2, false), - ..recursion_base_args.clone() - }, - ) + let tx_execution_info2 = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + resource_bounds: resource_used_depth1, + nonce: nonce_manager.next(account_address), + calldata: recursive_function_calldata(&contract_address, 2, false), + ..recursion_base_args.clone() + }) .unwrap(); // In the L1 gas bounds case, due to resource limit being estimated by steps, the execution // will not fail due to insufficient resources; there are not enough steps in execution to hit @@ -1208,25 +1132,23 @@ fn test_insufficient_max_fee_reverts( // snapping to bounds). assert_eq!(tx_execution_info2.receipt.da_gas, tx_execution_info1.receipt.da_gas); assert_eq!(tx_execution_info2.receipt.fee, tx_execution_info1.receipt.fee); - assert!(tx_execution_info2 - .revert_error - .unwrap() - .to_string() - .contains(&format!("Insufficient max {overdraft_resource}"))); + assert!( + tx_execution_info2 + .revert_error + .unwrap() + .to_string() + .contains(&format!("Insufficient max {overdraft_resource}")) + ); // Invoke the `recurse` function with depth of 824 and the actual fee of depth 1 as max_fee. // This call should fail due to no remaining steps (execution steps based on max_fee are bounded // well enough to catch this mid-execution). - let tx_execution_info3 = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - resource_bounds: resource_used_depth1, - nonce: nonce_manager.next(account_address), - calldata: recursive_function_calldata(&contract_address, 824, false), - ..recursion_base_args - }, - ) + let tx_execution_info3 = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + resource_bounds: resource_used_depth1, + nonce: nonce_manager.next(account_address), + calldata: recursive_function_calldata(&contract_address, 824, false), + ..recursion_base_args + }) .unwrap(); assert!(tx_execution_info3.is_reverted()); assert_eq!(tx_execution_info3.receipt.da_gas, tx_execution_info1.receipt.da_gas); @@ -1314,11 +1236,11 @@ fn test_count_actual_storage_changes( create_calldata(contract_address, "test_count_actual_storage_changes", &[]); let recipient = 435_u16; let transfer_amount: Felt = 1.into(); - let transfer_calldata = create_calldata( - fee_token_address, - TRANSFER_ENTRY_POINT_NAME, - &[felt!(recipient), transfer_amount, felt!(0_u8)], - ); + let transfer_calldata = create_calldata(fee_token_address, TRANSFER_ENTRY_POINT_NAME, &[ + felt!(recipient), + transfer_amount, + felt!(0_u8), + ]); // Run transactions; using transactional state to count only storage changes of the current // transaction. @@ -1525,11 +1447,11 @@ fn test_concurrency_execute_fee_transfer( // Case 2: The transaction read from and write to the sequenser balance before executing fee // transfer. - let transfer_calldata = create_calldata( - fee_token_address, - TRANSFER_ENTRY_POINT_NAME, - &[*block_context.block_info.sequencer_address.0.key(), felt!(TRANSFER_AMOUNT), felt!(0_u8)], - ); + let transfer_calldata = create_calldata(fee_token_address, TRANSFER_ENTRY_POINT_NAME, &[ + *block_context.block_info.sequencer_address.0.key(), + felt!(TRANSFER_AMOUNT), + felt!(0_u8), + ]); // Set the sequencer balance to a constant value to check that the read set did not changed. fund_account( @@ -1750,11 +1672,13 @@ fn test_revert_in_execute( let tx_execution_info = account_tx.execute(state, &block_context).unwrap(); assert!(tx_execution_info.is_reverted()); - assert!(tx_execution_info - .revert_error - .unwrap() - .to_string() - .contains("Failed to deserialize param #1")); + assert!( + tx_execution_info + .revert_error + .unwrap() + .to_string() + .contains("Failed to deserialize param #1") + ); } #[rstest] @@ -1801,14 +1725,10 @@ fn test_call_contract_that_panics( ), nonce: nonce_manager.next(account_address) }; - let tx_execution_info = run_invoke_tx( - state, - &block_context, - invoke_tx_args! { - resource_bounds: default_all_resource_bounds, - ..tx_args - }, - ) + let tx_execution_info = run_invoke_tx(state, &block_context, invoke_tx_args! { + resource_bounds: default_all_resource_bounds, + ..tx_args + }) .unwrap(); // If reverts are enabled, `test_call_contract_revert` should catch it and ignore it. diff --git a/crates/blockifier/src/transaction/errors.rs b/crates/blockifier/src/transaction/errors.rs index e166d1ad65..98db87b154 100644 --- a/crates/blockifier/src/transaction/errors.rs +++ b/crates/blockifier/src/transaction/errors.rs @@ -1,18 +1,18 @@ use cairo_vm::types::errors::program_errors::ProgramError; use num_bigint::BigUint; +use starknet_api::StarknetApiError; use starknet_api::block::GasPrice; use starknet_api::core::{ClassHash, ContractAddress, EntryPointSelector, Nonce}; use starknet_api::execution_resources::GasAmount; -use starknet_api::transaction::fields::{AllResourceBounds, Fee, Resource}; use starknet_api::transaction::TransactionVersion; -use starknet_api::StarknetApiError; +use starknet_api::transaction::fields::{AllResourceBounds, Fee, Resource}; use starknet_types_core::felt::FromStrError; use thiserror::Error; use crate::bouncer::BouncerWeights; use crate::execution::call_info::Retdata; use crate::execution::errors::{ConstructorEntryPointExecutionError, EntryPointExecutionError}; -use crate::execution::stack_trace::{gen_tx_execution_error_trace, Cairo1RevertSummary}; +use crate::execution::stack_trace::{Cairo1RevertSummary, gen_tx_execution_error_trace}; use crate::fee::fee_checks::FeeCheckError; use crate::state::errors::StateError; diff --git a/crates/blockifier/src/transaction/execution_flavors_test.rs b/crates/blockifier/src/transaction/execution_flavors_test.rs index 1301213098..aaf61daa2a 100644 --- a/crates/blockifier/src/transaction/execution_flavors_test.rs +++ b/crates/blockifier/src/transaction/execution_flavors_test.rs @@ -4,12 +4,12 @@ use rstest::rstest; use starknet_api::block::FeeType; use starknet_api::core::ContractAddress; use starknet_api::execution_resources::{GasAmount, GasVector}; -use starknet_api::test_utils::invoke::{executable_invoke_tx, InvokeTxArgs}; use starknet_api::test_utils::NonceManager; +use starknet_api::test_utils::invoke::{InvokeTxArgs, executable_invoke_tx}; +use starknet_api::transaction::TransactionVersion; use starknet_api::transaction::fields::{ Calldata, Fee, GasVectorComputationMode, Resource, TransactionSignature, ValidResourceBounds, }; -use starknet_api::transaction::TransactionVersion; use starknet_api::{felt, invoke_tx_args, nonce}; use starknet_types_core::felt::Felt; @@ -22,8 +22,8 @@ use crate::test_utils::contracts::FeatureContract; use crate::test_utils::dict_state_reader::DictStateReader; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::{ + BALANCE, CairoVersion, DEFAULT_L1_GAS_AMOUNT, DEFAULT_STRK_L1_GAS_PRICE, MAX_FEE, create_calldata, create_trivial_calldata, get_syscall_resources, get_tx_resources, - CairoVersion, BALANCE, DEFAULT_L1_GAS_AMOUNT, DEFAULT_STRK_L1_GAS_PRICE, MAX_FEE, }; use crate::transaction::account_transaction::{AccountTransaction, ExecutionFlags}; use crate::transaction::errors::{ @@ -31,7 +31,7 @@ use crate::transaction::errors::{ }; use crate::transaction::objects::{TransactionExecutionInfo, TransactionExecutionResult}; use crate::transaction::test_utils::{ - default_l1_resource_bounds, invoke_tx_with_default_flags, l1_resource_bounds, INVALID, + INVALID, default_l1_resource_bounds, invoke_tx_with_default_flags, l1_resource_bounds, }; use crate::transaction::transaction_types::TransactionType; use crate::transaction::transactions::ExecutableTransaction; @@ -54,11 +54,11 @@ fn create_flavors_test_state( let test_contract = FeatureContract::TestContract(cairo_version); let account_contract = FeatureContract::AccountWithoutValidations(cairo_version); let faulty_account_contract = FeatureContract::FaultyAccount(cairo_version); - let state = test_state( - chain_info, - BALANCE, - &[(account_contract, 1), (faulty_account_contract, 1), (test_contract, 1)], - ); + let state = test_state(chain_info, BALANCE, &[ + (account_contract, 1), + (faulty_account_contract, 1), + (test_contract, 1), + ]); FlavorTestInitialState { state, account_address: account_contract.get_instance_address(0), @@ -156,11 +156,9 @@ fn check_gas_and_fee( } fn recurse_calldata(contract_address: ContractAddress, fail: bool, depth: u32) -> Calldata { - create_calldata( - contract_address, - if fail { "recursive_fail" } else { "recurse" }, - &[felt!(depth)], - ) + create_calldata(contract_address, if fail { "recursive_fail" } else { "recurse" }, &[felt!( + depth + )]) } // Helper function to get the arguments for the pre-validation tests. @@ -479,17 +477,19 @@ fn test_simulate_charge_fee_with_validation_fail_validate( default_l1_resource_bounds: ValidResourceBounds, ) { let validate = true; - assert!(execute_fail_validation( - only_query, - validate, - charge_fee, - cairo_version, - version, - default_l1_resource_bounds, - ) - .unwrap_err() - .to_string() - .contains("An ASSERT_EQ instruction failed: 1 != 0.")); + assert!( + execute_fail_validation( + only_query, + validate, + charge_fee, + cairo_version, + version, + default_l1_resource_bounds, + ) + .unwrap_err() + .to_string() + .contains("An ASSERT_EQ instruction failed: 1 != 0.") + ); } /// Test gas and fee with simulate / charge_fee flag combinations in (fallible) validation stage, @@ -641,12 +641,14 @@ fn test_simulate_validate_charge_fee_mid_execution( let tx_execution_info = account_tx.execute(&mut state, &block_context).unwrap(); assert_eq!(tx_execution_info.is_reverted(), charge_fee); if charge_fee { - assert!(tx_execution_info - .revert_error - .clone() - .unwrap() - .to_string() - .contains("no remaining steps")); + assert!( + tx_execution_info + .revert_error + .clone() + .unwrap() + .to_string() + .contains("no remaining steps") + ); } check_gas_and_fee( &block_context, @@ -694,12 +696,9 @@ fn test_simulate_validate_charge_fee_mid_execution( execution_flags: ExecutionFlags { only_query, charge_fee, validate }, }; let tx_execution_info = account_tx.execute(&mut state, &low_step_block_context).unwrap(); - assert!(tx_execution_info - .revert_error - .clone() - .unwrap() - .to_string() - .contains("no remaining steps")); + assert!( + tx_execution_info.revert_error.clone().unwrap().to_string().contains("no remaining steps") + ); // Complete resources used are reported as receipt.resources; but only the charged // final fee is shown in actual_fee. As a sanity check, verify that the fee derived directly // from the consumed resources is also equal to the expected fee. @@ -826,15 +825,11 @@ fn test_simulate_validate_charge_fee_post_execution( assert!(felt!(actual_fee.0) < current_balance); let transfer_amount = current_balance - Felt::from(actual_fee.0 / 2); let recipient = felt!(7_u8); - let transfer_calldata = create_calldata( - fee_token_address, - "transfer", - &[ - recipient, // Calldata: to. - transfer_amount, - felt!(0_u8), - ], - ); + let transfer_calldata = create_calldata(fee_token_address, "transfer", &[ + recipient, // Calldata: to. + transfer_amount, + felt!(0_u8), + ]); let tx = executable_invoke_tx(invoke_tx_args! { max_fee: actual_fee, resource_bounds: l1_resource_bounds(success_actual_gas, gas_price.into()), @@ -851,12 +846,14 @@ fn test_simulate_validate_charge_fee_post_execution( assert_eq!(tx_execution_info.is_reverted(), charge_fee); if charge_fee { - assert!(tx_execution_info - .revert_error - .clone() - .unwrap() - .to_string() - .contains("Insufficient fee token balance.")); + assert!( + tx_execution_info + .revert_error + .clone() + .unwrap() + .to_string() + .contains("Insufficient fee token balance.") + ); } check_gas_and_fee( &block_context, diff --git a/crates/blockifier/src/transaction/objects.rs b/crates/blockifier/src/transaction/objects.rs index 1d450514e4..8a294c731b 100644 --- a/crates/blockifier/src/transaction/objects.rs +++ b/crates/blockifier/src/transaction/objects.rs @@ -11,7 +11,7 @@ use starknet_api::transaction::fields::{ ResourceBounds, Tip, TransactionSignature, ValidResourceBounds, }; use starknet_api::transaction::{ - signed_tx_version, TransactionHash, TransactionOptions, TransactionVersion, + TransactionHash, TransactionOptions, TransactionVersion, signed_tx_version, }; use crate::abi::constants as abi_constants; diff --git a/crates/blockifier/src/transaction/post_execution_test.rs b/crates/blockifier/src/transaction/post_execution_test.rs index 1a85386b6e..e85a349fbe 100644 --- a/crates/blockifier/src/transaction/post_execution_test.rs +++ b/crates/blockifier/src/transaction/post_execution_test.rs @@ -4,11 +4,11 @@ use starknet_api::block::FeeType; use starknet_api::core::ContractAddress; use starknet_api::execution_resources::GasAmount; use starknet_api::state::StorageKey; +use starknet_api::transaction::TransactionVersion; use starknet_api::transaction::fields::{ AllResourceBounds, Calldata, Fee, GasVectorComputationMode, Resource, ResourceBounds, ValidResourceBounds, }; -use starknet_api::transaction::TransactionVersion; use starknet_api::{contract_address, felt, invoke_tx_args}; use starknet_types_core::felt::Felt; @@ -18,16 +18,16 @@ use crate::state::state_api::StateReader; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::{ - create_calldata, CairoVersion, BALANCE, DEFAULT_STRK_L1_DATA_GAS_PRICE, - DEFAULT_STRK_L1_GAS_PRICE, DEFAULT_STRK_L2_GAS_PRICE, + BALANCE, CairoVersion, DEFAULT_STRK_L1_DATA_GAS_PRICE, DEFAULT_STRK_L1_GAS_PRICE, + DEFAULT_STRK_L2_GAS_PRICE, create_calldata, }; use crate::transaction::account_transaction::AccountTransaction; use crate::transaction::errors::TransactionExecutionError; use crate::transaction::objects::{HasRelatedFeeType, TransactionInfoCreator}; use crate::transaction::test_utils::{ - block_context, create_all_resource_bounds, default_all_resource_bounds, + TestInitData, block_context, create_all_resource_bounds, default_all_resource_bounds, default_l1_resource_bounds, invoke_tx_with_default_flags, l1_resource_bounds, max_fee, - run_invoke_tx, TestInitData, + run_invoke_tx, }; use crate::transaction::transactions::ExecutableTransaction; use crate::versioned_constants::AllocationCost; @@ -52,17 +52,13 @@ fn calldata_for_write_and_transfer( transfer_amount: Felt, fee_token_address: ContractAddress, ) -> Calldata { - create_calldata( - test_contract_address, - "test_write_and_transfer", - &[ - storage_address, // Calldata: storage address. - storage_value, // Calldata: storage value. - recipient, // Calldata: to. - transfer_amount, // Calldata: amount. - *fee_token_address.0.key(), // Calldata: fee token address. - ], - ) + create_calldata(test_contract_address, "test_write_and_transfer", &[ + storage_address, // Calldata: storage address. + storage_value, // Calldata: storage value. + recipient, // Calldata: to. + transfer_amount, // Calldata: amount. + *fee_token_address.0.key(), // Calldata: fee token address. + ]) } /// Tests that when a transaction drains an account's balance before fee transfer, the execution is @@ -100,15 +96,11 @@ fn test_revert_on_overdraft( assert_eq!(state.get_storage_at(contract_address, storage_key).unwrap(), felt!(0_u8)); // Approve the test contract to transfer funds. - let approve_calldata = create_calldata( - fee_token_address, - "approve", - &[ - *contract_address.0.key(), // Calldata: to. - felt!(BALANCE.0), - felt!(0_u8), - ], - ); + let approve_calldata = create_calldata(fee_token_address, "approve", &[ + *contract_address.0.key(), // Calldata: to. + felt!(BALANCE.0), + felt!(0_u8), + ]); let approve_tx: AccountTransaction = invoke_tx_with_default_flags(invoke_tx_args! { max_fee, @@ -124,25 +116,21 @@ fn test_revert_on_overdraft( // Transfer a valid amount of funds to compute the cost of a successful // `test_write_and_transfer` operation. This operation should succeed. - let execution_info = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - max_fee, - sender_address: account_address, - calldata: calldata_for_write_and_transfer( - contract_address, - storage_address, - expected_final_value, - recipient, - final_received_amount, - fee_token_address - ), - version, - resource_bounds: default_all_resource_bounds, - nonce: nonce_manager.next(account_address), - }, - ) + let execution_info = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + max_fee, + sender_address: account_address, + calldata: calldata_for_write_and_transfer( + contract_address, + storage_address, + expected_final_value, + recipient, + final_received_amount, + fee_token_address + ), + version, + resource_bounds: default_all_resource_bounds, + nonce: nonce_manager.next(account_address), + }) .unwrap(); assert!(!execution_info.is_reverted()); @@ -155,25 +143,21 @@ fn test_revert_on_overdraft( // Attempt to transfer the entire balance, such that no funds remain to pay transaction fee. // This operation should revert. - let execution_info = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - max_fee, - sender_address: account_address, - calldata: calldata_for_write_and_transfer( - contract_address, - storage_address, - felt!(0_u8), - recipient, - balance, - fee_token_address - ), - version, - resource_bounds: default_all_resource_bounds, - nonce: nonce_manager.next(account_address), - }, - ) + let execution_info = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + max_fee, + sender_address: account_address, + calldata: calldata_for_write_and_transfer( + contract_address, + storage_address, + felt!(0_u8), + recipient, + balance, + fee_token_address + ), + version, + resource_bounds: default_all_resource_bounds, + nonce: nonce_manager.next(account_address), + }) .unwrap(); // Compute the expected balance after the reverted write+transfer (tx fee should be charged). @@ -181,11 +165,13 @@ fn test_revert_on_overdraft( // Verify the execution was reverted (including nonce bump) with the correct error. assert!(execution_info.is_reverted()); - assert!(execution_info - .revert_error - .unwrap() - .to_string() - .starts_with("Insufficient fee token balance")); + assert!( + execution_info + .revert_error + .unwrap() + .to_string() + .starts_with("Insufficient fee token balance") + ); assert_eq!(state.get_nonce_at(account_address).unwrap(), nonce_manager.next(account_address)); // Verify the storage key/value were not updated in the last tx. @@ -275,17 +261,13 @@ fn test_revert_on_resource_overuse( // We need this kind of invocation, to be able to test the specific scenario: the resource // bounds must be enough to allow completion of the transaction, and yet must still fail // post-execution bounds check. - let mut execution_info_measure = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - max_fee, - resource_bounds, - nonce: nonce_manager.next(account_address), - calldata: write_a_lot_calldata(), - ..base_args.clone() - }, - ) + let mut execution_info_measure = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + max_fee, + resource_bounds, + nonce: nonce_manager.next(account_address), + calldata: write_a_lot_calldata(), + ..base_args.clone() + }) .unwrap(); assert_eq!(execution_info_measure.revert_error, None); @@ -309,17 +291,13 @@ fn test_revert_on_resource_overuse( // Run the same function, with a different written value (to keep cost high), with the actual // resources used as upper bounds. Make sure execution does not revert. - let execution_info_tight = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - max_fee: actual_fee, - resource_bounds: tight_resource_bounds, - nonce: nonce_manager.next(account_address), - calldata: write_a_lot_calldata(), - ..base_args.clone() - }, - ) + let execution_info_tight = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + max_fee: actual_fee, + resource_bounds: tight_resource_bounds, + nonce: nonce_manager.next(account_address), + calldata: write_a_lot_calldata(), + ..base_args.clone() + }) .unwrap(); assert_eq!(execution_info_tight.revert_error, None); assert_eq!(execution_info_tight.receipt.fee, actual_fee); @@ -368,17 +346,13 @@ fn test_revert_on_resource_overuse( } } }; - let execution_info_result = run_invoke_tx( - &mut state, - &block_context, - invoke_tx_args! { - max_fee: low_max_fee, - resource_bounds: low_bounds, - nonce: nonce_manager.next(account_address), - calldata: write_a_lot_calldata(), - ..base_args - }, - ); + let execution_info_result = run_invoke_tx(&mut state, &block_context, invoke_tx_args! { + max_fee: low_max_fee, + resource_bounds: low_bounds, + nonce: nonce_manager.next(account_address), + calldata: write_a_lot_calldata(), + ..base_args + }); // Assert the transaction was reverted with the correct error. let expected_error_prefix = if version == TransactionVersion::ZERO { @@ -390,12 +364,14 @@ fn test_revert_on_resource_overuse( &format!("Insufficient max {}", resource_to_decrement.unwrap()) }; if is_revertible { - assert!(execution_info_result - .unwrap() - .revert_error - .unwrap() - .to_string() - .starts_with(expected_error_prefix)); + assert!( + execution_info_result + .unwrap() + .revert_error + .unwrap() + .to_string() + .starts_with(expected_error_prefix) + ); } else { assert_matches!( execution_info_result.unwrap_err(), diff --git a/crates/blockifier/src/transaction/test_utils.rs b/crates/blockifier/src/transaction/test_utils.rs index 8eb560d3f7..97773b6244 100644 --- a/crates/blockifier/src/transaction/test_utils.rs +++ b/crates/blockifier/src/transaction/test_utils.rs @@ -4,15 +4,15 @@ use starknet_api::block::{FeeType, GasPrice}; use starknet_api::contract_class::{ClassInfo, ContractClass, SierraVersion}; use starknet_api::core::{ClassHash, ContractAddress, Nonce}; use starknet_api::execution_resources::GasAmount; -use starknet_api::test_utils::declare::executable_declare_tx; -use starknet_api::test_utils::deploy_account::{executable_deploy_account_tx, DeployAccountTxArgs}; -use starknet_api::test_utils::invoke::{executable_invoke_tx, InvokeTxArgs}; use starknet_api::test_utils::NonceManager; +use starknet_api::test_utils::declare::executable_declare_tx; +use starknet_api::test_utils::deploy_account::{DeployAccountTxArgs, executable_deploy_account_tx}; +use starknet_api::test_utils::invoke::{InvokeTxArgs, executable_invoke_tx}; use starknet_api::transaction::fields::{ AllResourceBounds, ContractAddressSalt, Fee, GasVectorComputationMode, ResourceBounds, TransactionSignature, ValidResourceBounds, }; -use starknet_api::transaction::{constants, TransactionVersion}; +use starknet_api::transaction::{TransactionVersion, constants}; use starknet_api::{calldata, declare_tx_args, deploy_account_tx_args, felt, invoke_tx_args}; use starknet_types_core::felt::Felt; use strum::IntoEnumIterator; @@ -24,9 +24,9 @@ use crate::test_utils::contracts::FeatureContract; use crate::test_utils::dict_state_reader::DictStateReader; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::{ - create_calldata, CairoVersion, BALANCE, DEFAULT_L1_DATA_GAS_MAX_AMOUNT, DEFAULT_L1_GAS_AMOUNT, + BALANCE, CairoVersion, DEFAULT_L1_DATA_GAS_MAX_AMOUNT, DEFAULT_L1_GAS_AMOUNT, DEFAULT_L2_GAS_MAX_AMOUNT, DEFAULT_STRK_L1_DATA_GAS_PRICE, DEFAULT_STRK_L1_GAS_PRICE, - DEFAULT_STRK_L2_GAS_PRICE, MAX_FEE, + DEFAULT_STRK_L2_GAS_PRICE, MAX_FEE, create_calldata, }; use crate::transaction::account_transaction::{AccountTransaction, ExecutionFlags}; use crate::transaction::objects::{TransactionExecutionInfo, TransactionExecutionResult}; diff --git a/crates/blockifier/src/transaction/transaction_execution.rs b/crates/blockifier/src/transaction/transaction_execution.rs index 312cfbbf4f..143ed563b3 100644 --- a/crates/blockifier/src/transaction/transaction_execution.rs +++ b/crates/blockifier/src/transaction/transaction_execution.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use starknet_api::contract_class::ClassInfo; -use starknet_api::core::{calculate_contract_address, ContractAddress, Nonce}; +use starknet_api::core::{ContractAddress, Nonce, calculate_contract_address}; use starknet_api::executable_transaction::{ AccountTransaction as ApiExecutableTransaction, DeclareTransaction, DeployAccountTransaction, InvokeTransaction, L1HandlerTransaction, diff --git a/crates/blockifier/src/transaction/transactions.rs b/crates/blockifier/src/transaction/transactions.rs index e3f00ed3dd..bb7faa2bb7 100644 --- a/crates/blockifier/src/transaction/transactions.rs +++ b/crates/blockifier/src/transaction/transactions.rs @@ -11,7 +11,7 @@ use starknet_api::transaction::fields::{ AccountDeploymentData, Calldata, Fee, TransactionSignature, }; use starknet_api::transaction::{ - constants, DeclareTransactionV2, DeclareTransactionV3, TransactionVersion, + DeclareTransactionV2, DeclareTransactionV3, TransactionVersion, constants, }; use crate::context::{BlockContext, TransactionContext}; diff --git a/crates/blockifier/src/transaction/transactions_test.rs b/crates/blockifier/src/transaction/transactions_test.rs index 1bf7266837..9c508c7fdd 100644 --- a/crates/blockifier/src/transaction/transactions_test.rs +++ b/crates/blockifier/src/transaction/transactions_test.rs @@ -17,18 +17,18 @@ use starknet_api::core::{ChainId, ClassHash, ContractAddress, EthAddress, Nonce} use starknet_api::executable_transaction::AccountTransaction as ApiExecutableTransaction; use starknet_api::execution_resources::{GasAmount, GasVector}; use starknet_api::state::StorageKey; +use starknet_api::test_utils::NonceManager; use starknet_api::test_utils::declare::executable_declare_tx; use starknet_api::test_utils::deploy_account::executable_deploy_account_tx; -use starknet_api::test_utils::invoke::{executable_invoke_tx, InvokeTxArgs}; -use starknet_api::test_utils::NonceManager; +use starknet_api::test_utils::invoke::{InvokeTxArgs, executable_invoke_tx}; use starknet_api::transaction::fields::Resource::{L1DataGas, L1Gas, L2Gas}; use starknet_api::transaction::fields::{ AllResourceBounds, Calldata, Fee, GasVectorComputationMode, Resource, ResourceBounds, TransactionSignature, ValidResourceBounds, }; use starknet_api::transaction::{ - constants, EventContent, EventData, EventKey, L2ToL1Payload, TransactionVersion, - QUERY_VERSION_BASE, + EventContent, EventData, EventKey, L2ToL1Payload, QUERY_VERSION_BASE, TransactionVersion, + constants, }; use starknet_api::{ calldata, class_hash, contract_address, declare_tx_args, deploy_account_tx_args, felt, @@ -45,8 +45,8 @@ use crate::execution::call_info::{ use crate::execution::contract_class::TrackedResource; use crate::execution::entry_point::{CallEntryPoint, CallType}; use crate::execution::errors::{ConstructorEntryPointExecutionError, EntryPointExecutionError}; -use crate::execution::syscalls::hint_processor::EmitEventError; use crate::execution::syscalls::SyscallSelector; +use crate::execution::syscalls::hint_processor::EmitEventError; use crate::fee::fee_utils::{balance_to_big_uint, get_fee_by_gas_vector}; use crate::fee::gas_usage::{ estimate_minimal_gas_vector, get_da_gas_cost, get_onchain_data_segment_length, @@ -64,12 +64,12 @@ use crate::test_utils::initial_test_state::test_state; use crate::test_utils::l1_handler::l1handler_tx; use crate::test_utils::prices::Prices; use crate::test_utils::{ - create_calldata, create_trivial_calldata, get_syscall_resources, get_tx_resources, - test_erc20_sequencer_balance_key, CairoVersion, RunnableCairo1, SaltManager, BALANCE, - CURRENT_BLOCK_NUMBER, CURRENT_BLOCK_NUMBER_FOR_VALIDATE, CURRENT_BLOCK_TIMESTAMP, - CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE, DEFAULT_L1_DATA_GAS_MAX_AMOUNT, DEFAULT_L1_GAS_AMOUNT, - DEFAULT_L2_GAS_MAX_AMOUNT, DEFAULT_STRK_L1_DATA_GAS_PRICE, DEFAULT_STRK_L1_GAS_PRICE, - DEFAULT_STRK_L2_GAS_PRICE, MAX_FEE, TEST_SEQUENCER_ADDRESS, + BALANCE, CURRENT_BLOCK_NUMBER, CURRENT_BLOCK_NUMBER_FOR_VALIDATE, CURRENT_BLOCK_TIMESTAMP, + CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE, CairoVersion, DEFAULT_L1_DATA_GAS_MAX_AMOUNT, + DEFAULT_L1_GAS_AMOUNT, DEFAULT_L2_GAS_MAX_AMOUNT, DEFAULT_STRK_L1_DATA_GAS_PRICE, + DEFAULT_STRK_L1_GAS_PRICE, DEFAULT_STRK_L2_GAS_PRICE, MAX_FEE, RunnableCairo1, SaltManager, + TEST_SEQUENCER_ADDRESS, create_calldata, create_trivial_calldata, get_syscall_resources, + get_tx_resources, test_erc20_sequencer_balance_key, }; use crate::transaction::account_transaction::{AccountTransaction, ExecutionFlags}; use crate::transaction::errors::{ @@ -79,12 +79,12 @@ use crate::transaction::objects::{ HasRelatedFeeType, TransactionExecutionInfo, TransactionInfo, TransactionInfoCreator, }; use crate::transaction::test_utils::{ - block_context, calculate_class_info_for_testing, create_account_tx_for_validate_test, + CALL_CONTRACT, FaultyAccountTxCreatorArgs, GET_BLOCK_HASH, GET_BLOCK_NUMBER, + GET_BLOCK_TIMESTAMP, GET_EXECUTION_INFO, GET_SEQUENCER_ADDRESS, INVALID, VALID, block_context, + calculate_class_info_for_testing, create_account_tx_for_validate_test, create_account_tx_for_validate_test_nonce_0, create_all_resource_bounds, default_all_resource_bounds, default_l1_resource_bounds, invoke_tx_with_default_flags, - l1_resource_bounds, FaultyAccountTxCreatorArgs, CALL_CONTRACT, GET_BLOCK_HASH, - GET_BLOCK_NUMBER, GET_BLOCK_TIMESTAMP, GET_EXECUTION_INFO, GET_SEQUENCER_ADDRESS, INVALID, - VALID, + l1_resource_bounds, }; use crate::transaction::transaction_types::TransactionType; use crate::transaction::transactions::ExecutableTransaction; @@ -146,19 +146,11 @@ fn expected_validate_call_info( usize::from(entry_point_selector_name == constants::VALIDATE_ENTRY_POINT_NAME) } CairoVersion::Cairo1(RunnableCairo1::Casm) => { - if entry_point_selector_name == constants::VALIDATE_ENTRY_POINT_NAME { - 7 - } else { - 2 - } + if entry_point_selector_name == constants::VALIDATE_ENTRY_POINT_NAME { 7 } else { 2 } } #[cfg(feature = "cairo_native")] CairoVersion::Cairo1(RunnableCairo1::Native) => { - if entry_point_selector_name == constants::VALIDATE_ENTRY_POINT_NAME { - 7 - } else { - 2 - } + if entry_point_selector_name == constants::VALIDATE_ENTRY_POINT_NAME { 7 } else { 2 } } }; let n_steps = match (entry_point_selector_name, cairo_version) { @@ -919,11 +911,10 @@ fn test_max_fee_exceeds_balance( let block_context = &block_context; let account_contract = FeatureContract::AccountWithoutValidations(account_cairo_version); let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); - let state = &mut test_state( - &block_context.chain_info, - BALANCE, - &[(account_contract, 1), (test_contract, 1)], - ); + let state = &mut test_state(&block_context.chain_info, BALANCE, &[ + (account_contract, 1), + (test_contract, 1), + ]); let sender_address = account_contract.get_instance_address(0); let default_invoke_args = invoke_tx_args! { sender_address, @@ -1031,11 +1022,10 @@ fn test_insufficient_new_resource_bounds_pre_validation( let block_context = &block_context; let account_contract = FeatureContract::AccountWithoutValidations(account_cairo_version); let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); - let state = &mut test_state( - &block_context.chain_info, - BALANCE, - &[(account_contract, 1), (test_contract, 1)], - ); + let state = &mut test_state(&block_context.chain_info, BALANCE, &[ + (account_contract, 1), + (test_contract, 1), + ]); let valid_invoke_tx_args = invoke_tx_args! { sender_address: account_contract.get_instance_address(0), calldata: create_trivial_calldata(test_contract.get_instance_address(0)), @@ -1163,11 +1153,10 @@ fn test_insufficient_deprecated_resource_bounds_pre_validation( let block_context = &block_context; let account_contract = FeatureContract::AccountWithoutValidations(account_cairo_version); let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); - let state = &mut test_state( - &block_context.chain_info, - BALANCE, - &[(account_contract, 1), (test_contract, 1)], - ); + let state = &mut test_state(&block_context.chain_info, BALANCE, &[ + (account_contract, 1), + (test_contract, 1), + ]); let valid_invoke_tx_args = invoke_tx_args! { sender_address: account_contract.get_instance_address(0), calldata: create_trivial_calldata(test_contract.get_instance_address(0)), @@ -1261,11 +1250,10 @@ fn test_actual_fee_gt_resource_bounds( let gas_prices = &block_context.block_info.gas_prices.strk_gas_prices; let account_contract = FeatureContract::AccountWithoutValidations(account_cairo_version); let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); - let state = &mut test_state( - &block_context.chain_info, - BALANCE, - &[(account_contract, 2), (test_contract, 1)], - ); + let state = &mut test_state(&block_context.chain_info, BALANCE, &[ + (account_contract, 2), + (test_contract, 1), + ]); let sender_address0 = account_contract.get_instance_address(0); let sender_address1 = account_contract.get_instance_address(1); let tx_args = invoke_tx_args! { @@ -1317,9 +1305,9 @@ fn test_actual_fee_gt_resource_bounds( // Test error and that fee was charged. Should be at most the fee charged in a successful // execution. - assert!(execution_error - .to_string() - .starts_with(&format!("Insufficient max {overdraft_resource}"))); + assert!( + execution_error.to_string().starts_with(&format!("Insufficient max {overdraft_resource}")) + ); assert_eq!(execution_result.receipt.fee, expected_fee); } @@ -1332,11 +1320,10 @@ fn test_invalid_nonce( ) { let account_contract = FeatureContract::AccountWithoutValidations(account_cairo_version); let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); - let state = &mut test_state( - &block_context.chain_info, - BALANCE, - &[(account_contract, 1), (test_contract, 1)], - ); + let state = &mut test_state(&block_context.chain_info, BALANCE, &[ + (account_contract, 1), + (test_contract, 1), + ]); let valid_invoke_tx_args = invoke_tx_args! { sender_address: account_contract.get_instance_address(0), calldata: create_trivial_calldata(test_contract.get_instance_address(0)), @@ -1999,25 +1986,22 @@ fn test_validate_accounts_tx( // Valid logic. let nonce_manager = &mut NonceManager::default(); let declared_contract_cairo_version = CairoVersion::from_declare_tx_version(tx_version); - let account_tx = create_account_tx_for_validate_test( - nonce_manager, - FaultyAccountTxCreatorArgs { + let account_tx = + create_account_tx_for_validate_test(nonce_manager, FaultyAccountTxCreatorArgs { scenario: VALID, contract_address_salt: salt_manager.next_salt(), additional_data: None, declared_contract: Some(FeatureContract::TestContract(declared_contract_cairo_version)), resource_bounds: ValidResourceBounds::create_for_testing_no_fee_enforcement(), ..default_args - }, - ); + }); let result = account_tx.execute(state, block_context); assert!(result.is_ok(), "Execution failed: {:?}", result.unwrap_err()); if tx_type != TransactionType::DeployAccount { // Call self (allowed). - let account_tx = create_account_tx_for_validate_test( - nonce_manager, - FaultyAccountTxCreatorArgs { + let account_tx = + create_account_tx_for_validate_test(nonce_manager, FaultyAccountTxCreatorArgs { scenario: CALL_CONTRACT, additional_data: Some(vec![*sender_address.0.key()]), declared_contract: Some(FeatureContract::AccountWithLongValidate( @@ -2025,8 +2009,7 @@ fn test_validate_accounts_tx( )), resource_bounds: ValidResourceBounds::create_for_testing_no_fee_enforcement(), ..default_args - }, - ); + }); let result = account_tx.execute(state, block_context); assert!(result.is_ok(), "Execution failed: {:?}", result.unwrap_err()); } @@ -2034,9 +2017,8 @@ fn test_validate_accounts_tx( if let CairoVersion::Cairo0 = cairo_version { // Call the syscall get_block_number and assert the returned block number was modified // for validate. - let account_tx = create_account_tx_for_validate_test( - nonce_manager, - FaultyAccountTxCreatorArgs { + let account_tx = + create_account_tx_for_validate_test(nonce_manager, FaultyAccountTxCreatorArgs { scenario: GET_BLOCK_NUMBER, contract_address_salt: salt_manager.next_salt(), additional_data: Some(vec![Felt::from(CURRENT_BLOCK_NUMBER_FOR_VALIDATE)]), @@ -2045,24 +2027,21 @@ fn test_validate_accounts_tx( )), resource_bounds: ValidResourceBounds::create_for_testing_no_fee_enforcement(), ..default_args - }, - ); + }); let result = account_tx.execute(state, block_context); assert!(result.is_ok(), "Execution failed: {:?}", result.unwrap_err()); // Call the syscall get_block_timestamp and assert the returned timestamp was modified // for validate. - let account_tx = create_account_tx_for_validate_test( - nonce_manager, - FaultyAccountTxCreatorArgs { + let account_tx = + create_account_tx_for_validate_test(nonce_manager, FaultyAccountTxCreatorArgs { scenario: GET_BLOCK_TIMESTAMP, contract_address_salt: salt_manager.next_salt(), additional_data: Some(vec![Felt::from(CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE)]), declared_contract: Some(FeatureContract::Empty(declared_contract_cairo_version)), resource_bounds: ValidResourceBounds::create_for_testing_no_fee_enforcement(), ..default_args - }, - ); + }); let result = account_tx.execute(state, block_context); assert!(result.is_ok(), "Execution failed: {:?}", result.unwrap_err()); } @@ -2102,11 +2081,10 @@ fn test_valid_flag( let block_context = &block_context; let account_contract = FeatureContract::AccountWithoutValidations(account_cairo_version); let test_contract = FeatureContract::TestContract(test_contract_cairo_version); - let state = &mut test_state( - &block_context.chain_info, - BALANCE, - &[(account_contract, 1), (test_contract, 1)], - ); + let state = &mut test_state(&block_context.chain_info, BALANCE, &[ + (account_contract, 1), + (test_contract, 1), + ]); let tx = executable_invoke_tx(invoke_tx_args! { sender_address: account_contract.get_instance_address(0), @@ -2135,11 +2113,10 @@ fn test_only_query_flag( let account = FeatureContract::AccountWithoutValidations(CairoVersion::Cairo1(RunnableCairo1::Casm)); let test_contract = FeatureContract::TestContract(CairoVersion::Cairo1(RunnableCairo1::Casm)); - let state = &mut test_state( - &block_context.chain_info, - account_balance, - &[(account, 1), (test_contract, 1)], - ); + let state = &mut test_state(&block_context.chain_info, account_balance, &[ + (account, 1), + (test_contract, 1), + ]); let mut version = Felt::from(3_u8); if only_query { version += *QUERY_VERSION_BASE; @@ -2370,7 +2347,7 @@ fn test_l1_handler(#[values(false, true)] use_kzg_da: bool) { state.set_storage_at(contract_address, StorageKey::try_from(key).unwrap(), Felt::ZERO).unwrap(); let tx_no_fee = l1handler_tx(Fee(0), contract_address); let error = tx_no_fee.execute(state, block_context).unwrap_err(); // Do not charge fee as L1Handler's resource bounds (/max fee) is 0. - // Today, we check that the paid_fee is positive, no matter what was the actual fee. + // Today, we check that the paid_fee is positive, no matter what was the actual fee. let expected_actual_fee = get_fee_by_gas_vector(&block_context.block_info, total_gas, &FeeType::Eth); @@ -2395,11 +2372,10 @@ fn test_execute_tx_with_invalid_tx_version( let state = &mut test_state(&block_context.chain_info, BALANCE, &[(account, 1), (test_contract, 1)]); let invalid_version = 12345_u64; - let calldata = create_calldata( - test_contract.get_instance_address(0), - "test_tx_version", - &[felt!(invalid_version)], - ); + let calldata = + create_calldata(test_contract.get_instance_address(0), "test_tx_version", &[felt!( + invalid_version + )]); let account_tx = invoke_tx_with_default_flags(invoke_tx_args! { resource_bounds: default_all_resource_bounds, sender_address: account.get_instance_address(0), @@ -2407,11 +2383,13 @@ fn test_execute_tx_with_invalid_tx_version( }); let execution_info = account_tx.execute(state, block_context).unwrap(); - assert!(execution_info - .revert_error - .unwrap() - .to_string() - .contains(format!("ASSERT_EQ instruction failed: {} != 3.", invalid_version).as_str())); + assert!( + execution_info + .revert_error + .unwrap() + .to_string() + .contains(format!("ASSERT_EQ instruction failed: {} != 3.", invalid_version).as_str()) + ); } fn max_n_emitted_events() -> usize { @@ -2470,11 +2448,10 @@ fn test_emit_event_exceeds_limit( let account_contract = FeatureContract::AccountWithoutValidations(CairoVersion::Cairo1(RunnableCairo1::Casm)); let block_context = &block_context; - let state = &mut test_state( - &block_context.chain_info, - BALANCE, - &[(test_contract, 1), (account_contract, 1)], - ); + let state = &mut test_state(&block_context.chain_info, BALANCE, &[ + (test_contract, 1), + (account_contract, 1), + ]); let calldata = [ vec![felt!(u16::try_from(n_emitted_events).expect("Failed to convert usize to u16."))] diff --git a/crates/blockifier/src/utils_test.rs b/crates/blockifier/src/utils_test.rs index c4d123cd8e..98888db72c 100644 --- a/crates/blockifier/src/utils_test.rs +++ b/crates/blockifier/src/utils_test.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use pretty_assertions::assert_eq; -use crate::utils::{strict_subtract_mappings, subtract_mappings, STRICT_SUBTRACT_MAPPING_ERROR}; +use crate::utils::{STRICT_SUBTRACT_MAPPING_ERROR, strict_subtract_mappings, subtract_mappings}; #[test] fn test_subtract_mappings() { diff --git a/crates/blockifier/src/versioned_constants.rs b/crates/blockifier/src/versioned_constants.rs index 3fc03c463c..625174f77b 100644 --- a/crates/blockifier/src/versioned_constants.rs +++ b/crates/blockifier/src/versioned_constants.rs @@ -9,7 +9,7 @@ use indexmap::{IndexMap, IndexSet}; use infra_utils::compile_time_cargo_manifest_dir; use num_rational::Ratio; use num_traits::Inv; -use papyrus_config::dumping::{ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use paste::paste; use semver::Version; @@ -152,11 +152,7 @@ impl AllocationCost { AllocationCost { blob_cost: GasVector::ZERO, gas_cost: GasVector::ZERO }; pub fn get_cost(&self, use_kzg_da: bool) -> &GasVector { - if use_kzg_da { - &self.blob_cost - } else { - &self.gas_cost - } + if use_kzg_da { &self.blob_cost } else { &self.gas_cost } } } diff --git a/crates/blockifier/src/versioned_constants_test.rs b/crates/blockifier/src/versioned_constants_test.rs index b8518138d9..7c6f0252e8 100644 --- a/crates/blockifier/src/versioned_constants_test.rs +++ b/crates/blockifier/src/versioned_constants_test.rs @@ -1,4 +1,4 @@ -use glob::{glob, Paths}; +use glob::{Paths, glob}; use pretty_assertions::assert_eq; use super::*; diff --git a/crates/blockifier/tests/feature_contracts_compatibility_test.rs b/crates/blockifier/tests/feature_contracts_compatibility_test.rs index d89a3526d1..419f35f00c 100644 --- a/crates/blockifier/tests/feature_contracts_compatibility_test.rs +++ b/crates/blockifier/tests/feature_contracts_compatibility_test.rs @@ -1,10 +1,10 @@ use std::fs; use blockifier::test_utils::cairo_compile::{ - prepare_group_tag_compiler_deps, CompilationArtifacts, + CompilationArtifacts, prepare_group_tag_compiler_deps, }; use blockifier::test_utils::contracts::{ - FeatureContract, CAIRO1_FEATURE_CONTRACTS_DIR, SIERRA_CONTRACTS_SUBDIR, + CAIRO1_FEATURE_CONTRACTS_DIR, FeatureContract, SIERRA_CONTRACTS_SUBDIR, }; use blockifier::test_utils::{CairoVersion, RunnableCairo1}; use pretty_assertions::assert_eq; diff --git a/crates/blockifier_reexecution/src/main.rs b/crates/blockifier_reexecution/src/main.rs index 2cdc9b346c..2328aa6e65 100644 --- a/crates/blockifier_reexecution/src/main.rs +++ b/crates/blockifier_reexecution/src/main.rs @@ -4,8 +4,8 @@ use std::path::Path; use blockifier_reexecution::state_reader::offline_state_reader::OfflineConsecutiveStateReaders; use blockifier_reexecution::state_reader::test_state_reader::ConsecutiveTestStateReaders; use blockifier_reexecution::state_reader::utils::{ - get_block_numbers_for_reexecution, guess_chain_id_from_node_url, - reexecute_and_verify_correctness, write_block_reexecution_data_to_file, JSON_RPC_VERSION, + JSON_RPC_VERSION, get_block_numbers_for_reexecution, guess_chain_id_from_node_url, + reexecute_and_verify_correctness, write_block_reexecution_data_to_file, }; use clap::{Args, Parser, Subcommand}; use google_cloud_storage::client::{Client, ClientConfig}; @@ -307,7 +307,9 @@ async fn main() { .unwrap(); } - println!("All blocks uploaded successfully to https://console.cloud.google.com/storage/browser/{BUCKET}/{files_prefix}."); + println!( + "All blocks uploaded successfully to https://console.cloud.google.com/storage/browser/{BUCKET}/{files_prefix}." + ); } Command::DownloadFiles { block_numbers, directory_path } => { diff --git a/crates/blockifier_reexecution/src/state_reader/offline_state_reader.rs b/crates/blockifier_reexecution/src/state_reader/offline_state_reader.rs index 080e043581..e93d4ce969 100644 --- a/crates/blockifier_reexecution/src/state_reader/offline_state_reader.rs +++ b/crates/blockifier_reexecution/src/state_reader/offline_state_reader.rs @@ -25,7 +25,7 @@ use crate::state_reader::reexecution_state_reader::{ ConsecutiveReexecutionStateReaders, ReexecutionStateReader, }; use crate::state_reader::test_state_reader::StarknetContractClassMapping; -use crate::state_reader::utils::{get_chain_info, ReexecutionStateMaps}; +use crate::state_reader::utils::{ReexecutionStateMaps, get_chain_info}; pub struct OfflineReexecutionData { offline_state_reader_prev_block: OfflineStateReader, diff --git a/crates/blockifier_reexecution/src/state_reader/test_state_reader.rs b/crates/blockifier_reexecution/src/state_reader/test_state_reader.rs index 533669f56a..e23fd4c057 100644 --- a/crates/blockifier_reexecution/src/state_reader/test_state_reader.rs +++ b/crates/blockifier_reexecution/src/state_reader/test_state_reader.rs @@ -21,7 +21,7 @@ use starknet_api::state::StorageKey; use starknet_api::transaction::{Transaction, TransactionHash}; use starknet_core::types::ContractClass as StarknetContractClass; use starknet_gateway::config::RpcStateReaderConfig; -use starknet_gateway::errors::{serde_err_to_state_err, RPCStateReaderError}; +use starknet_gateway::errors::{RPCStateReaderError, serde_err_to_state_err}; use starknet_gateway::rpc_objects::{ BlockHeader, BlockId, GetBlockWithTxHashesParams, ResourcePrice, }; @@ -163,10 +163,10 @@ impl TestStateReader { /// If l2_gas_price is not present in the block header, it will be set to 1. pub fn get_block_info(&self) -> ReexecutionResult { let mut json = retry_request!(self.retry_config, || { - self.rpc_state_reader.send_rpc_request( - "starknet_getBlockWithTxHashes", - GetBlockWithTxHashesParams { block_id: self.rpc_state_reader.block_id }, - ) + self.rpc_state_reader + .send_rpc_request("starknet_getBlockWithTxHashes", GetBlockWithTxHashesParams { + block_id: self.rpc_state_reader.block_id, + }) })?; let block_header_map = json.as_object_mut().ok_or(StateError::StateReadError( @@ -187,10 +187,10 @@ impl TestStateReader { pub fn get_starknet_version(&self) -> ReexecutionResult { let raw_version: String = serde_json::from_value( retry_request!(self.retry_config, || { - self.rpc_state_reader.send_rpc_request( - "starknet_getBlockWithTxHashes", - GetBlockWithTxHashesParams { block_id: self.rpc_state_reader.block_id }, - ) + self.rpc_state_reader + .send_rpc_request("starknet_getBlockWithTxHashes", GetBlockWithTxHashesParams { + block_id: self.rpc_state_reader.block_id, + }) })?["starknet_version"] .clone(), )?; @@ -215,10 +215,10 @@ impl TestStateReader { Ok(deserialize_transaction_json_to_starknet_api_tx(retry_request!( self.retry_config, || { - self.rpc_state_reader.send_rpc_request( - "starknet_getTransactionByHash", - GetTransactionByHashParams { transaction_hash: tx_hash.to_string() }, - ) + self.rpc_state_reader + .send_rpc_request("starknet_getTransactionByHash", GetTransactionByHashParams { + transaction_hash: tx_hash.to_string(), + }) } )?)?) } @@ -266,11 +266,11 @@ impl TestStateReader { } pub fn get_state_diff(&self) -> ReexecutionResult { - let raw_statediff = - &retry_request!(self.retry_config, || self.rpc_state_reader.send_rpc_request( - "starknet_getStateUpdate", - GetBlockWithTxHashesParams { block_id: self.rpc_state_reader.block_id } - ))?["state_diff"]; + let raw_statediff = &retry_request!(self.retry_config, || self + .rpc_state_reader + .send_rpc_request("starknet_getStateUpdate", GetBlockWithTxHashesParams { + block_id: self.rpc_state_reader.block_id + }))?["state_diff"]; let deployed_contracts = hashmap_from_raw::( raw_statediff, diff --git a/crates/committer_cli/benches/committer_bench.rs b/crates/committer_cli/benches/committer_bench.rs index 2d5947466a..f299736776 100644 --- a/crates/committer_cli/benches/committer_bench.rs +++ b/crates/committer_cli/benches/committer_bench.rs @@ -12,7 +12,7 @@ use std::collections::HashMap; use committer_cli::commands::commit; use committer_cli::parse_input::read::parse_input; use committer_cli::tests::utils::parse_from_python::TreeFlowInput; -use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; +use criterion::{BatchSize, Criterion, criterion_group, criterion_main}; use starknet_committer::block_committer::input::StarknetStorageValue; use starknet_committer::hash_function::hash::TreeHashFunctionImpl; use starknet_committer::patricia_merkle_tree::tree::OriginalSkeletonStorageTrieConfig; diff --git a/crates/committer_cli/src/commands.rs b/crates/committer_cli/src/commands.rs index fad171a4cb..f71348e3b6 100644 --- a/crates/committer_cli/src/commands.rs +++ b/crates/committer_cli/src/commands.rs @@ -2,8 +2,8 @@ use starknet_committer::block_committer::commit::commit_block; use starknet_committer::block_committer::input::{Config, ConfigImpl, Input}; use tracing::info; use tracing::level_filters::LevelFilter; -use tracing_subscriber::reload::Handle; use tracing_subscriber::Registry; +use tracing_subscriber::reload::Handle; use crate::filled_tree_output::filled_forest::SerializedForest; use crate::parse_input::read::{parse_input, write_to_file}; diff --git a/crates/committer_cli/src/tests/utils/random_structs.rs b/crates/committer_cli/src/tests/utils/random_structs.rs index 6a6009cf05..0cb233fb69 100644 --- a/crates/committer_cli/src/tests/utils/random_structs.rs +++ b/crates/committer_cli/src/tests/utils/random_structs.rs @@ -2,8 +2,8 @@ use std::cmp::min; use std::collections::HashMap; use ethnum::U256; -use rand::prelude::IteratorRandom; use rand::Rng; +use rand::prelude::IteratorRandom; use rand_distr::num_traits::ToPrimitive; use rand_distr::{Distribution, Geometric}; use starknet_committer::block_committer::input::{ContractAddress, StarknetStorageValue}; diff --git a/crates/committer_cli/src/tracing_utils.rs b/crates/committer_cli/src/tracing_utils.rs index 2a859abdd1..fbc817828d 100644 --- a/crates/committer_cli/src/tracing_utils.rs +++ b/crates/committer_cli/src/tracing_utils.rs @@ -1,7 +1,7 @@ use tracing::level_filters::LevelFilter; use tracing_subscriber::prelude::*; use tracing_subscriber::reload::Handle; -use tracing_subscriber::{filter, fmt, reload, Registry}; +use tracing_subscriber::{Registry, filter, fmt, reload}; // TODO(Amos, 1/8/2024) Move all tracing instantiations in the Sequencer repo to a common location. pub fn configure_tracing() -> Handle { diff --git a/crates/infra_utils/src/run_until.rs b/crates/infra_utils/src/run_until.rs index a4fb3ee951..8ced53c2a7 100644 --- a/crates/infra_utils/src/run_until.rs +++ b/crates/infra_utils/src/run_until.rs @@ -1,6 +1,6 @@ use std::future::Future; -use tokio::time::{sleep, Duration}; +use tokio::time::{Duration, sleep}; use crate::tracing::CustomLogger; diff --git a/crates/mempool_test_utils/src/starknet_api_test_utils.rs b/crates/mempool_test_utils/src/starknet_api_test_utils.rs index 1697f655f9..aeb9db52c4 100644 --- a/crates/mempool_test_utils/src/starknet_api_test_utils.rs +++ b/crates/mempool_test_utils/src/starknet_api_test_utils.rs @@ -7,7 +7,7 @@ use std::sync::LazyLock; use assert_matches::assert_matches; use blockifier::test_utils::contracts::FeatureContract; -use blockifier::test_utils::{create_trivial_calldata, CairoVersion, RunnableCairo1}; +use blockifier::test_utils::{CairoVersion, RunnableCairo1, create_trivial_calldata}; use infra_utils::path::resolve_project_relative_path; use pretty_assertions::assert_ne; use starknet_api::block::GasPrice; @@ -16,10 +16,10 @@ use starknet_api::executable_transaction::AccountTransaction; use starknet_api::execution_resources::GasAmount; use starknet_api::rpc_transaction::RpcTransaction; use starknet_api::state::SierraContractClass; +use starknet_api::test_utils::NonceManager; use starknet_api::test_utils::declare::rpc_declare_tx; use starknet_api::test_utils::deploy_account::rpc_deploy_account_tx; -use starknet_api::test_utils::invoke::{rpc_invoke_tx, InvokeTxArgs}; -use starknet_api::test_utils::NonceManager; +use starknet_api::test_utils::invoke::{InvokeTxArgs, rpc_invoke_tx}; use starknet_api::transaction::fields::{ AllResourceBounds, ContractAddressSalt, ResourceBounds, Tip, TransactionSignature, ValidResourceBounds, diff --git a/crates/native_blockifier/src/lib.rs b/crates/native_blockifier/src/lib.rs index 33913a2a70..2532a750d8 100644 --- a/crates/native_blockifier/src/lib.rs +++ b/crates/native_blockifier/src/lib.rs @@ -20,7 +20,7 @@ pub mod state_readers; pub mod storage; pub mod test_utils; -use errors::{add_py_exceptions, UndeclaredClassHashError}; +use errors::{UndeclaredClassHashError, add_py_exceptions}; use py_block_executor::PyBlockExecutor; use py_objects::PyExecutionResources; use py_validator::PyValidator; diff --git a/crates/native_blockifier/src/py_block_executor.rs b/crates/native_blockifier/src/py_block_executor.rs index 22e294824f..734ef00ba5 100644 --- a/crates/native_blockifier/src/py_block_executor.rs +++ b/crates/native_blockifier/src/py_block_executor.rs @@ -32,8 +32,8 @@ use crate::py_objects::{ PyVersionedConstantsOverrides, }; use crate::py_state_diff::{PyBlockInfo, PyStateDiff}; -use crate::py_transaction::{py_tx, PyClassInfo, PY_TX_PARSING_ERR}; -use crate::py_utils::{int_to_chain_id, into_block_number_hash_pair, PyFelt}; +use crate::py_transaction::{PY_TX_PARSING_ERR, PyClassInfo, py_tx}; +use crate::py_utils::{PyFelt, int_to_chain_id, into_block_number_hash_pair}; use crate::storage::{ PapyrusStorage, RawDeclaredClassMapping, RawDeprecatedDeclaredClassMapping, Storage, StorageConfig, diff --git a/crates/native_blockifier/src/py_declare.rs b/crates/native_blockifier/src/py_declare.rs index 8b058c6741..924f079bef 100644 --- a/crates/native_blockifier/src/py_declare.rs +++ b/crates/native_blockifier/src/py_declare.rs @@ -15,7 +15,7 @@ use starknet_types_core::felt::Felt; use crate::errors::{NativeBlockifierInputError, NativeBlockifierResult}; use crate::py_transaction::{PyClassInfo, PyDataAvailabilityMode, PyResourceBoundsMapping}; -use crate::py_utils::{from_py_felts, py_attr, PyFelt}; +use crate::py_utils::{PyFelt, from_py_felts, py_attr}; #[derive(FromPyObject)] struct PyDeclareTransactionV0V1 { diff --git a/crates/native_blockifier/src/py_deploy_account.rs b/crates/native_blockifier/src/py_deploy_account.rs index 246dad3f2b..280e7e426b 100644 --- a/crates/native_blockifier/src/py_deploy_account.rs +++ b/crates/native_blockifier/src/py_deploy_account.rs @@ -15,7 +15,7 @@ use starknet_types_core::felt::Felt; use crate::errors::{NativeBlockifierInputError, NativeBlockifierResult}; use crate::py_transaction::{PyDataAvailabilityMode, PyResourceBoundsMapping}; -use crate::py_utils::{from_py_felts, py_attr, PyFelt}; +use crate::py_utils::{PyFelt, from_py_felts, py_attr}; #[derive(FromPyObject)] struct PyDeployAccountTransactionV1 { diff --git a/crates/native_blockifier/src/py_invoke_function.rs b/crates/native_blockifier/src/py_invoke_function.rs index c00e2e89a4..114fe2e285 100644 --- a/crates/native_blockifier/src/py_invoke_function.rs +++ b/crates/native_blockifier/src/py_invoke_function.rs @@ -16,7 +16,7 @@ use starknet_types_core::felt::Felt; use crate::errors::{NativeBlockifierInputError, NativeBlockifierResult}; use crate::py_transaction::{PyDataAvailabilityMode, PyResourceBoundsMapping}; -use crate::py_utils::{from_py_felts, py_attr, PyFelt}; +use crate::py_utils::{PyFelt, from_py_felts, py_attr}; #[derive(FromPyObject)] struct PyInvokeTransactionV0 { diff --git a/crates/native_blockifier/src/py_l1_handler.rs b/crates/native_blockifier/src/py_l1_handler.rs index df90b9642e..62989a424f 100644 --- a/crates/native_blockifier/src/py_l1_handler.rs +++ b/crates/native_blockifier/src/py_l1_handler.rs @@ -4,11 +4,11 @@ use blockifier::abi::constants; use pyo3::prelude::*; use starknet_api::core::{ContractAddress, EntryPointSelector, Nonce}; use starknet_api::executable_transaction::L1HandlerTransaction; -use starknet_api::transaction::fields::{Calldata, Fee}; use starknet_api::transaction::TransactionHash; +use starknet_api::transaction::fields::{Calldata, Fee}; use crate::errors::{NativeBlockifierInputError, NativeBlockifierResult}; -use crate::py_utils::{from_py_felts, py_attr, PyFelt}; +use crate::py_utils::{PyFelt, from_py_felts, py_attr}; #[derive(FromPyObject)] struct PyL1HandlerTransaction { diff --git a/crates/native_blockifier/src/py_state_diff.rs b/crates/native_blockifier/src/py_state_diff.rs index 7d15b07fcd..6c91c51a96 100644 --- a/crates/native_blockifier/src/py_state_diff.rs +++ b/crates/native_blockifier/src/py_state_diff.rs @@ -9,8 +9,8 @@ use blockifier::test_utils::{ }; use blockifier::versioned_constants::VersionedConstants; use indexmap::IndexMap; -use pyo3::prelude::*; use pyo3::FromPyObject; +use pyo3::prelude::*; use starknet_api::block::{BlockInfo, BlockNumber, BlockTimestamp, NonzeroGasPrice}; use starknet_api::core::{ClassHash, ContractAddress, Nonce}; use starknet_api::state::{StateDiff, StorageKey}; diff --git a/crates/native_blockifier/src/py_test_utils.rs b/crates/native_blockifier/src/py_test_utils.rs index 2ba5ac4d48..5e84f93c57 100644 --- a/crates/native_blockifier/src/py_test_utils.rs +++ b/crates/native_blockifier/src/py_test_utils.rs @@ -9,8 +9,7 @@ use starknet_api::deprecated_contract_class::ContractClass; pub const TOKEN_FOR_TESTING_CLASS_HASH: &str = "0x30"; // This package is run within the StarkWare repository build directory. -pub const TOKEN_FOR_TESTING_CONTRACT_PATH: &str = - "./src/starkware/starknet/core/test_contract/starknet_compiled_contracts_lib/starkware/\ +pub const TOKEN_FOR_TESTING_CONTRACT_PATH: &str = "./src/starkware/starknet/core/test_contract/starknet_compiled_contracts_lib/starkware/\ starknet/core/test_contract/token_for_testing.json"; pub fn create_py_test_state() -> CachedState { diff --git a/crates/native_blockifier/src/py_testing_wrappers.rs b/crates/native_blockifier/src/py_testing_wrappers.rs index f0d9f607e0..2ddc8eeef3 100644 --- a/crates/native_blockifier/src/py_testing_wrappers.rs +++ b/crates/native_blockifier/src/py_testing_wrappers.rs @@ -1,7 +1,7 @@ use blockifier::execution::contract_class::estimate_casm_hash_computation_resources; use blockifier::transaction::errors::{TransactionExecutionError, TransactionFeeError}; use cairo_lang_starknet_classes::NestedIntList; -use pyo3::{pyfunction, PyResult}; +use pyo3::{PyResult, pyfunction}; use crate::errors::NativeBlockifierResult; use crate::py_objects::PyExecutionResources; diff --git a/crates/native_blockifier/src/py_transaction.rs b/crates/native_blockifier/src/py_transaction.rs index 33d715bd1a..1b474ad541 100644 --- a/crates/native_blockifier/src/py_transaction.rs +++ b/crates/native_blockifier/src/py_transaction.rs @@ -5,6 +5,7 @@ use blockifier::transaction::transaction_execution::Transaction; use blockifier::transaction::transaction_types::TransactionType; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; +use starknet_api::StarknetApiError; use starknet_api::block::GasPrice; use starknet_api::contract_class::{ClassInfo, ContractClass, SierraVersion}; use starknet_api::executable_transaction::AccountTransaction as ExecutableTransaction; @@ -12,7 +13,6 @@ use starknet_api::execution_resources::GasAmount; use starknet_api::transaction::fields::{ DeprecatedResourceBoundsMapping, Resource, ResourceBounds, ValidResourceBounds, }; -use starknet_api::StarknetApiError; use crate::errors::{NativeBlockifierInputError, NativeBlockifierResult}; use crate::py_declare::py_declare; diff --git a/crates/native_blockifier/src/py_validator.rs b/crates/native_blockifier/src/py_validator.rs index 4085a0a5d4..447e760128 100644 --- a/crates/native_blockifier/src/py_validator.rs +++ b/crates/native_blockifier/src/py_validator.rs @@ -8,7 +8,7 @@ use blockifier::transaction::account_transaction::AccountTransaction; use blockifier::transaction::objects::TransactionInfoCreator; use blockifier::transaction::transaction_types::TransactionType; use blockifier::versioned_constants::VersionedConstants; -use pyo3::{pyclass, pymethods, PyAny}; +use pyo3::{PyAny, pyclass, pymethods}; use starknet_api::core::Nonce; use starknet_api::transaction::TransactionHash; use starknet_types_core::felt::Felt; @@ -17,7 +17,7 @@ use crate::errors::NativeBlockifierResult; use crate::py_block_executor::PyOsConfig; use crate::py_objects::PyVersionedConstantsOverrides; use crate::py_state_diff::PyBlockInfo; -use crate::py_transaction::{py_account_tx, PyClassInfo, PY_TX_PARSING_ERR}; +use crate::py_transaction::{PY_TX_PARSING_ERR, PyClassInfo, py_account_tx}; use crate::py_utils::PyFelt; use crate::state_readers::py_state_reader::PyStateReader; diff --git a/crates/native_blockifier/src/storage.rs b/crates/native_blockifier/src/storage.rs index 5e028f14c1..f06e3919fc 100644 --- a/crates/native_blockifier/src/storage.rs +++ b/crates/native_blockifier/src/storage.rs @@ -17,10 +17,10 @@ use starknet_api::deprecated_contract_class::ContractClass as DeprecatedContract use starknet_api::hash::StarkHash; use starknet_api::state::{SierraContractClass, StateDiff, StateNumber, ThinStateDiff}; +use crate::PyStateDiff; use crate::errors::NativeBlockifierResult; use crate::py_state_diff::PyBlockInfo; -use crate::py_utils::{int_to_chain_id, PyFelt}; -use crate::PyStateDiff; +use crate::py_utils::{PyFelt, int_to_chain_id}; const GENESIS_BLOCK_ID: u64 = u64::MAX; diff --git a/crates/papyrus_base_layer/src/base_layer_test.rs b/crates/papyrus_base_layer/src/base_layer_test.rs index b52d053897..0ddc8ae93a 100644 --- a/crates/papyrus_base_layer/src/base_layer_test.rs +++ b/crates/papyrus_base_layer/src/base_layer_test.rs @@ -2,9 +2,9 @@ use pretty_assertions::assert_eq; use starknet_api::block::{BlockHash, BlockNumber}; use starknet_api::felt; +use crate::BaseLayerContract; use crate::ethereum_base_layer_contract::{EthereumBaseLayerConfig, EthereumBaseLayerContract}; use crate::test_utils::get_test_ethereum_node; -use crate::BaseLayerContract; // TODO: move to global test_utils crate and use everywhere instead of relying on the // confusing `#[ignore]` api to mark slow tests. diff --git a/crates/papyrus_base_layer/src/ethereum_base_layer_contract.rs b/crates/papyrus_base_layer/src/ethereum_base_layer_contract.rs index 3f9366065e..e536bbb148 100644 --- a/crates/papyrus_base_layer/src/ethereum_base_layer_contract.rs +++ b/crates/papyrus_base_layer/src/ethereum_base_layer_contract.rs @@ -11,7 +11,7 @@ use alloy_sol_types::sol_data; use alloy_transport::TransportErrorKind; use alloy_transport_http::{Client, Http}; use async_trait::async_trait; -use papyrus_config::dumping::{ser_param, ser_required_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_param, ser_required_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializationType, SerializedParam}; use serde::{Deserialize, Serialize}; use starknet_api::block::{BlockHash, BlockNumber}; diff --git a/crates/papyrus_base_layer/src/test_utils.rs b/crates/papyrus_base_layer/src/test_utils.rs index 230578e131..586f4ceedd 100644 --- a/crates/papyrus_base_layer/src/test_utils.rs +++ b/crates/papyrus_base_layer/src/test_utils.rs @@ -4,7 +4,7 @@ use std::process::Command; pub(crate) use alloy_primitives::Address as EthereumContractAddress; use ethers::utils::{Ganache, GanacheInstance}; use tar::Archive; -use tempfile::{tempdir, TempDir}; +use tempfile::{TempDir, tempdir}; type TestEthereumNodeHandle = (GanacheInstance, TempDir); diff --git a/crates/papyrus_common/src/python_json.rs b/crates/papyrus_common/src/python_json.rs index 69649fe8e5..220a874bb0 100644 --- a/crates/papyrus_common/src/python_json.rs +++ b/crates/papyrus_common/src/python_json.rs @@ -11,11 +11,7 @@ impl Formatter for PythonJsonFormatter { W: ?Sized + Write, { CompactFormatter.begin_array_value(writer, first)?; - if first { - Ok(()) - } else { - writer.write_all(b" ") - } + if first { Ok(()) } else { writer.write_all(b" ") } } fn begin_object_key(&mut self, writer: &mut W, first: bool) -> IOResult<()> @@ -23,11 +19,7 @@ impl Formatter for PythonJsonFormatter { W: ?Sized + Write, { CompactFormatter.begin_object_key(writer, first)?; - if first { - Ok(()) - } else { - writer.write_all(b" ") - } + if first { Ok(()) } else { writer.write_all(b" ") } } fn begin_object_value(&mut self, writer: &mut W) -> IOResult<()> diff --git a/crates/papyrus_config/src/command.rs b/crates/papyrus_config/src/command.rs index f21d1e9bee..ccc5ed875f 100644 --- a/crates/papyrus_config/src/command.rs +++ b/crates/papyrus_config/src/command.rs @@ -1,8 +1,8 @@ use std::collections::BTreeMap; use std::path::PathBuf; -use clap::{value_parser, Arg, ArgMatches, Command}; -use serde_json::{json, Value}; +use clap::{Arg, ArgMatches, Command, value_parser}; +use serde_json::{Value, json}; use crate::loading::update_config_map; use crate::{ConfigError, ParamPath, SerializationType, SerializedParam}; diff --git a/crates/papyrus_config/src/config_test.rs b/crates/papyrus_config/src/config_test.rs index d5ba39df85..72d84c4b95 100644 --- a/crates/papyrus_config/src/config_test.rs +++ b/crates/papyrus_config/src/config_test.rs @@ -17,10 +17,10 @@ use validator::Validate; use crate::command::{get_command_matches, update_config_map_by_command_args}; use crate::converters::deserialize_milliseconds_to_duration; use crate::dumping::{ - append_sub_config_name, combine_config_map_and_pointers, generate_struct_pointer, - required_param_description, ser_generated_param, ser_optional_param, ser_optional_sub_config, - ser_param, ser_pointer_target_param, ser_pointer_target_required_param, ser_required_param, - set_pointing_param_paths, SerializeConfig, + SerializeConfig, append_sub_config_name, combine_config_map_and_pointers, + generate_struct_pointer, required_param_description, ser_generated_param, ser_optional_param, + ser_optional_sub_config, ser_param, ser_pointer_target_param, + ser_pointer_target_required_param, ser_required_param, set_pointing_param_paths, }; use crate::loading::{ load, load_and_process_config, split_pointers_map, split_values_and_types, @@ -784,10 +784,10 @@ fn deeply_nested_optionals() { vec!["Testing".to_owned(), "--level1.#is_none".to_owned(), "false".to_owned()], ) .unwrap(); - assert_eq!( - l1, - Level0 { level0_value: 1, level1: Some(Level1 { level1_value: 0, level2: None }) } - ); + assert_eq!(l1, Level0 { + level0_value: 1, + level1: Some(Level1 { level1_value: 0, level2: None }) + }); let l2 = load_and_process_config::( File::open(file_path.clone()).unwrap(), @@ -801,13 +801,10 @@ fn deeply_nested_optionals() { ], ) .unwrap(); - assert_eq!( - l2, - Level0 { - level0_value: 1, - level1: Some(Level1 { level1_value: 0, level2: Some(Level2 { level2_value: None }) }), - } - ); + assert_eq!(l2, Level0 { + level0_value: 1, + level1: Some(Level1 { level1_value: 0, level2: Some(Level2 { level2_value: None }) }), + }); let l2_value = load_and_process_config::( File::open(file_path).unwrap(), @@ -823,14 +820,8 @@ fn deeply_nested_optionals() { ], ) .unwrap(); - assert_eq!( - l2_value, - Level0 { - level0_value: 1, - level1: Some(Level1 { - level1_value: 0, - level2: Some(Level2 { level2_value: Some(1) }), - }), - } - ); + assert_eq!(l2_value, Level0 { + level0_value: 1, + level1: Some(Level1 { level1_value: 0, level2: Some(Level2 { level2_value: Some(1) }) }), + }); } diff --git a/crates/papyrus_config/src/dumping.rs b/crates/papyrus_config/src/dumping.rs index f452ddaee4..94d02e5936 100644 --- a/crates/papyrus_config/src/dumping.rs +++ b/crates/papyrus_config/src/dumping.rs @@ -40,11 +40,11 @@ use std::io::{BufWriter, Write}; use itertools::chain; use serde::Serialize; -use serde_json::{json, Value}; +use serde_json::{Value, json}; use crate::{ - ConfigError, ParamPath, ParamPrivacy, ParamPrivacyInput, SerializationType, SerializedContent, - SerializedParam, FIELD_SEPARATOR, IS_NONE_MARK, + ConfigError, FIELD_SEPARATOR, IS_NONE_MARK, ParamPath, ParamPrivacy, ParamPrivacyInput, + SerializationType, SerializedContent, SerializedParam, }; /// Type alias for a pointer parameter and its serialized representation. @@ -372,14 +372,11 @@ pub(crate) fn combine_config_map_and_pointers( config_map.get(pointing_param).ok_or(ConfigError::PointerSourceNotFound { pointing_param: pointing_param.to_owned(), })?; - config_map.insert( - pointing_param.to_owned(), - SerializedParam { - description: pointing_serialized_param.description.clone(), - content: SerializedContent::PointerTarget(target_param.to_owned()), - privacy: pointing_serialized_param.privacy.clone(), - }, - ); + config_map.insert(pointing_param.to_owned(), SerializedParam { + description: pointing_serialized_param.description.clone(), + content: SerializedContent::PointerTarget(target_param.to_owned()), + privacy: pointing_serialized_param.privacy.clone(), + }); } } diff --git a/crates/papyrus_config/src/loading.rs b/crates/papyrus_config/src/loading.rs index ec9bd4cb87..e9ff85c4f7 100644 --- a/crates/papyrus_config/src/loading.rs +++ b/crates/papyrus_config/src/loading.rs @@ -9,17 +9,17 @@ use std::fs::File; use std::ops::IndexMut; use std::path::PathBuf; -use clap::parser::Values; use clap::Command; +use clap::parser::Values; use command::{get_command_matches, update_config_map_by_command_args}; use itertools::any; use serde::Deserialize; -use serde_json::{json, Map, Value}; +use serde_json::{Map, Value, json}; use crate::validators::validate_path_exists; use crate::{ - command, ConfigError, ParamPath, SerializationType, SerializedContent, SerializedParam, - IS_NONE_MARK, + ConfigError, IS_NONE_MARK, ParamPath, SerializationType, SerializedContent, SerializedParam, + command, }; /// Deserializes config from flatten JSON. diff --git a/crates/papyrus_execution/src/execution_test.rs b/crates/papyrus_execution/src/execution_test.rs index 04296ff61e..890eb37f1e 100644 --- a/crates/papyrus_execution/src/execution_test.rs +++ b/crates/papyrus_execution/src/execution_test.rs @@ -26,15 +26,15 @@ use crate::objects::{ TransactionTrace, }; use crate::test_utils::{ - execute_simulate_transactions, prepare_storage, TxsScenarioBuilder, ACCOUNT_ADDRESS, - ACCOUNT_CLASS_HASH, ACCOUNT_INITIAL_BALANCE, CHAIN_ID, CONTRACT_ADDRESS, + ACCOUNT_ADDRESS, ACCOUNT_CLASS_HASH, ACCOUNT_INITIAL_BALANCE, CHAIN_ID, CONTRACT_ADDRESS, DEPRECATED_CONTRACT_ADDRESS, GAS_PRICE, NEW_ACCOUNT_ADDRESS, SEQUENCER_ADDRESS, - TEST_ERC20_CONTRACT_ADDRESS, + TEST_ERC20_CONTRACT_ADDRESS, TxsScenarioBuilder, execute_simulate_transactions, + prepare_storage, }; use crate::testing_instances::get_test_execution_config; use crate::{ - estimate_fee, execute_call, ExecutableTransactionInput, ExecutionError, FeeEstimationResult, - RevertedTransaction, + ExecutableTransactionInput, ExecutionError, FeeEstimationResult, RevertedTransaction, + estimate_fee, execute_call, }; // Test calling entry points of a deprecated class. @@ -272,38 +272,29 @@ fn simulate_invoke() { let TransactionTrace::Invoke(exec_only_trace) = &exec_only.transaction_trace else { panic!("Wrong trace type, expected InvokeTransactionTrace.") }; - assert_matches!( - exec_only_trace, - InvokeTransactionTrace { - validate_invocation: None, - execute_invocation: FunctionInvocationResult::Ok(_), - fee_transfer_invocation: None, - } - ); + assert_matches!(exec_only_trace, InvokeTransactionTrace { + validate_invocation: None, + execute_invocation: FunctionInvocationResult::Ok(_), + fee_transfer_invocation: None, + }); let TransactionTrace::Invoke(validate_trace) = &validate.transaction_trace else { panic!("Wrong trace type, expected InvokeTransactionTrace.") }; - assert_matches!( - validate_trace, - InvokeTransactionTrace { - validate_invocation: Some(_), - execute_invocation: FunctionInvocationResult::Ok(_), - fee_transfer_invocation: None, - } - ); + assert_matches!(validate_trace, InvokeTransactionTrace { + validate_invocation: Some(_), + execute_invocation: FunctionInvocationResult::Ok(_), + fee_transfer_invocation: None, + }); let TransactionTrace::Invoke(charge_fee_trace) = &charge_fee.transaction_trace else { panic!("Wrong trace type, expected InvokeTransactionTrace.") }; - assert_matches!( - charge_fee_trace, - InvokeTransactionTrace { - validate_invocation: None, - execute_invocation: FunctionInvocationResult::Ok(_), - fee_transfer_invocation: Some(_), - } - ); + assert_matches!(charge_fee_trace, InvokeTransactionTrace { + validate_invocation: None, + execute_invocation: FunctionInvocationResult::Ok(_), + fee_transfer_invocation: Some(_), + }); assert_eq!(charge_fee.fee_estimation.l1_gas_price, GAS_PRICE.price_in_wei); assert_eq!(exec_only_trace.execute_invocation, charge_fee_trace.execute_invocation); @@ -313,14 +304,11 @@ fn simulate_invoke() { else { panic!("Wrong trace type, expected InvokeTransactionTrace.") }; - assert_matches!( - charge_fee_validate_trace, - InvokeTransactionTrace { - validate_invocation: Some(_), - execute_invocation: FunctionInvocationResult::Ok(_), - fee_transfer_invocation: Some(_), - } - ); + assert_matches!(charge_fee_validate_trace, InvokeTransactionTrace { + validate_invocation: Some(_), + execute_invocation: FunctionInvocationResult::Ok(_), + fee_transfer_invocation: Some(_), + }); // TODO(yair): Compare the trace to an expected trace. } @@ -349,39 +337,36 @@ fn simulate_declare_deprecated() { let TransactionTrace::Declare(exec_only_trace) = &exec_only.transaction_trace else { panic!("Wrong trace type, expected DeclareTransactionTrace.") }; - assert_matches!( - exec_only_trace, - DeclareTransactionTrace { validate_invocation: None, fee_transfer_invocation: None } - ); + assert_matches!(exec_only_trace, DeclareTransactionTrace { + validate_invocation: None, + fee_transfer_invocation: None + }); let TransactionTrace::Declare(validate_trace) = &validate.transaction_trace else { panic!("Wrong trace type, expected DeclareTransactionTrace.") }; - assert_matches!( - validate_trace, - DeclareTransactionTrace { validate_invocation: Some(_), fee_transfer_invocation: None } - ); + assert_matches!(validate_trace, DeclareTransactionTrace { + validate_invocation: Some(_), + fee_transfer_invocation: None + }); let TransactionTrace::Declare(charge_fee_trace) = &charge_fee.transaction_trace else { panic!("Wrong trace type, expected DeclareTransactionTrace.") }; - assert_matches!( - charge_fee_trace, - DeclareTransactionTrace { validate_invocation: None, fee_transfer_invocation: Some(_) } - ); + assert_matches!(charge_fee_trace, DeclareTransactionTrace { + validate_invocation: None, + fee_transfer_invocation: Some(_) + }); let TransactionTrace::Declare(charge_fee_validate_trace) = &charge_fee_validate.transaction_trace else { panic!("Wrong trace type, expected DeclareTransactionTrace.") }; - assert_matches!( - charge_fee_validate_trace, - DeclareTransactionTrace { - validate_invocation: Some(_), - fee_transfer_invocation: Some(_), - } - ); + assert_matches!(charge_fee_validate_trace, DeclareTransactionTrace { + validate_invocation: Some(_), + fee_transfer_invocation: Some(_), + }); // TODO(yair): Compare the trace to an expected trace. } @@ -410,39 +395,36 @@ fn simulate_declare() { let TransactionTrace::Declare(exec_only_trace) = &exec_only.transaction_trace else { panic!("Wrong trace type, expected DeclareTransactionTrace.") }; - assert_matches!( - exec_only_trace, - DeclareTransactionTrace { validate_invocation: None, fee_transfer_invocation: None } - ); + assert_matches!(exec_only_trace, DeclareTransactionTrace { + validate_invocation: None, + fee_transfer_invocation: None + }); let TransactionTrace::Declare(validate_trace) = &validate.transaction_trace else { panic!("Wrong trace type, expected DeclareTransactionTrace.") }; - assert_matches!( - validate_trace, - DeclareTransactionTrace { validate_invocation: Some(_), fee_transfer_invocation: None } - ); + assert_matches!(validate_trace, DeclareTransactionTrace { + validate_invocation: Some(_), + fee_transfer_invocation: None + }); let TransactionTrace::Declare(charge_fee_trace) = &charge_fee.transaction_trace else { panic!("Wrong trace type, expected DeclareTransactionTrace.") }; - assert_matches!( - charge_fee_trace, - DeclareTransactionTrace { validate_invocation: None, fee_transfer_invocation: Some(_) } - ); + assert_matches!(charge_fee_trace, DeclareTransactionTrace { + validate_invocation: None, + fee_transfer_invocation: Some(_) + }); let TransactionTrace::Declare(charge_fee_validate_trace) = &charge_fee_validate.transaction_trace else { panic!("Wrong trace type, expected DeclareTransactionTrace.") }; - assert_matches!( - charge_fee_validate_trace, - DeclareTransactionTrace { - validate_invocation: Some(_), - fee_transfer_invocation: Some(_), - } - ); + assert_matches!(charge_fee_validate_trace, DeclareTransactionTrace { + validate_invocation: Some(_), + fee_transfer_invocation: Some(_), + }); // TODO(yair): Compare the trace to an expected trace. } @@ -471,53 +453,41 @@ fn simulate_deploy_account() { let TransactionTrace::DeployAccount(exec_only_trace) = &exec_only.transaction_trace else { panic!("Wrong trace type, expected DeployAccountTransactionTrace.") }; - assert_matches!( - exec_only_trace, - DeployAccountTransactionTrace { - validate_invocation: None, - fee_transfer_invocation: None, - constructor_invocation: _, - } - ); + assert_matches!(exec_only_trace, DeployAccountTransactionTrace { + validate_invocation: None, + fee_transfer_invocation: None, + constructor_invocation: _, + }); let TransactionTrace::DeployAccount(validate_trace) = &validate.transaction_trace else { panic!("Wrong trace type, expected DeployAccountTransactionTrace.") }; - assert_matches!( - validate_trace, - DeployAccountTransactionTrace { - validate_invocation: Some(_), - fee_transfer_invocation: None, - constructor_invocation: _ - } - ); + assert_matches!(validate_trace, DeployAccountTransactionTrace { + validate_invocation: Some(_), + fee_transfer_invocation: None, + constructor_invocation: _ + }); let TransactionTrace::DeployAccount(charge_fee_trace) = &charge_fee.transaction_trace else { panic!("Wrong trace type, expected DeployAccountTransactionTrace.") }; - assert_matches!( - charge_fee_trace, - DeployAccountTransactionTrace { - validate_invocation: None, - fee_transfer_invocation: Some(_), - constructor_invocation: _ - } - ); + assert_matches!(charge_fee_trace, DeployAccountTransactionTrace { + validate_invocation: None, + fee_transfer_invocation: Some(_), + constructor_invocation: _ + }); let TransactionTrace::DeployAccount(charge_fee_validate_trace) = &charge_fee_validate.transaction_trace else { panic!("Wrong trace type, expected DeployAccountTransactionTrace.") }; - assert_matches!( - charge_fee_validate_trace, - DeployAccountTransactionTrace { - validate_invocation: Some(_), - fee_transfer_invocation: Some(_), - constructor_invocation: _ - } - ); + assert_matches!(charge_fee_validate_trace, DeployAccountTransactionTrace { + validate_invocation: Some(_), + fee_transfer_invocation: Some(_), + constructor_invocation: _ + }); // TODO(yair): Compare the trace to an expected trace. } diff --git a/crates/papyrus_execution/src/execution_utils.rs b/crates/papyrus_execution/src/execution_utils.rs index 51bc4bbba6..502d47dfba 100644 --- a/crates/papyrus_execution/src/execution_utils.rs +++ b/crates/papyrus_execution/src/execution_utils.rs @@ -12,7 +12,7 @@ use cairo_vm::types::errors::program_errors::ProgramError; use indexmap::IndexMap; use papyrus_common::state::{DeployedContract, ReplacedClass, StorageEntry}; use papyrus_storage::compiled_class::CasmStorageReader; -use papyrus_storage::db::{TransactionKind, RO}; +use papyrus_storage::db::{RO, TransactionKind}; use papyrus_storage::state::StateStorageReader; use papyrus_storage::{StorageError, StorageResult, StorageTxn}; // Expose the tool for creating entry point selectors from function names. diff --git a/crates/papyrus_execution/src/lib.rs b/crates/papyrus_execution/src/lib.rs index 4b47931bde..0a504a6a0b 100644 --- a/crates/papyrus_execution/src/lib.rs +++ b/crates/papyrus_execution/src/lib.rs @@ -42,11 +42,12 @@ use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; use cairo_vm::types::builtin_name::BuiltinName; use execution_utils::{get_trace_constructor, induced_state_diff}; use objects::{PriceUnit, TransactionSimulationOutput}; -use papyrus_config::dumping::{ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use papyrus_storage::header::HeaderStorageReader; use papyrus_storage::{StorageError, StorageReader}; use serde::{Deserialize, Serialize}; +use starknet_api::StarknetApiError; use starknet_api::block::{ BlockHashAndNumber, BlockInfo, BlockNumber, NonzeroGasPrice, StarknetVersion, }; @@ -62,12 +63,11 @@ use starknet_api::transaction::{ TransactionHash, TransactionOptions, TransactionVersion, }; use starknet_api::transaction_hash::get_transaction_hash; -use starknet_api::StarknetApiError; use starknet_types_core::felt::Felt; use state_reader::ExecutionStateReader; use tracing::trace; -use crate::objects::{tx_execution_output_to_fee_estimation, FeeEstimation, PendingData}; +use crate::objects::{FeeEstimation, PendingData, tx_execution_output_to_fee_estimation}; /// The address of the STRK fee contract on Starknet. const STRK_FEE_CONTRACT_ADDRESS_STR: &str = diff --git a/crates/papyrus_execution/src/state_reader.rs b/crates/papyrus_execution/src/state_reader.rs index 2841b4df02..9ed18d7209 100644 --- a/crates/papyrus_execution/src/state_reader.rs +++ b/crates/papyrus_execution/src/state_reader.rs @@ -18,7 +18,7 @@ use starknet_api::state::{StateNumber, StorageKey}; use starknet_types_core::felt::Felt; use crate::execution_utils; -use crate::execution_utils::{get_contract_class, ExecutionUtilsError}; +use crate::execution_utils::{ExecutionUtilsError, get_contract_class}; use crate::objects::PendingData; /// A view into the state at a specific state number. diff --git a/crates/papyrus_execution/src/state_reader_test.rs b/crates/papyrus_execution/src/state_reader_test.rs index 39c16fd179..99aff4773a 100644 --- a/crates/papyrus_execution/src/state_reader_test.rs +++ b/crates/papyrus_execution/src/state_reader_test.rs @@ -77,64 +77,54 @@ fn read_state() { .unwrap() .append_classes(BlockNumber(0), &[], &[]) .unwrap() - .append_header( - BlockNumber(1), - &BlockHeader { - block_hash: BlockHash(felt!(1_u128)), - block_header_without_hash: BlockHeaderWithoutHash { - block_number: BlockNumber(1), - ..Default::default() - }, + .append_header(BlockNumber(1), &BlockHeader { + block_hash: BlockHash(felt!(1_u128)), + block_header_without_hash: BlockHeaderWithoutHash { + block_number: BlockNumber(1), ..Default::default() }, - ) + ..Default::default() + }) .unwrap() .append_body(BlockNumber(1), BlockBody::default()) .unwrap() - .append_state_diff( - BlockNumber(1), - ThinStateDiff { - deployed_contracts: indexmap!( - address0 => class_hash0, - address1 => class_hash1, + .append_state_diff(BlockNumber(1), ThinStateDiff { + deployed_contracts: indexmap!( + address0 => class_hash0, + address1 => class_hash1, + ), + storage_diffs: indexmap!( + address0 => indexmap!( + storage_key0 => storage_value0, ), - storage_diffs: indexmap!( - address0 => indexmap!( - storage_key0 => storage_value0, - ), - ), - declared_classes: indexmap!( - class_hash0 => compiled_class_hash0, - class_hash5 => compiled_class_hash0, - ), - deprecated_declared_classes: vec![class_hash1], - nonces: indexmap!( - address0 => nonce0, - address1 => Nonce::default(), - ), - replaced_classes: indexmap!(), - }, - ) + ), + declared_classes: indexmap!( + class_hash0 => compiled_class_hash0, + class_hash5 => compiled_class_hash0, + ), + deprecated_declared_classes: vec![class_hash1], + nonces: indexmap!( + address0 => nonce0, + address1 => Nonce::default(), + ), + replaced_classes: indexmap!(), + }) .unwrap() - .append_classes( - BlockNumber(1), - &[(class_hash0, &class0), (class_hash5, &class0)], - &[(class_hash1, &class1)], - ) + .append_classes(BlockNumber(1), &[(class_hash0, &class0), (class_hash5, &class0)], &[( + class_hash1, + &class1, + )]) .unwrap() .append_casm(&class_hash0, &casm0) .unwrap() - .append_header( - BlockNumber(2), - &BlockHeader { - block_hash: BlockHash(felt!(2_u128)), - block_header_without_hash: BlockHeaderWithoutHash { - block_number: BlockNumber(2), - ..Default::default() - }, + .append_header(BlockNumber(2), &BlockHeader { + block_hash: BlockHash(felt!(2_u128)), + block_header_without_hash: BlockHeaderWithoutHash { + block_number: BlockNumber(2), ..Default::default() }, - ) + ..Default::default() + }) .unwrap() .append_body(BlockNumber(2), BlockBody::default()) .unwrap() @@ -240,10 +230,11 @@ fn read_state() { // Test get_class_hash_at when the class is replaced. if let Some(pending_data) = &mut state_reader2.maybe_pending_data { - pending_data.replaced_classes = vec![ - ReplacedClass { address: address0, class_hash: class_hash3 }, - ReplacedClass { address: address2, class_hash: class_hash3 }, - ]; + pending_data.replaced_classes = + vec![ReplacedClass { address: address0, class_hash: class_hash3 }, ReplacedClass { + address: address2, + class_hash: class_hash3, + }]; } assert_eq!(state_reader2.get_class_hash_at(address0).unwrap(), class_hash3); assert_eq!(state_reader2.get_class_hash_at(address2).unwrap(), class_hash3); diff --git a/crates/papyrus_execution/src/test_utils.rs b/crates/papyrus_execution/src/test_utils.rs index 354a4136c6..c22d5a6248 100644 --- a/crates/papyrus_execution/src/test_utils.rs +++ b/crates/papyrus_execution/src/test_utils.rs @@ -33,7 +33,7 @@ use starknet_types_core::felt::Felt; use crate::execution_utils::selector_from_name; use crate::objects::{PendingData, TransactionSimulationOutput}; use crate::testing_instances::get_test_execution_config; -use crate::{simulate_transactions, ExecutableTransactionInput, OnlyQuery, SierraSize}; +use crate::{ExecutableTransactionInput, OnlyQuery, SierraSize, simulate_transactions}; lazy_static! { pub static ref CHAIN_ID: ChainId = ChainId::Other(String::from("TEST_CHAIN_ID")); @@ -94,84 +94,71 @@ pub fn prepare_storage(mut storage_writer: StorageWriter) { storage_writer .begin_rw_txn() .unwrap() - .append_header( - BlockNumber(0), - &BlockHeader { - block_header_without_hash: BlockHeaderWithoutHash { - l1_gas_price: *GAS_PRICE, - sequencer: *SEQUENCER_ADDRESS, - timestamp: *BLOCK_TIMESTAMP, - ..Default::default() - }, + .append_header(BlockNumber(0), &BlockHeader { + block_header_without_hash: BlockHeaderWithoutHash { + l1_gas_price: *GAS_PRICE, + sequencer: *SEQUENCER_ADDRESS, + timestamp: *BLOCK_TIMESTAMP, ..Default::default() }, - ) + ..Default::default() + }) .unwrap() .append_body(BlockNumber(0), BlockBody::default()) .unwrap() - .append_state_diff( - BlockNumber(0), - ThinStateDiff { - deployed_contracts: indexmap!( - *TEST_ERC20_CONTRACT_ADDRESS => *TEST_ERC20_CONTRACT_CLASS_HASH, - *CONTRACT_ADDRESS => class_hash0, - *DEPRECATED_CONTRACT_ADDRESS => class_hash1, - *ACCOUNT_ADDRESS => *ACCOUNT_CLASS_HASH, + .append_state_diff(BlockNumber(0), ThinStateDiff { + deployed_contracts: indexmap!( + *TEST_ERC20_CONTRACT_ADDRESS => *TEST_ERC20_CONTRACT_CLASS_HASH, + *CONTRACT_ADDRESS => class_hash0, + *DEPRECATED_CONTRACT_ADDRESS => class_hash1, + *ACCOUNT_ADDRESS => *ACCOUNT_CLASS_HASH, + ), + storage_diffs: indexmap!( + *TEST_ERC20_CONTRACT_ADDRESS => indexmap!( + // Give the accounts some balance. + account_balance_key => *ACCOUNT_INITIAL_BALANCE, + new_account_balance_key => *ACCOUNT_INITIAL_BALANCE, + // Give the first account mint permission (what is this?). + minter_var_address => *ACCOUNT_ADDRESS.0.key() ), - storage_diffs: indexmap!( - *TEST_ERC20_CONTRACT_ADDRESS => indexmap!( - // Give the accounts some balance. - account_balance_key => *ACCOUNT_INITIAL_BALANCE, - new_account_balance_key => *ACCOUNT_INITIAL_BALANCE, - // Give the first account mint permission (what is this?). - minter_var_address => *ACCOUNT_ADDRESS.0.key() - ), - ), - declared_classes: indexmap!( - // The class is not used in the execution, so it can be default. - class_hash0 => CompiledClassHash::default() - ), - deprecated_declared_classes: vec![ - *TEST_ERC20_CONTRACT_CLASS_HASH, - class_hash1, - *ACCOUNT_CLASS_HASH, - ], - nonces: indexmap!( - *TEST_ERC20_CONTRACT_ADDRESS => Nonce::default(), - *CONTRACT_ADDRESS => Nonce::default(), - *DEPRECATED_CONTRACT_ADDRESS => Nonce::default(), - *ACCOUNT_ADDRESS => Nonce::default(), - ), - replaced_classes: indexmap!(), - }, - ) - .unwrap() - .append_classes( - BlockNumber(0), - &[(class_hash0, &SierraContractClass::default())], - &[ - (*TEST_ERC20_CONTRACT_CLASS_HASH, &get_test_erc20_fee_contract_class()), - (class_hash1, &get_test_deprecated_contract_class()), - (*ACCOUNT_CLASS_HASH, &get_test_account_class()), + ), + declared_classes: indexmap!( + // The class is not used in the execution, so it can be default. + class_hash0 => CompiledClassHash::default() + ), + deprecated_declared_classes: vec![ + *TEST_ERC20_CONTRACT_CLASS_HASH, + class_hash1, + *ACCOUNT_CLASS_HASH, ], - ) + nonces: indexmap!( + *TEST_ERC20_CONTRACT_ADDRESS => Nonce::default(), + *CONTRACT_ADDRESS => Nonce::default(), + *DEPRECATED_CONTRACT_ADDRESS => Nonce::default(), + *ACCOUNT_ADDRESS => Nonce::default(), + ), + replaced_classes: indexmap!(), + }) + .unwrap() + .append_classes(BlockNumber(0), &[(class_hash0, &SierraContractClass::default())], &[ + (*TEST_ERC20_CONTRACT_CLASS_HASH, &get_test_erc20_fee_contract_class()), + (class_hash1, &get_test_deprecated_contract_class()), + (*ACCOUNT_CLASS_HASH, &get_test_account_class()), + ]) .unwrap() .append_casm(&class_hash0, &get_test_casm()) .unwrap() - .append_header( - BlockNumber(1), - &BlockHeader { - block_hash: BlockHash(felt!(1_u128)), - block_header_without_hash: BlockHeaderWithoutHash { - l1_gas_price: *GAS_PRICE, - sequencer: *SEQUENCER_ADDRESS, - timestamp: *BLOCK_TIMESTAMP, - parent_hash: BlockHash(felt!(0_u128)), - ..Default::default() - }, + .append_header(BlockNumber(1), &BlockHeader { + block_hash: BlockHash(felt!(1_u128)), + block_header_without_hash: BlockHeaderWithoutHash { + l1_gas_price: *GAS_PRICE, + sequencer: *SEQUENCER_ADDRESS, + timestamp: *BLOCK_TIMESTAMP, + parent_hash: BlockHash(felt!(0_u128)), ..Default::default() }, - ) + ..Default::default() + }) .unwrap() .append_body(BlockNumber(1), BlockBody::default()) .unwrap() diff --git a/crates/papyrus_execution/src/testing_instances.rs b/crates/papyrus_execution/src/testing_instances.rs index 7b6fb61fe6..b78ff6bc2a 100644 --- a/crates/papyrus_execution/src/testing_instances.rs +++ b/crates/papyrus_execution/src/testing_instances.rs @@ -1,7 +1,7 @@ #![allow(clippy::unwrap_used)] //! Utilities for generating testing instances of the execution objects. -use papyrus_test_utils::{auto_impl_get_test_instance, get_number_of_variants, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, auto_impl_get_test_instance, get_number_of_variants}; /// Returns the storage key of a storage variable. pub use starknet_api::abi::abi_utils::get_storage_var_address; use starknet_api::block::GasPrice; @@ -13,13 +13,13 @@ use starknet_api::transaction::fields::{Calldata, Fee}; use starknet_api::transaction::{EventContent, MessageToL1}; use starknet_types_core::felt::Felt; +use crate::ExecutionConfig; use crate::objects::{ CallType, DeclareTransactionTrace, DeployAccountTransactionTrace, FeeEstimation, FunctionCall, FunctionInvocation, FunctionInvocationResult, InvokeTransactionTrace, L1HandlerTransactionTrace, OrderedEvent, OrderedL2ToL1Message, PriceUnit, Retdata, RevertReason, TransactionTrace, }; -use crate::ExecutionConfig; /// Creates ExecutionConfig for tests. pub fn get_test_execution_config() -> ExecutionConfig { diff --git a/crates/papyrus_load_test/src/compare_endpoints.rs b/crates/papyrus_load_test/src/compare_endpoints.rs index e3968e2f8a..72f2aa09df 100644 --- a/crates/papyrus_load_test/src/compare_endpoints.rs +++ b/crates/papyrus_load_test/src/compare_endpoints.rs @@ -1,5 +1,5 @@ use std::env::var; -use std::fs::{create_dir, remove_dir_all, File}; +use std::fs::{File, create_dir, remove_dir_all}; use std::io::Write; use std::path::Path; diff --git a/crates/papyrus_load_test/src/create_files.rs b/crates/papyrus_load_test/src/create_files.rs index 128508cb8d..cb9192bc13 100644 --- a/crates/papyrus_load_test/src/create_files.rs +++ b/crates/papyrus_load_test/src/create_files.rs @@ -9,19 +9,19 @@ use serde_json::Value as jsonVal; use starknet_api::test_utils::path_in_resources; use crate::{ - get_last_block_number, get_random_block_number, GET_BLOCK_TRANSACTION_COUNT_BY_HASH_WEIGHT, - GET_BLOCK_TRANSACTION_COUNT_BY_NUMBER_WEIGHT, GET_BLOCK_WITH_FULL_TRANSACTIONS_BY_HASH_WEIGHT, + GET_BLOCK_TRANSACTION_COUNT_BY_HASH_WEIGHT, GET_BLOCK_TRANSACTION_COUNT_BY_NUMBER_WEIGHT, + GET_BLOCK_WITH_FULL_TRANSACTIONS_BY_HASH_WEIGHT, GET_BLOCK_WITH_FULL_TRANSACTIONS_BY_NUMBER_WEIGHT, GET_BLOCK_WITH_TRANSACTION_HASHES_BY_HASH_WEIGHT, GET_BLOCK_WITH_TRANSACTION_HASHES_BY_NUMBER_WEIGHT, GET_CLASS_AT_BY_HASH_WEIGHT, GET_CLASS_AT_BY_NUMBER_WEIGHT, GET_CLASS_BY_HASH_WEIGHT, GET_CLASS_BY_NUMBER_WEIGHT, GET_CLASS_HASH_AT_BY_HASH_WEIGHT, GET_CLASS_HASH_AT_BY_NUMBER_WEIGHT, - GET_EVENTS_WITHOUT_ADDRESS_WEIGHT, GET_EVENTS_WITH_ADDRESS_WEIGHT, GET_NONCE_BY_HASH_WEIGHT, + GET_EVENTS_WITH_ADDRESS_WEIGHT, GET_EVENTS_WITHOUT_ADDRESS_WEIGHT, GET_NONCE_BY_HASH_WEIGHT, GET_NONCE_BY_NUMBER_WEIGHT, GET_STATE_UPDATE_BY_HASH_WEIGHT, GET_STATE_UPDATE_BY_NUMBER_WEIGHT, GET_STORAGE_AT_BY_HASH_WEIGHT, GET_STORAGE_AT_BY_NUMBER_WEIGHT, GET_TRANSACTION_BY_BLOCK_ID_AND_INDEX_BY_HASH_WEIGHT, GET_TRANSACTION_BY_BLOCK_ID_AND_INDEX_BY_NUMBER_WEIGHT, GET_TRANSACTION_BY_HASH_WEIGHT, - GET_TRANSACTION_RECEIPT_WEIGHT, + GET_TRANSACTION_RECEIPT_WEIGHT, get_last_block_number, get_random_block_number, }; // The limit on the storage size for request arguments. diff --git a/crates/papyrus_load_test/src/create_request.rs b/crates/papyrus_load_test/src/create_request.rs index 8040ddac24..2d79a5825b 100644 --- a/crates/papyrus_load_test/src/create_request.rs +++ b/crates/papyrus_load_test/src/create_request.rs @@ -1,6 +1,6 @@ use std::str::SplitWhitespace; -use serde_json::{json, Value as jsonVal}; +use serde_json::{Value as jsonVal, json}; use crate::jsonrpc_request; diff --git a/crates/papyrus_load_test/src/lib.rs b/crates/papyrus_load_test/src/lib.rs index 9b97a0a615..ae38cc9a18 100644 --- a/crates/papyrus_load_test/src/lib.rs +++ b/crates/papyrus_load_test/src/lib.rs @@ -20,7 +20,7 @@ use goose::goose::{GooseUser, TransactionError}; use once_cell::sync::OnceCell; use rand::Rng; use serde::Deserialize; -use serde_json::{json, Value as jsonVal}; +use serde_json::{Value as jsonVal, json}; use starknet_api::test_utils::path_in_resources; type PostResult = Result>; diff --git a/crates/papyrus_load_test/src/main.rs b/crates/papyrus_load_test/src/main.rs index 8375cd8efc..913a89874b 100644 --- a/crates/papyrus_load_test/src/main.rs +++ b/crates/papyrus_load_test/src/main.rs @@ -13,7 +13,7 @@ use std::env; use std::fs::File; use assert_matches::assert_matches; -use goose::{util, GooseAttack}; +use goose::{GooseAttack, util}; use papyrus_load_test::create_files::create_files; use papyrus_load_test::scenarios; use serde::Serialize; diff --git a/crates/papyrus_load_test/src/scenarios.rs b/crates/papyrus_load_test/src/scenarios.rs index 73c748fcfd..602bd139b6 100644 --- a/crates/papyrus_load_test/src/scenarios.rs +++ b/crates/papyrus_load_test/src/scenarios.rs @@ -1,7 +1,7 @@ use goose::goose::Scenario; use crate::{ - transactions as txs, BLOCK_HASH_AND_NUMBER_WEIGHT, BLOCK_NUMBER_WEIGHT, CHAIN_ID_WEIGHT, + BLOCK_HASH_AND_NUMBER_WEIGHT, BLOCK_NUMBER_WEIGHT, CHAIN_ID_WEIGHT, GET_BLOCK_TRANSACTION_COUNT_BY_HASH_WEIGHT, GET_BLOCK_TRANSACTION_COUNT_BY_NUMBER_WEIGHT, GET_BLOCK_WITH_FULL_TRANSACTIONS_BY_HASH_WEIGHT, GET_BLOCK_WITH_FULL_TRANSACTIONS_BY_NUMBER_WEIGHT, @@ -9,13 +9,13 @@ use crate::{ GET_BLOCK_WITH_TRANSACTION_HASHES_BY_NUMBER_WEIGHT, GET_CLASS_AT_BY_HASH_WEIGHT, GET_CLASS_AT_BY_NUMBER_WEIGHT, GET_CLASS_BY_HASH_WEIGHT, GET_CLASS_BY_NUMBER_WEIGHT, GET_CLASS_HASH_AT_BY_HASH_WEIGHT, GET_CLASS_HASH_AT_BY_NUMBER_WEIGHT, - GET_EVENTS_WITHOUT_ADDRESS_WEIGHT, GET_EVENTS_WITH_ADDRESS_WEIGHT, GET_NONCE_BY_HASH_WEIGHT, + GET_EVENTS_WITH_ADDRESS_WEIGHT, GET_EVENTS_WITHOUT_ADDRESS_WEIGHT, GET_NONCE_BY_HASH_WEIGHT, GET_NONCE_BY_NUMBER_WEIGHT, GET_STATE_UPDATE_BY_HASH_WEIGHT, GET_STATE_UPDATE_BY_NUMBER_WEIGHT, GET_STORAGE_AT_BY_HASH_WEIGHT, GET_STORAGE_AT_BY_NUMBER_WEIGHT, GET_TRANSACTION_BY_BLOCK_ID_AND_INDEX_BY_HASH_WEIGHT, GET_TRANSACTION_BY_BLOCK_ID_AND_INDEX_BY_NUMBER_WEIGHT, GET_TRANSACTION_BY_HASH_WEIGHT, GET_TRANSACTION_RECEIPT_WEIGHT, SYNCING_WEIGHT, TRACE_BLOCK_TRANSACTIONS_BY_HASH_WEIGHT, - TRACE_BLOCK_TRANSACTIONS_BY_NUMBER_WEIGHT, TRACE_TRANSACTION_WEIGHT, + TRACE_BLOCK_TRANSACTIONS_BY_NUMBER_WEIGHT, TRACE_TRANSACTION_WEIGHT, transactions as txs, }; // TODO(dvir): add also traceTransaction, simulateTransactions, estimateFee and call endpoints. diff --git a/crates/papyrus_load_test/src/transactions.rs b/crates/papyrus_load_test/src/transactions.rs index 43b506e498..47826d08c5 100644 --- a/crates/papyrus_load_test/src/transactions.rs +++ b/crates/papyrus_load_test/src/transactions.rs @@ -1,11 +1,11 @@ use std::fs::File; -use std::io::prelude::*; use std::io::BufReader; +use std::io::prelude::*; use std::sync::Arc; use goose::goose::{Transaction, TransactionFunction}; use rand::Rng; -use serde_json::{json, Value as jsonVal}; +use serde_json::{Value as jsonVal, json}; use starknet_api::test_utils::path_in_resources; use crate::{create_request, jsonrpc_request, post_jsonrpc_request}; diff --git a/crates/papyrus_monitoring_gateway/src/gateway_test.rs b/crates/papyrus_monitoring_gateway/src/gateway_test.rs index a075bca640..c9d384e2e5 100644 --- a/crates/papyrus_monitoring_gateway/src/gateway_test.rs +++ b/crates/papyrus_monitoring_gateway/src/gateway_test.rs @@ -1,20 +1,20 @@ use std::net::{SocketAddr, TcpListener}; use std::sync::Arc; +use axum::Router; use axum::body::Body; use axum::http::{Request, StatusCode}; use axum::response::Response; -use axum::Router; use metrics::{absolute_counter, describe_counter, register_counter}; use metrics_exporter_prometheus::PrometheusBuilder; use papyrus_storage::{table_names, test_utils}; use pretty_assertions::assert_eq; -use serde_json::{json, Value}; +use serde_json::{Value, json}; use starknet_client::reader::MockStarknetReader; use starknet_client::writer::MockStarknetWriter; use tower::ServiceExt; -use crate::{app, is_ready, MONITORING_PREFIX}; +use crate::{MONITORING_PREFIX, app, is_ready}; const TEST_CONFIG_PRESENTATION: &str = "full_general_config_presentation"; const PUBLIC_TEST_CONFIG_PRESENTATION: &str = "public_general_config_presentation"; diff --git a/crates/papyrus_monitoring_gateway/src/lib.rs b/crates/papyrus_monitoring_gateway/src/lib.rs index 20abb42a9f..07852a2211 100644 --- a/crates/papyrus_monitoring_gateway/src/lib.rs +++ b/crates/papyrus_monitoring_gateway/src/lib.rs @@ -18,16 +18,16 @@ use axum::{Json, Router}; use metrics_exporter_prometheus::{BuildError, PrometheusBuilder, PrometheusHandle}; use metrics_process::Collector; use papyrus_config::converters::{deserialize_optional_map, serialize_optional_map}; -use papyrus_config::dumping::{ser_generated_param, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_generated_param, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializationType, SerializedParam}; use papyrus_storage::mmap_file::MMapFileStats; use papyrus_storage::{DbStats, StorageError, StorageReader}; use rand::distributions::Alphanumeric; -use rand::{thread_rng, Rng}; +use rand::{Rng, thread_rng}; use serde::{Deserialize, Serialize}; +use starknet_client::RetryConfig; use starknet_client::reader::{StarknetFeederGatewayClient, StarknetReader}; use starknet_client::writer::{StarknetGatewayClient, StarknetWriter}; -use starknet_client::RetryConfig; use tracing::{debug, info, instrument}; use validator::Validate; diff --git a/crates/papyrus_network/src/bin_utils/mod.rs b/crates/papyrus_network/src/bin_utils/mod.rs index 53cd97449c..5450a93a4f 100644 --- a/crates/papyrus_network/src/bin_utils/mod.rs +++ b/crates/papyrus_network/src/bin_utils/mod.rs @@ -3,7 +3,7 @@ use std::time::Duration; use libp2p::identity::Keypair; use libp2p::swarm::NetworkBehaviour; -use libp2p::{noise, yamux, Multiaddr, Swarm, SwarmBuilder}; +use libp2p::{Multiaddr, Swarm, SwarmBuilder, noise, yamux}; use tracing::debug; pub fn build_swarm( diff --git a/crates/papyrus_network/src/discovery/flow_test.rs b/crates/papyrus_network/src/discovery/flow_test.rs index 7bc33d7339..4b62ca13f7 100644 --- a/crates/papyrus_network/src/discovery/flow_test.rs +++ b/crates/papyrus_network/src/discovery/flow_test.rs @@ -7,7 +7,7 @@ use libp2p::identity::Keypair; use libp2p::kad::store::MemoryStore; use libp2p::swarm::behaviour::toggle::Toggle; use libp2p::swarm::{NetworkBehaviour, SwarmEvent}; -use libp2p::{identify, kad, Multiaddr, Swarm}; +use libp2p::{Multiaddr, Swarm, identify, kad}; use libp2p_swarm_test::SwarmExt; use starknet_api::core::ChainId; diff --git a/crates/papyrus_network/src/discovery/identify_impl.rs b/crates/papyrus_network/src/discovery/identify_impl.rs index 945aed2942..ff27ec5476 100644 --- a/crates/papyrus_network/src/discovery/identify_impl.rs +++ b/crates/papyrus_network/src/discovery/identify_impl.rs @@ -1,4 +1,4 @@ -use libp2p::{identify, Multiaddr, PeerId}; +use libp2p::{Multiaddr, PeerId, identify}; use crate::mixed_behaviour; use crate::mixed_behaviour::BridgedBehaviour; diff --git a/crates/papyrus_network/src/discovery/mod.rs b/crates/papyrus_network/src/discovery/mod.rs index 0e1eb6e8fd..c41077e51c 100644 --- a/crates/papyrus_network/src/discovery/mod.rs +++ b/crates/papyrus_network/src/discovery/mod.rs @@ -6,23 +6,23 @@ pub mod identify_impl; pub mod kad_impl; use std::collections::BTreeMap; -use std::task::{ready, Context, Poll}; +use std::task::{Context, Poll, ready}; use std::time::Duration; -use futures::future::{pending, select, BoxFuture, Either}; -use futures::{pin_mut, Future, FutureExt}; +use futures::future::{BoxFuture, Either, pending, select}; +use futures::{Future, FutureExt, pin_mut}; use libp2p::core::Endpoint; use libp2p::swarm::behaviour::ConnectionEstablished; use libp2p::swarm::dial_opts::{DialOpts, PeerCondition}; use libp2p::swarm::{ - dummy, AddressChange, ConnectionClosed, ConnectionDenied, ConnectionHandler, ConnectionId, - DialFailure, FromSwarm, NetworkBehaviour, ToSwarm, + AddressChange, ConnectionClosed, ConnectionDenied, ConnectionHandler, ConnectionId, + DialFailure, FromSwarm, NetworkBehaviour, ToSwarm, dummy, }; use libp2p::{Multiaddr, PeerId}; use papyrus_config::converters::{ deserialize_milliseconds_to_duration, deserialize_seconds_to_duration, }; -use papyrus_config::dumping::{append_sub_config_name, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use serde::{Deserialize, Serialize}; use tokio_retry::strategy::ExponentialBackoff; diff --git a/crates/papyrus_network/src/gossipsub_impl.rs b/crates/papyrus_network/src/gossipsub_impl.rs index f2d4327ff3..e58329a57c 100644 --- a/crates/papyrus_network/src/gossipsub_impl.rs +++ b/crates/papyrus_network/src/gossipsub_impl.rs @@ -1,5 +1,5 @@ use libp2p::gossipsub::TopicHash; -use libp2p::{gossipsub, PeerId}; +use libp2p::{PeerId, gossipsub}; use tracing::error; use crate::mixed_behaviour; diff --git a/crates/papyrus_network/src/lib.rs b/crates/papyrus_network/src/lib.rs index d156e7be7f..acc7906e82 100644 --- a/crates/papyrus_network/src/lib.rs +++ b/crates/papyrus_network/src/lib.rs @@ -24,7 +24,7 @@ use papyrus_config::converters::{ deserialize_optional_vec_u8, deserialize_seconds_to_duration, serialize_optional_vec_u8, }; use papyrus_config::dumping::{ - append_sub_config_name, ser_optional_param, ser_param, SerializeConfig, + SerializeConfig, append_sub_config_name, ser_optional_param, ser_param, }; use papyrus_config::validators::validate_vec_u256; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; diff --git a/crates/papyrus_network/src/mixed_behaviour.rs b/crates/papyrus_network/src/mixed_behaviour.rs index 7395c6e022..4899498cae 100644 --- a/crates/papyrus_network/src/mixed_behaviour.rs +++ b/crates/papyrus_network/src/mixed_behaviour.rs @@ -2,15 +2,15 @@ use libp2p::identity::Keypair; use libp2p::kad::store::MemoryStore; +use libp2p::swarm::NetworkBehaviour; use libp2p::swarm::behaviour::toggle::Toggle; use libp2p::swarm::dial_opts::DialOpts; -use libp2p::swarm::NetworkBehaviour; -use libp2p::{gossipsub, identify, kad, Multiaddr, PeerId, StreamProtocol}; +use libp2p::{Multiaddr, PeerId, StreamProtocol, gossipsub, identify, kad}; use starknet_api::core::ChainId; -use crate::discovery::identify_impl::{IdentifyToOtherBehaviourEvent, IDENTIFY_PROTOCOL_VERSION}; -use crate::discovery::kad_impl::KadToOtherBehaviourEvent; use crate::discovery::DiscoveryConfig; +use crate::discovery::identify_impl::{IDENTIFY_PROTOCOL_VERSION, IdentifyToOtherBehaviourEvent}; +use crate::discovery::kad_impl::KadToOtherBehaviourEvent; use crate::peer_manager::PeerManagerConfig; use crate::{discovery, gossipsub_impl, peer_manager, sqmr}; @@ -70,11 +70,10 @@ impl MixedBehaviour { let public_key = keypair.public(); let local_peer_id = PeerId::from_public_key(&public_key); let mut kademlia_config = kad::Config::default(); - kademlia_config.set_protocol_names(vec![StreamProtocol::try_from_owned(format!( - "/starknet/kad/{}/1.0.0", - chain_id - )) - .expect("Failed to create StreamProtocol from a string that starts with /")]); + kademlia_config.set_protocol_names(vec![ + StreamProtocol::try_from_owned(format!("/starknet/kad/{}/1.0.0", chain_id)) + .expect("Failed to create StreamProtocol from a string that starts with /"), + ]); Self { peer_manager: peer_manager::PeerManager::new(peer_manager_config), discovery: bootstrap_peer_multiaddr diff --git a/crates/papyrus_network/src/network_manager/mod.rs b/crates/papyrus_network/src/network_manager/mod.rs index 8fa5434961..769282db17 100644 --- a/crates/papyrus_network/src/network_manager/mod.rs +++ b/crates/papyrus_network/src/network_manager/mod.rs @@ -12,10 +12,10 @@ use std::task::{Context, Poll}; use async_trait::async_trait; use futures::channel::mpsc::{Receiver, SendError, Sender}; use futures::channel::oneshot; -use futures::future::{ready, BoxFuture, Ready}; +use futures::future::{BoxFuture, Ready, ready}; use futures::sink::With; use futures::stream::{FuturesUnordered, Map, Stream}; -use futures::{pin_mut, FutureExt, Sink, SinkExt, StreamExt}; +use futures::{FutureExt, Sink, SinkExt, StreamExt, pin_mut}; use libp2p::gossipsub::{SubscriptionError, TopicHash}; use libp2p::swarm::SwarmEvent; use libp2p::{Multiaddr, PeerId, StreamProtocol, Swarm}; @@ -31,8 +31,8 @@ use crate::gossipsub_impl::Topic; use crate::mixed_behaviour::{self, BridgedBehaviour}; use crate::sqmr::behaviour::SessionError; use crate::sqmr::{self, InboundSessionId, OutboundSessionId, SessionId}; -use crate::utils::{is_localhost, StreamHashMap}; -use crate::{gossipsub_impl, NetworkConfig}; +use crate::utils::{StreamHashMap, is_localhost}; +use crate::{NetworkConfig, gossipsub_impl}; #[derive(thiserror::Error, Debug)] pub enum NetworkError { diff --git a/crates/papyrus_network/src/network_manager/swarm_trait.rs b/crates/papyrus_network/src/network_manager/swarm_trait.rs index d91cfc7f9b..b64b0ff097 100644 --- a/crates/papyrus_network/src/network_manager/swarm_trait.rs +++ b/crates/papyrus_network/src/network_manager/swarm_trait.rs @@ -8,7 +8,7 @@ use tracing::{info, warn}; use super::BroadcastedMessageMetadata; use crate::gossipsub_impl::Topic; use crate::mixed_behaviour; -use crate::peer_manager::{ReputationModifier, MALICIOUS}; +use crate::peer_manager::{MALICIOUS, ReputationModifier}; use crate::sqmr::behaviour::{PeerNotConnected, SessionIdNotFoundError}; use crate::sqmr::{Bytes, InboundSessionId, OutboundSessionId, SessionId}; diff --git a/crates/papyrus_network/src/network_manager/test.rs b/crates/papyrus_network/src/network_manager/test.rs index 1859836305..ea112e81ef 100644 --- a/crates/papyrus_network/src/network_manager/test.rs +++ b/crates/papyrus_network/src/network_manager/test.rs @@ -6,11 +6,11 @@ use std::time::Duration; use std::vec; use deadqueue::unlimited::Queue; -use futures::channel::mpsc::{unbounded, UnboundedSender}; +use futures::channel::mpsc::{UnboundedSender, unbounded}; use futures::channel::oneshot; use futures::future::FutureExt; use futures::stream::Stream; -use futures::{pin_mut, Future, SinkExt, StreamExt}; +use futures::{Future, SinkExt, StreamExt, pin_mut}; use lazy_static::lazy_static; use libp2p::core::ConnectedPoint; use libp2p::gossipsub::{SubscriptionError, TopicHash}; diff --git a/crates/papyrus_network/src/network_manager/test_utils.rs b/crates/papyrus_network/src/network_manager/test_utils.rs index b3a3af5d02..0a46097ab5 100644 --- a/crates/papyrus_network/src/network_manager/test_utils.rs +++ b/crates/papyrus_network/src/network_manager/test_utils.rs @@ -3,7 +3,7 @@ use std::time::Duration; use futures::channel::mpsc::{Receiver, SendError, Sender}; use futures::channel::oneshot; -use futures::future::{ready, Ready}; +use futures::future::{Ready, ready}; use futures::sink::With; use futures::stream::Map; use futures::{SinkExt, StreamExt}; @@ -18,9 +18,9 @@ use super::{ ReportReceiver, ServerQueryManager, ServerResponsesSender, SqmrClientPayload, SqmrClientSender, SqmrServerReceiver, Topic, }; +use crate::NetworkConfig; use crate::network_manager::{BroadcastReceivedMessagesConverterFn, BroadcastTopicChannels}; use crate::sqmr::Bytes; -use crate::NetworkConfig; pub fn mock_register_sqmr_protocol_client( buffer_size: usize, diff --git a/crates/papyrus_network/src/peer_manager/behaviour_impl.rs b/crates/papyrus_network/src/peer_manager/behaviour_impl.rs index 2bce533af0..648107b4b2 100644 --- a/crates/papyrus_network/src/peer_manager/behaviour_impl.rs +++ b/crates/papyrus_network/src/peer_manager/behaviour_impl.rs @@ -1,8 +1,8 @@ -use std::task::{ready, Poll}; +use std::task::{Poll, ready}; use libp2p::swarm::behaviour::ConnectionEstablished; use libp2p::swarm::{ - dummy, ConnectionClosed, ConnectionId, DialError, DialFailure, NetworkBehaviour, ToSwarm, + ConnectionClosed, ConnectionId, DialError, DialFailure, NetworkBehaviour, ToSwarm, dummy, }; use libp2p::{Multiaddr, PeerId}; use tracing::{debug, error, warn}; @@ -106,11 +106,7 @@ impl NetworkBehaviour for PeerManager { self.session_to_peer_map .iter() .filter_map(|(outbound_session_id, p_id)| { - if *p_id == peer_id { - Some(*outbound_session_id) - } else { - None - } + if *p_id == peer_id { Some(*outbound_session_id) } else { None } }) .collect::>(); for outbound_session_id in queries_to_assign { diff --git a/crates/papyrus_network/src/peer_manager/mod.rs b/crates/papyrus_network/src/peer_manager/mod.rs index b9593ef1c0..e6df28162e 100644 --- a/crates/papyrus_network/src/peer_manager/mod.rs +++ b/crates/papyrus_network/src/peer_manager/mod.rs @@ -1,15 +1,15 @@ use std::collections::{BTreeMap, HashMap}; use std::time::Duration; -use futures::future::BoxFuture; use futures::FutureExt; -use libp2p::swarm::dial_opts::DialOpts; -use libp2p::swarm::ToSwarm; +use futures::future::BoxFuture; use libp2p::PeerId; +use libp2p::swarm::ToSwarm; +use libp2p::swarm::dial_opts::DialOpts; use papyrus_config::converters::{ deserialize_milliseconds_to_duration, deserialize_seconds_to_duration, }; -use papyrus_config::dumping::{ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use peer::Peer; use serde::{Deserialize, Serialize}; diff --git a/crates/papyrus_network/src/peer_manager/test.rs b/crates/papyrus_network/src/peer_manager/test.rs index 56f69e34c4..940ab5e2af 100644 --- a/crates/papyrus_network/src/peer_manager/test.rs +++ b/crates/papyrus_network/src/peer_manager/test.rs @@ -19,7 +19,7 @@ use crate::discovery::identify_impl::IdentifyToOtherBehaviourEvent; use crate::mixed_behaviour; use crate::mixed_behaviour::BridgedBehaviour; use crate::peer_manager::peer::{Peer, PeerTrait}; -use crate::peer_manager::{PeerManager, PeerManagerConfig, ReputationModifier, MALICIOUS}; +use crate::peer_manager::{MALICIOUS, PeerManager, PeerManagerConfig, ReputationModifier}; use crate::sqmr::OutboundSessionId; impl Unpin for PeerManager {} @@ -287,10 +287,9 @@ fn report_session_on_unknown_session_id() { let outbound_session_id = OutboundSessionId { value: 1 }; peer_manager - .report_session( - outbound_session_id, - ReputationModifier::Misconduct { misconduct_score: MALICIOUS }, - ) + .report_session(outbound_session_id, ReputationModifier::Misconduct { + misconduct_score: MALICIOUS, + }) .expect_err("report_session on unknown outbound_session_id should return an error"); } diff --git a/crates/papyrus_network/src/sqmr/behaviour.rs b/crates/papyrus_network/src/sqmr/behaviour.rs index 144edbc5b9..b2f09ac691 100644 --- a/crates/papyrus_network/src/sqmr/behaviour.rs +++ b/crates/papyrus_network/src/sqmr/behaviour.rs @@ -4,8 +4,8 @@ mod behaviour_test; use std::collections::{HashMap, HashSet, VecDeque}; use std::io; -use std::sync::atomic::AtomicUsize; use std::sync::Arc; +use std::sync::atomic::AtomicUsize; use std::task::{Context, Poll, Waker}; use std::time::Duration; diff --git a/crates/papyrus_network/src/sqmr/flow_test.rs b/crates/papyrus_network/src/sqmr/flow_test.rs index 99fced9439..3026ad53aa 100644 --- a/crates/papyrus_network/src/sqmr/flow_test.rs +++ b/crates/papyrus_network/src/sqmr/flow_test.rs @@ -1,5 +1,5 @@ -use std::collections::hash_map::DefaultHasher; use std::collections::HashMap; +use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::time::Duration; diff --git a/crates/papyrus_network/src/sqmr/handler.rs b/crates/papyrus_network/src/sqmr/handler.rs index 552b7c26df..2c88a47edb 100644 --- a/crates/papyrus_network/src/sqmr/handler.rs +++ b/crates/papyrus_network/src/sqmr/handler.rs @@ -5,8 +5,8 @@ mod inbound_session; use std::collections::{HashMap, HashSet, VecDeque}; use std::io; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::task::{Context, Poll}; use std::time::Duration; diff --git a/crates/papyrus_network/src/sqmr/handler/inbound_session.rs b/crates/papyrus_network/src/sqmr/handler/inbound_session.rs index 26819cc0f9..5fe7850cb8 100644 --- a/crates/papyrus_network/src/sqmr/handler/inbound_session.rs +++ b/crates/papyrus_network/src/sqmr/handler/inbound_session.rs @@ -2,7 +2,7 @@ use std::collections::VecDeque; use std::future::Future; use std::io; use std::pin::Pin; -use std::task::{ready, Context, Poll, Waker}; +use std::task::{Context, Poll, Waker, ready}; use futures::future::BoxFuture; use futures::io::WriteHalf; @@ -10,8 +10,8 @@ use futures::{AsyncWriteExt, FutureExt}; use libp2p::swarm::Stream; use replace_with::replace_with_or_abort; -use super::super::messages::write_message; use super::super::Bytes; +use super::super::messages::write_message; pub(super) struct InboundSession { pending_messages: VecDeque, diff --git a/crates/papyrus_network/src/sqmr/handler_test.rs b/crates/papyrus_network/src/sqmr/handler_test.rs index 69a358faec..7607c84435 100644 --- a/crates/papyrus_network/src/sqmr/handler_test.rs +++ b/crates/papyrus_network/src/sqmr/handler_test.rs @@ -1,12 +1,12 @@ use std::collections::HashSet; use std::io; use std::pin::Pin; -use std::sync::atomic::AtomicUsize; use std::sync::Arc; +use std::sync::atomic::AtomicUsize; use assert_matches::assert_matches; use futures::task::{Context, Poll}; -use futures::{select, AsyncReadExt, AsyncWriteExt, FutureExt, Stream as StreamTrait, StreamExt}; +use futures::{AsyncReadExt, AsyncWriteExt, FutureExt, Stream as StreamTrait, StreamExt, select}; use lazy_static::lazy_static; use libp2p::swarm::handler::{ ConnectionEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, diff --git a/crates/papyrus_network/src/sqmr/messages_test.rs b/crates/papyrus_network/src/sqmr/messages_test.rs index a30132605e..1c472929fd 100644 --- a/crates/papyrus_network/src/sqmr/messages_test.rs +++ b/crates/papyrus_network/src/sqmr/messages_test.rs @@ -41,7 +41,7 @@ async fn read_message_returns_none_when_other_stream_is_closed() { #[tokio::test] async fn read_message_is_pending_when_other_stream_didnt_send() { let (_stream1, mut stream2, _) = get_connected_streams().await; - assert!(tokio::time::timeout(Duration::from_millis(10), read_message(&mut stream2)) - .await - .is_err()); + assert!( + tokio::time::timeout(Duration::from_millis(10), read_message(&mut stream2)).await.is_err() + ); } diff --git a/crates/papyrus_network/src/sqmr/protocol.rs b/crates/papyrus_network/src/sqmr/protocol.rs index 6b91057818..5a2bd0c6ec 100644 --- a/crates/papyrus_network/src/sqmr/protocol.rs +++ b/crates/papyrus_network/src/sqmr/protocol.rs @@ -7,11 +7,11 @@ use std::{io, iter}; use futures::future::BoxFuture; use futures::io::{ReadHalf, WriteHalf}; use futures::{AsyncRead, AsyncReadExt, AsyncWrite, FutureExt}; -use libp2p::core::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}; use libp2p::StreamProtocol; +use libp2p::core::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}; -use super::messages::{read_message_without_length_prefix, write_message_without_length_prefix}; use super::Bytes; +use super::messages::{read_message_without_length_prefix, write_message_without_length_prefix}; pub struct InboundProtocol { supported_protocols: Vec, diff --git a/crates/papyrus_network/src/sqmr/protocol_test.rs b/crates/papyrus_network/src/sqmr/protocol_test.rs index f061153e81..9c1e68bfb6 100644 --- a/crates/papyrus_network/src/sqmr/protocol_test.rs +++ b/crates/papyrus_network/src/sqmr/protocol_test.rs @@ -1,6 +1,6 @@ -use libp2p::core::upgrade::{InboundUpgrade, OutboundUpgrade}; -use libp2p::core::UpgradeInfo; use libp2p::StreamProtocol; +use libp2p::core::UpgradeInfo; +use libp2p::core::upgrade::{InboundUpgrade, OutboundUpgrade}; use pretty_assertions::assert_eq; use super::super::messages::{read_message, write_message}; diff --git a/crates/papyrus_network/src/test_utils/get_stream.rs b/crates/papyrus_network/src/test_utils/get_stream.rs index 173f7f82dd..0abcff8a0e 100644 --- a/crates/papyrus_network/src/test_utils/get_stream.rs +++ b/crates/papyrus_network/src/test_utils/get_stream.rs @@ -3,8 +3,8 @@ use std::task::{Context, Poll}; use futures::future::BoxFuture; use futures::{AsyncRead, AsyncWrite, FutureExt}; -use libp2p::core::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}; use libp2p::core::Endpoint; +use libp2p::core::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}; use libp2p::swarm::handler::{ConnectionEvent, FullyNegotiatedInbound, FullyNegotiatedOutbound}; use libp2p::swarm::{ ConnectionDenied, ConnectionHandler, ConnectionHandlerEvent, ConnectionId, FromSwarm, diff --git a/crates/papyrus_network/src/test_utils/mod.rs b/crates/papyrus_network/src/test_utils/mod.rs index 498d8b9f9a..ebdc3148fb 100644 --- a/crates/papyrus_network/src/test_utils/mod.rs +++ b/crates/papyrus_network/src/test_utils/mod.rs @@ -28,11 +28,7 @@ pub(crate) async fn get_connected_streams() -> (Stream, Stream, JoinHandle<()>) let merged_swarm = swarm1.merge(swarm2); let mut filtered_swarm = merged_swarm.filter_map(|event| { - if let SwarmEvent::Behaviour(stream) = event { - Some(stream) - } else { - None - } + if let SwarmEvent::Behaviour(stream) = event { Some(stream) } else { None } }); ( filtered_swarm.next().await.unwrap(), diff --git a/crates/papyrus_network/src/utils.rs b/crates/papyrus_network/src/utils.rs index 72c862b61c..d268513e32 100644 --- a/crates/papyrus_network/src/utils.rs +++ b/crates/papyrus_network/src/utils.rs @@ -1,13 +1,13 @@ use core::net::Ipv4Addr; -use std::collections::hash_map::{Keys, ValuesMut}; use std::collections::HashMap; +use std::collections::hash_map::{Keys, ValuesMut}; use std::hash::Hash; use std::pin::Pin; use std::task::{Context, Poll, Waker}; use futures::stream::{Stream, StreamExt}; -use libp2p::core::multiaddr::Protocol; use libp2p::Multiaddr; +use libp2p::core::multiaddr::Protocol; // This is an implementation of `StreamMap` from tokio_stream. The reason we're implementing it // ourselves is that the implementation in tokio_stream requires that the values implement the diff --git a/crates/papyrus_network_types/src/test_utils.rs b/crates/papyrus_network_types/src/test_utils.rs index e7c20c5dab..bb1e5f72ff 100644 --- a/crates/papyrus_network_types/src/test_utils.rs +++ b/crates/papyrus_network_types/src/test_utils.rs @@ -1,5 +1,5 @@ use libp2p::PeerId; -use papyrus_test_utils::{auto_impl_get_test_instance, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, auto_impl_get_test_instance}; use rand_chacha::ChaCha8Rng; use crate::network_types::{BroadcastedMessageMetadata, OpaquePeerId}; diff --git a/crates/papyrus_node/examples/get_transaction_hash.rs b/crates/papyrus_node/examples/get_transaction_hash.rs index bf91ba0f95..ff8ccc091c 100644 --- a/crates/papyrus_node/examples/get_transaction_hash.rs +++ b/crates/papyrus_node/examples/get_transaction_hash.rs @@ -6,10 +6,10 @@ use clap::{Arg, Command}; use futures::future::join_all; use once_cell::sync::OnceCell; use reqwest::Client; -use serde_json::{json, to_writer_pretty, Map, Value}; +use serde_json::{Map, Value, json, to_writer_pretty}; use starknet_api::core::ChainId; use starknet_api::transaction::{self, Transaction, TransactionOptions}; -use starknet_api::transaction_hash::{get_transaction_hash, MAINNET_TRANSACTION_HASH_WITH_VERSION}; +use starknet_api::transaction_hash::{MAINNET_TRANSACTION_HASH_WITH_VERSION, get_transaction_hash}; use starknet_client::reader::objects::transaction::TransactionType; use strum::IntoEnumIterator; @@ -247,12 +247,12 @@ fn create_map_of_transaction( // insert the only_query_transaction_hash into the json file. transaction_info.insert( "only_query_transaction_hash".to_string(), - json!(get_transaction_hash( - transaction, - &chain_id, - &TransactionOptions { only_query: true } - ) - .expect("Couldn't get only query transaction hash")), + json!( + get_transaction_hash(transaction, &chain_id, &TransactionOptions { + only_query: true + }) + .expect("Couldn't get only query transaction hash") + ), ); } transaction_info diff --git a/crates/papyrus_node/src/bin/papyrus_dump_config.rs b/crates/papyrus_node/src/bin/papyrus_dump_config.rs index 0e7f6e67aa..4866f4627e 100644 --- a/crates/papyrus_node/src/bin/papyrus_dump_config.rs +++ b/crates/papyrus_node/src/bin/papyrus_dump_config.rs @@ -7,7 +7,7 @@ use papyrus_config::dumping::SerializeConfig; #[cfg(feature = "rpc")] use papyrus_node::config::pointers::{CONFIG_NON_POINTERS_WHITELIST, CONFIG_POINTERS}; #[cfg(feature = "rpc")] -use papyrus_node::config::{NodeConfig, DEFAULT_CONFIG_PATH}; +use papyrus_node::config::{DEFAULT_CONFIG_PATH, NodeConfig}; /// Updates the default config file by: /// cargo run --bin papyrus_dump_config -q diff --git a/crates/papyrus_node/src/bin/run_consensus.rs b/crates/papyrus_node/src/bin/run_consensus.rs index ec62abc1d9..6ffd44f42b 100644 --- a/crates/papyrus_node/src/bin/run_consensus.rs +++ b/crates/papyrus_node/src/bin/run_consensus.rs @@ -14,7 +14,7 @@ use papyrus_consensus_orchestrator::papyrus_consensus_context::PapyrusConsensusC use papyrus_network::gossipsub_impl::Topic; use papyrus_network::network_manager::NetworkManager; use papyrus_node::bin_utils::build_configs; -use papyrus_node::run::{run, PapyrusResources, PapyrusTaskHandles}; +use papyrus_node::run::{PapyrusResources, PapyrusTaskHandles, run}; use papyrus_p2p_sync::BUFFER_SIZE; use papyrus_storage::StorageReader; use starknet_api::block::BlockNumber; diff --git a/crates/papyrus_node/src/config/config_test.rs b/crates/papyrus_node/src/config/config_test.rs index fe7a025a5a..de7eee2566 100644 --- a/crates/papyrus_node/src/config/config_test.rs +++ b/crates/papyrus_node/src/config/config_test.rs @@ -17,14 +17,14 @@ use papyrus_config::presentation::get_config_presentation; use papyrus_config::{SerializationType, SerializedContent, SerializedParam}; use papyrus_monitoring_gateway::MonitoringGatewayConfig; use pretty_assertions::assert_eq; -use serde_json::{json, Map, Value}; +use serde_json::{Map, Value, json}; use starknet_api::core::ChainId; use tempfile::NamedTempFile; use validator::Validate; #[cfg(feature = "rpc")] use crate::config::pointers::{CONFIG_NON_POINTERS_WHITELIST, CONFIG_POINTERS}; -use crate::config::{node_command, NodeConfig, DEFAULT_CONFIG_PATH}; +use crate::config::{DEFAULT_CONFIG_PATH, NodeConfig, node_command}; // Returns the required and generated params in config/papyrus/default_config.json with the default // value from the config presentation. diff --git a/crates/papyrus_node/src/config/mod.rs b/crates/papyrus_node/src/config/mod.rs index 9d94183f07..a992793d3c 100644 --- a/crates/papyrus_node/src/config/mod.rs +++ b/crates/papyrus_node/src/config/mod.rs @@ -12,13 +12,13 @@ use std::path::{Path, PathBuf}; use std::time::Duration; use std::{env, fs, io}; -use clap::{arg, value_parser, Arg, ArgMatches, Command}; -use itertools::{chain, Itertools}; +use clap::{Arg, ArgMatches, Command, arg, value_parser}; +use itertools::{Itertools, chain}; use lazy_static::lazy_static; use papyrus_base_layer::ethereum_base_layer_contract::EthereumBaseLayerConfig; use papyrus_config::dumping::{ - append_sub_config_name, ser_optional_sub_config, ser_param, ser_pointer_target_param, - SerializeConfig, + SerializeConfig, append_sub_config_name, ser_optional_sub_config, ser_param, + ser_pointer_target_param, }; use papyrus_config::loading::load_and_process_config; use papyrus_config::{ConfigError, ParamPath, ParamPrivacyInput, SerializedParam}; @@ -28,10 +28,10 @@ use papyrus_network::NetworkConfig; use papyrus_p2p_sync::client::{P2PSyncClient, P2PSyncClientConfig}; #[cfg(feature = "rpc")] use papyrus_rpc::RpcConfig; -use papyrus_storage::db::DbConfig; use papyrus_storage::StorageConfig; -use papyrus_sync::sources::central::CentralSourceConfig; +use papyrus_storage::db::DbConfig; use papyrus_sync::SyncConfig; +use papyrus_sync::sources::central::CentralSourceConfig; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use starknet_api::core::ChainId; diff --git a/crates/papyrus_node/src/config/pointers.rs b/crates/papyrus_node/src/config/pointers.rs index e87d2e9680..1ac0e4e230 100644 --- a/crates/papyrus_node/src/config/pointers.rs +++ b/crates/papyrus_node/src/config/pointers.rs @@ -8,29 +8,29 @@ use std::sync::LazyLock; use std::time::Duration; use std::{env, fs, io}; -use clap::{arg, value_parser, Arg, ArgMatches, Command}; -use itertools::{chain, Itertools}; +use clap::{Arg, ArgMatches, Command, arg, value_parser}; +use itertools::{Itertools, chain}; use lazy_static::lazy_static; use papyrus_base_layer::ethereum_base_layer_contract::EthereumBaseLayerConfig; #[cfg(not(feature = "rpc"))] +use papyrus_config::ParamPrivacyInput; +#[cfg(not(feature = "rpc"))] use papyrus_config::dumping::ser_param; use papyrus_config::dumping::{ - append_sub_config_name, ser_optional_sub_config, ser_pointer_target_param, - set_pointing_param_paths, ConfigPointers, Pointers, SerializeConfig, + ConfigPointers, Pointers, SerializeConfig, append_sub_config_name, ser_optional_sub_config, + ser_pointer_target_param, set_pointing_param_paths, }; use papyrus_config::loading::load_and_process_config; -#[cfg(not(feature = "rpc"))] -use papyrus_config::ParamPrivacyInput; use papyrus_config::{ConfigError, ParamPath, SerializedParam}; use papyrus_monitoring_gateway::MonitoringGatewayConfig; use papyrus_network::NetworkConfig; use papyrus_p2p_sync::client::{P2PSyncClient, P2PSyncClientConfig}; #[cfg(feature = "rpc")] use papyrus_rpc::RpcConfig; -use papyrus_storage::db::DbConfig; use papyrus_storage::StorageConfig; -use papyrus_sync::sources::central::CentralSourceConfig; +use papyrus_storage::db::DbConfig; use papyrus_sync::SyncConfig; +use papyrus_sync::sources::central::CentralSourceConfig; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use starknet_api::core::ChainId; @@ -57,7 +57,7 @@ pub static CONFIG_POINTERS: LazyLock = LazyLock::new(|| { "network.chain_id", "rpc.chain_id", "storage.db_config.chain_id", - ]) + ]), ), ( ser_pointer_target_param( @@ -69,7 +69,7 @@ pub static CONFIG_POINTERS: LazyLock = LazyLock::new(|| { "rpc.starknet_url", "central.starknet_url", "monitoring_gateway.starknet_url", - ]) + ]), ), ( ser_pointer_target_param( @@ -80,7 +80,7 @@ pub static CONFIG_POINTERS: LazyLock = LazyLock::new(|| { set_pointing_param_paths(&[ "rpc.collect_metrics", "monitoring_gateway.collect_metrics", - ]) + ]), ), ] }); diff --git a/crates/papyrus_node/src/main.rs b/crates/papyrus_node/src/main.rs index 3af3d3e536..81c855095d 100644 --- a/crates/papyrus_node/src/main.rs +++ b/crates/papyrus_node/src/main.rs @@ -2,7 +2,7 @@ use std::env::args; use papyrus_config::ConfigError; use papyrus_node::config::NodeConfig; -use papyrus_node::run::{run, PapyrusResources, PapyrusTaskHandles}; +use papyrus_node::run::{PapyrusResources, PapyrusTaskHandles, run}; #[tokio::main] async fn main() -> anyhow::Result<()> { diff --git a/crates/papyrus_node/src/run.rs b/crates/papyrus_node/src/run.rs index e26b379759..2323841c06 100644 --- a/crates/papyrus_node/src/run.rs +++ b/crates/papyrus_node/src/run.rs @@ -18,29 +18,29 @@ use papyrus_consensus_orchestrator::papyrus_consensus_context::PapyrusConsensusC use papyrus_monitoring_gateway::MonitoringServer; use papyrus_network::gossipsub_impl::Topic; use papyrus_network::network_manager::{BroadcastTopicChannels, NetworkManager}; -use papyrus_network::{network_manager, NetworkConfig}; +use papyrus_network::{NetworkConfig, network_manager}; use papyrus_p2p_sync::client::{P2PSyncClient, P2PSyncClientChannels}; use papyrus_p2p_sync::server::{P2PSyncServer, P2PSyncServerChannels}; -use papyrus_p2p_sync::{Protocol, BUFFER_SIZE}; +use papyrus_p2p_sync::{BUFFER_SIZE, Protocol}; use papyrus_protobuf::consensus::{ProposalPart, StreamMessage}; #[cfg(feature = "rpc")] use papyrus_rpc::run_server; use papyrus_storage::storage_metrics::update_storage_metrics; -use papyrus_storage::{open_storage, StorageReader, StorageWriter}; +use papyrus_storage::{StorageReader, StorageWriter, open_storage}; use papyrus_sync::sources::base_layer::{BaseLayerSourceError, EthereumBaseLayerSource}; use papyrus_sync::sources::central::{CentralError, CentralSource, CentralSourceConfig}; use papyrus_sync::sources::pending::PendingSource; use papyrus_sync::{StateSync, SyncConfig}; use starknet_api::block::{BlockHash, BlockHashAndNumber}; use starknet_api::felt; -use starknet_client::reader::objects::pending_data::{PendingBlock, PendingBlockOrDeprecated}; use starknet_client::reader::PendingData; +use starknet_client::reader::objects::pending_data::{PendingBlock, PendingBlockOrDeprecated}; use tokio::sync::RwLock; use tokio::task::JoinHandle; use tracing::metadata::LevelFilter; -use tracing::{debug, debug_span, error, info, warn, Instrument}; +use tracing::{Instrument, debug, debug_span, error, info, warn}; use tracing_subscriber::prelude::*; -use tracing_subscriber::{fmt, EnvFilter}; +use tracing_subscriber::{EnvFilter, fmt}; use crate::config::NodeConfig; use crate::version::VERSION_FULL; diff --git a/crates/papyrus_node/src/run_test.rs b/crates/papyrus_node/src/run_test.rs index c1fec1be70..8078e2456c 100644 --- a/crates/papyrus_node/src/run_test.rs +++ b/crates/papyrus_node/src/run_test.rs @@ -1,13 +1,13 @@ use std::time::Duration; use metrics_exporter_prometheus::PrometheusBuilder; -use papyrus_storage::{open_storage, StorageConfig}; +use papyrus_storage::{StorageConfig, open_storage}; use papyrus_test_utils::prometheus_is_contained; use tempfile::TempDir; use crate::config::NodeConfig; use crate::run::{ - run_threads, spawn_storage_metrics_collector, PapyrusResources, PapyrusTaskHandles, + PapyrusResources, PapyrusTaskHandles, run_threads, spawn_storage_metrics_collector, }; // The mission of this test is to ensure that if an error is returned from one of the spawned tasks, diff --git a/crates/papyrus_p2p_sync/src/client/class.rs b/crates/papyrus_p2p_sync/src/client/class.rs index 7418d4e010..4df8715673 100644 --- a/crates/papyrus_p2p_sync/src/client/class.rs +++ b/crates/papyrus_p2p_sync/src/client/class.rs @@ -15,7 +15,7 @@ use starknet_api::state::{DeclaredClasses, DeprecatedDeclaredClasses}; use super::stream_builder::{ BadPeerError, BlockData, BlockNumberLimit, DataStreamBuilder, ParseDataError, }; -use super::{P2PSyncClientError, NETWORK_DATA_TIMEOUT}; +use super::{NETWORK_DATA_TIMEOUT, P2PSyncClientError}; impl BlockData for (DeclaredClasses, DeprecatedDeclaredClasses, BlockNumber) { fn write_to_storage( diff --git a/crates/papyrus_p2p_sync/src/client/class_test.rs b/crates/papyrus_p2p_sync/src/client/class_test.rs index 69b5ffafb6..98eac1fbe7 100644 --- a/crates/papyrus_p2p_sync/src/client/class_test.rs +++ b/crates/papyrus_p2p_sync/src/client/class_test.rs @@ -7,7 +7,7 @@ use papyrus_protobuf::sync::{ Query, StateDiffChunk, }; use papyrus_storage::class::ClassStorageReader; -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use rand::{Rng, RngCore}; use rand_chacha::ChaCha8Rng; use starknet_api::block::BlockNumber; @@ -16,8 +16,8 @@ use starknet_api::deprecated_contract_class::ContractClass as DeprecatedContract use starknet_api::state::SierraContractClass; use super::test_utils::{ - setup, wait_for_marker, DataType, TestArgs, CLASS_DIFF_QUERY_LENGTH, HEADER_QUERY_LENGTH, - SLEEP_DURATION_TO_LET_SYNC_ADVANCE, TIMEOUT_FOR_TEST, + CLASS_DIFF_QUERY_LENGTH, DataType, HEADER_QUERY_LENGTH, SLEEP_DURATION_TO_LET_SYNC_ADVANCE, + TIMEOUT_FOR_TEST, TestArgs, setup, wait_for_marker, }; use crate::client::state_diff_test::run_state_diff_sync; diff --git a/crates/papyrus_p2p_sync/src/client/header.rs b/crates/papyrus_p2p_sync/src/client/header.rs index 5c21d411d4..9700547d44 100644 --- a/crates/papyrus_p2p_sync/src/client/header.rs +++ b/crates/papyrus_p2p_sync/src/client/header.rs @@ -13,7 +13,7 @@ use tracing::debug; use super::stream_builder::{ BadPeerError, BlockData, BlockNumberLimit, DataStreamBuilder, ParseDataError, }; -use super::{P2PSyncClientError, ALLOWED_SIGNATURES_LENGTH, NETWORK_DATA_TIMEOUT}; +use super::{ALLOWED_SIGNATURES_LENGTH, NETWORK_DATA_TIMEOUT, P2PSyncClientError}; impl BlockData for SignedBlockHeader { #[allow(clippy::as_conversions)] // FIXME: use int metrics so `as f64` may be removed. diff --git a/crates/papyrus_p2p_sync/src/client/header_test.rs b/crates/papyrus_p2p_sync/src/client/header_test.rs index 8d41a86588..7a3ca1c8b8 100644 --- a/crates/papyrus_p2p_sync/src/client/header_test.rs +++ b/crates/papyrus_p2p_sync/src/client/header_test.rs @@ -10,9 +10,10 @@ use starknet_api::block::{BlockHeader, BlockHeaderWithoutHash, BlockNumber}; use tokio::time::timeout; use super::test_utils::{ - create_block_hashes_and_signatures, random_header, run_test, setup, wait_for_marker, Action, - DataType, TestArgs, HEADER_QUERY_LENGTH, SLEEP_DURATION_TO_LET_SYNC_ADVANCE, - TIMEOUT_FOR_NEW_QUERY_AFTER_PARTIAL_RESPONSE, TIMEOUT_FOR_TEST, WAIT_PERIOD_FOR_NEW_DATA, + Action, DataType, HEADER_QUERY_LENGTH, SLEEP_DURATION_TO_LET_SYNC_ADVANCE, + TIMEOUT_FOR_NEW_QUERY_AFTER_PARTIAL_RESPONSE, TIMEOUT_FOR_TEST, TestArgs, + WAIT_PERIOD_FOR_NEW_DATA, create_block_hashes_and_signatures, random_header, run_test, setup, + wait_for_marker, }; #[tokio::test] @@ -185,26 +186,23 @@ async fn sync_sends_new_header_query_if_it_got_partial_responses() { #[tokio::test] async fn wrong_block_number() { - run_test( - HashMap::from([(DataType::Header, 1)]), - vec![ - // We already validate the query content in other tests. - Action::ReceiveQuery(Box::new(|_query| ()), DataType::Header), - Action::SendHeader(DataOrFin(Some(random_header( - &mut get_rng(), - BlockNumber(1), - None, - None, - )))), - Action::ValidateReportSent(DataType::Header), - Action::CheckStorage(Box::new(|reader| { - async move { - assert_eq!(0, reader.begin_ro_txn().unwrap().get_header_marker().unwrap().0); - } - .boxed() - })), - ], - ) + run_test(HashMap::from([(DataType::Header, 1)]), vec![ + // We already validate the query content in other tests. + Action::ReceiveQuery(Box::new(|_query| ()), DataType::Header), + Action::SendHeader(DataOrFin(Some(random_header( + &mut get_rng(), + BlockNumber(1), + None, + None, + )))), + Action::ValidateReportSent(DataType::Header), + Action::CheckStorage(Box::new(|reader| { + async move { + assert_eq!(0, reader.begin_ro_txn().unwrap().get_header_marker().unwrap().0); + } + .boxed() + })), + ]) .await; } diff --git a/crates/papyrus_p2p_sync/src/client/mod.rs b/crates/papyrus_p2p_sync/src/client/mod.rs index d31936360d..2ca9408375 100644 --- a/crates/papyrus_p2p_sync/src/client/mod.rs +++ b/crates/papyrus_p2p_sync/src/client/mod.rs @@ -18,12 +18,12 @@ use std::collections::BTreeMap; use std::time::Duration; use class::ClassStreamBuilder; -use futures::channel::mpsc::SendError; use futures::Stream; +use futures::channel::mpsc::SendError; use header::HeaderStreamBuilder; use papyrus_common::pending_classes::ApiContractClass; use papyrus_config::converters::deserialize_milliseconds_to_duration; -use papyrus_config::dumping::{ser_optional_param, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_optional_param, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use papyrus_network::network_manager::SqmrClientSender; use papyrus_protobuf::sync::{ diff --git a/crates/papyrus_p2p_sync/src/client/state_diff.rs b/crates/papyrus_p2p_sync/src/client/state_diff.rs index 63394874fc..1e0a6ccc92 100644 --- a/crates/papyrus_p2p_sync/src/client/state_diff.rs +++ b/crates/papyrus_p2p_sync/src/client/state_diff.rs @@ -17,7 +17,7 @@ use super::stream_builder::BadPeerError; use crate::client::stream_builder::{ BlockData, BlockNumberLimit, DataStreamBuilder, ParseDataError, }; -use crate::client::{P2PSyncClientError, NETWORK_DATA_TIMEOUT}; +use crate::client::{NETWORK_DATA_TIMEOUT, P2PSyncClientError}; impl BlockData for (ThinStateDiff, BlockNumber) { #[latency_histogram("p2p_sync_state_diff_write_to_storage_latency_seconds", true)] diff --git a/crates/papyrus_p2p_sync/src/client/state_diff_test.rs b/crates/papyrus_p2p_sync/src/client/state_diff_test.rs index 011199c94e..4953ed920e 100644 --- a/crates/papyrus_p2p_sync/src/client/state_diff_test.rs +++ b/crates/papyrus_p2p_sync/src/client/state_diff_test.rs @@ -9,7 +9,7 @@ use papyrus_protobuf::sync::{ Query, SignedBlockHeader, StateDiffChunk, }; use papyrus_storage::state::StateStorageReader; -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use rand::RngCore; use rand_chacha::ChaCha8Rng; use starknet_api::block::{BlockHeader, BlockHeaderWithoutHash, BlockNumber}; @@ -17,12 +17,12 @@ use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce}; use starknet_api::state::{StorageKey, ThinStateDiff}; use starknet_types_core::felt::Felt; use static_assertions::const_assert; -use tokio::sync::mpsc::{channel, Receiver}; +use tokio::sync::mpsc::{Receiver, channel}; use super::test_utils::{ - create_block_hashes_and_signatures, setup, wait_for_marker, DataType, HeaderTestPayload, - StateDiffTestPayload, TestArgs, HEADER_QUERY_LENGTH, SLEEP_DURATION_TO_LET_SYNC_ADVANCE, - STATE_DIFF_QUERY_LENGTH, TIMEOUT_FOR_TEST, WAIT_PERIOD_FOR_NEW_DATA, + DataType, HEADER_QUERY_LENGTH, HeaderTestPayload, SLEEP_DURATION_TO_LET_SYNC_ADVANCE, + STATE_DIFF_QUERY_LENGTH, StateDiffTestPayload, TIMEOUT_FOR_TEST, TestArgs, + WAIT_PERIOD_FOR_NEW_DATA, create_block_hashes_and_signatures, setup, wait_for_marker, }; use super::{P2PSyncClientConfig, StateDiffQuery}; @@ -159,13 +159,10 @@ async fn state_diff_empty_state_diff() { // returned from parse_data_for_block. We currently dont have a way to check this. #[tokio::test] async fn state_diff_stopped_in_middle() { - validate_state_diff_fails( - vec![2], - vec![ - Some(StateDiffChunk::DeprecatedDeclaredClass(DeprecatedDeclaredClass::default())), - None, - ], - ) + validate_state_diff_fails(vec![2], vec![ + Some(StateDiffChunk::DeprecatedDeclaredClass(DeprecatedDeclaredClass::default())), + None, + ]) .await; } @@ -173,18 +170,15 @@ async fn state_diff_stopped_in_middle() { // returned from parse_data_for_block. We currently dont have a way to check this. #[tokio::test] async fn state_diff_not_split_correctly() { - validate_state_diff_fails( - vec![2], - vec![ - Some(StateDiffChunk::DeprecatedDeclaredClass(DeprecatedDeclaredClass::default())), - Some(StateDiffChunk::ContractDiff(ContractDiff { - contract_address: ContractAddress::default(), - class_hash: Some(ClassHash::default()), - nonce: Some(Nonce::default()), - ..Default::default() - })), - ], - ) + validate_state_diff_fails(vec![2], vec![ + Some(StateDiffChunk::DeprecatedDeclaredClass(DeprecatedDeclaredClass::default())), + Some(StateDiffChunk::ContractDiff(ContractDiff { + contract_address: ContractAddress::default(), + class_hash: Some(ClassHash::default()), + nonce: Some(Nonce::default()), + ..Default::default() + })), + ]) .await; } @@ -192,79 +186,64 @@ async fn state_diff_not_split_correctly() { // was returned from parse_data_for_block. We currently dont have a way to check this. #[tokio::test] async fn state_diff_conflicting() { - validate_state_diff_fails( - vec![2], - vec![ - Some(StateDiffChunk::ContractDiff(ContractDiff { - contract_address: ContractAddress::default(), - class_hash: Some(ClassHash::default()), - ..Default::default() - })), - Some(StateDiffChunk::ContractDiff(ContractDiff { - contract_address: ContractAddress::default(), - class_hash: Some(ClassHash::default()), - ..Default::default() - })), - ], - ) + validate_state_diff_fails(vec![2], vec![ + Some(StateDiffChunk::ContractDiff(ContractDiff { + contract_address: ContractAddress::default(), + class_hash: Some(ClassHash::default()), + ..Default::default() + })), + Some(StateDiffChunk::ContractDiff(ContractDiff { + contract_address: ContractAddress::default(), + class_hash: Some(ClassHash::default()), + ..Default::default() + })), + ]) .await; - validate_state_diff_fails( - vec![2], - vec![ - Some(StateDiffChunk::ContractDiff(ContractDiff { - contract_address: ContractAddress::default(), - storage_diffs: indexmap! { StorageKey::default() => Felt::default() }, - ..Default::default() - })), - Some(StateDiffChunk::ContractDiff(ContractDiff { - contract_address: ContractAddress::default(), - storage_diffs: indexmap! { StorageKey::default() => Felt::default() }, - ..Default::default() - })), - ], - ) + validate_state_diff_fails(vec![2], vec![ + Some(StateDiffChunk::ContractDiff(ContractDiff { + contract_address: ContractAddress::default(), + storage_diffs: indexmap! { StorageKey::default() => Felt::default() }, + ..Default::default() + })), + Some(StateDiffChunk::ContractDiff(ContractDiff { + contract_address: ContractAddress::default(), + storage_diffs: indexmap! { StorageKey::default() => Felt::default() }, + ..Default::default() + })), + ]) .await; - validate_state_diff_fails( - vec![2], - vec![ - Some(StateDiffChunk::DeclaredClass(DeclaredClass { - class_hash: ClassHash::default(), - compiled_class_hash: CompiledClassHash::default(), - })), - Some(StateDiffChunk::DeclaredClass(DeclaredClass { - class_hash: ClassHash::default(), - compiled_class_hash: CompiledClassHash::default(), - })), - ], - ) + validate_state_diff_fails(vec![2], vec![ + Some(StateDiffChunk::DeclaredClass(DeclaredClass { + class_hash: ClassHash::default(), + compiled_class_hash: CompiledClassHash::default(), + })), + Some(StateDiffChunk::DeclaredClass(DeclaredClass { + class_hash: ClassHash::default(), + compiled_class_hash: CompiledClassHash::default(), + })), + ]) .await; - validate_state_diff_fails( - vec![2], - vec![ - Some(StateDiffChunk::DeprecatedDeclaredClass(DeprecatedDeclaredClass { - class_hash: ClassHash::default(), - })), - Some(StateDiffChunk::DeprecatedDeclaredClass(DeprecatedDeclaredClass { - class_hash: ClassHash::default(), - })), - ], - ) + validate_state_diff_fails(vec![2], vec![ + Some(StateDiffChunk::DeprecatedDeclaredClass(DeprecatedDeclaredClass { + class_hash: ClassHash::default(), + })), + Some(StateDiffChunk::DeprecatedDeclaredClass(DeprecatedDeclaredClass { + class_hash: ClassHash::default(), + })), + ]) .await; - validate_state_diff_fails( - vec![2], - vec![ - Some(StateDiffChunk::ContractDiff(ContractDiff { - contract_address: ContractAddress::default(), - nonce: Some(Nonce::default()), - ..Default::default() - })), - Some(StateDiffChunk::ContractDiff(ContractDiff { - contract_address: ContractAddress::default(), - nonce: Some(Nonce::default()), - ..Default::default() - })), - ], - ) + validate_state_diff_fails(vec![2], vec![ + Some(StateDiffChunk::ContractDiff(ContractDiff { + contract_address: ContractAddress::default(), + nonce: Some(Nonce::default()), + ..Default::default() + })), + Some(StateDiffChunk::ContractDiff(ContractDiff { + contract_address: ContractAddress::default(), + nonce: Some(Nonce::default()), + ..Default::default() + })), + ]) .await; } diff --git a/crates/papyrus_p2p_sync/src/client/stream_builder.rs b/crates/papyrus_p2p_sync/src/client/stream_builder.rs index 36718a939d..57846ed259 100644 --- a/crates/papyrus_p2p_sync/src/client/stream_builder.rs +++ b/crates/papyrus_p2p_sync/src/client/stream_builder.rs @@ -2,10 +2,10 @@ use std::cmp::min; use std::time::Duration; use async_stream::stream; +use futures::StreamExt; use futures::channel::mpsc::Receiver; use futures::future::BoxFuture; use futures::stream::BoxStream; -use futures::StreamExt; use papyrus_network::network_manager::{ClientResponsesManager, SqmrClientSender}; use papyrus_protobuf::converters::ProtobufConversionError; use papyrus_protobuf::sync::{BlockHashOrNumber, DataOrFin, Direction, Query}; diff --git a/crates/papyrus_p2p_sync/src/client/test_utils.rs b/crates/papyrus_p2p_sync/src/client/test_utils.rs index 6cb6676920..759fbe404d 100644 --- a/crates/papyrus_p2p_sync/src/client/test_utils.rs +++ b/crates/papyrus_p2p_sync/src/client/test_utils.rs @@ -2,24 +2,24 @@ use std::collections::HashMap; use std::fmt::Debug; use std::time::{Duration, Instant}; -use futures::future::BoxFuture; use futures::StreamExt; +use futures::future::BoxFuture; use lazy_static::lazy_static; use papyrus_common::pending_classes::ApiContractClass; +use papyrus_network::network_manager::GenericReceiver; use papyrus_network::network_manager::test_utils::{ - mock_register_sqmr_protocol_client, MockClientResponsesManager, + MockClientResponsesManager, mock_register_sqmr_protocol_client, }; -use papyrus_network::network_manager::GenericReceiver; use papyrus_protobuf::sync::{ ClassQuery, DataOrFin, HeaderQuery, Query, SignedBlockHeader, StateDiffChunk, StateDiffQuery, TransactionQuery, }; +use papyrus_storage::StorageReader; use papyrus_storage::body::BodyStorageReader; use papyrus_storage::class::ClassStorageReader; use papyrus_storage::header::HeaderStorageReader; use papyrus_storage::state::StateStorageReader; use papyrus_storage::test_utils::get_test_storage; -use papyrus_storage::StorageReader; use papyrus_test_utils::GetTestInstance; use rand::{Rng, RngCore}; use rand_chacha::ChaCha8Rng; diff --git a/crates/papyrus_p2p_sync/src/client/transaction.rs b/crates/papyrus_p2p_sync/src/client/transaction.rs index e9d4513494..18328d1ba4 100644 --- a/crates/papyrus_p2p_sync/src/client/transaction.rs +++ b/crates/papyrus_p2p_sync/src/client/transaction.rs @@ -11,7 +11,7 @@ use starknet_api::transaction::FullTransaction; use super::stream_builder::{ BadPeerError, BlockData, BlockNumberLimit, DataStreamBuilder, ParseDataError, }; -use super::{P2PSyncClientError, NETWORK_DATA_TIMEOUT}; +use super::{NETWORK_DATA_TIMEOUT, P2PSyncClientError}; impl BlockData for (BlockBody, BlockNumber) { fn write_to_storage( diff --git a/crates/papyrus_p2p_sync/src/client/transaction_test.rs b/crates/papyrus_p2p_sync/src/client/transaction_test.rs index 3bc53f122b..2262a0a5f6 100644 --- a/crates/papyrus_p2p_sync/src/client/transaction_test.rs +++ b/crates/papyrus_p2p_sync/src/client/transaction_test.rs @@ -10,10 +10,10 @@ use starknet_api::block::{BlockBody, BlockHeader, BlockHeaderWithoutHash, BlockN use starknet_api::transaction::FullTransaction; use super::test_utils::{ - create_block_hashes_and_signatures, setup, TestArgs, HEADER_QUERY_LENGTH, - SLEEP_DURATION_TO_LET_SYNC_ADVANCE, TRANSACTION_QUERY_LENGTH, WAIT_PERIOD_FOR_NEW_DATA, + HEADER_QUERY_LENGTH, SLEEP_DURATION_TO_LET_SYNC_ADVANCE, TRANSACTION_QUERY_LENGTH, TestArgs, + WAIT_PERIOD_FOR_NEW_DATA, create_block_hashes_and_signatures, setup, }; -use crate::client::test_utils::{wait_for_marker, DataType, TIMEOUT_FOR_TEST}; +use crate::client::test_utils::{DataType, TIMEOUT_FOR_TEST, wait_for_marker}; #[tokio::test] async fn transaction_basic_flow() { diff --git a/crates/papyrus_p2p_sync/src/server/mod.rs b/crates/papyrus_p2p_sync/src/server/mod.rs index 40a090ec28..9162d362b0 100644 --- a/crates/papyrus_p2p_sync/src/server/mod.rs +++ b/crates/papyrus_p2p_sync/src/server/mod.rs @@ -13,7 +13,7 @@ use papyrus_storage::body::BodyStorageReader; use papyrus_storage::class::ClassStorageReader; use papyrus_storage::header::HeaderStorageReader; use papyrus_storage::state::StateStorageReader; -use papyrus_storage::{db, StorageReader, StorageTxn}; +use papyrus_storage::{StorageReader, StorageTxn, db}; use starknet_api::block::BlockNumber; use starknet_api::core::ClassHash; use starknet_api::state::ThinStateDiff; diff --git a/crates/papyrus_p2p_sync/src/server/test.rs b/crates/papyrus_p2p_sync/src/server/test.rs index 1a4f392017..2b8c4caf69 100644 --- a/crates/papyrus_p2p_sync/src/server/test.rs +++ b/crates/papyrus_p2p_sync/src/server/test.rs @@ -1,14 +1,14 @@ use std::fmt::Debug; -use futures::channel::mpsc::Sender; use futures::StreamExt; +use futures::channel::mpsc::Sender; use lazy_static::lazy_static; use papyrus_common::pending_classes::ApiContractClass; use papyrus_common::state::create_random_state_diff; +use papyrus_network::network_manager::ServerQueryManager; use papyrus_network::network_manager::test_utils::{ create_test_server_query_manager, mock_register_sqmr_protocol_server, }; -use papyrus_network::network_manager::ServerQueryManager; use papyrus_protobuf::converters::ProtobufConversionError; use papyrus_protobuf::sync::{ BlockHashOrNumber, ClassQuery, DataOrFin, Direction, EventQuery, HeaderQuery, Query, @@ -20,7 +20,7 @@ use papyrus_storage::header::{HeaderStorageReader, HeaderStorageWriter}; use papyrus_storage::state::StateStorageWriter; use papyrus_storage::test_utils::get_test_storage; use papyrus_storage::{StorageReader, StorageWriter}; -use papyrus_test_utils::{get_rng, get_test_body, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng, get_test_body}; use rand::random; use starknet_api::block::{ BlockBody, BlockHash, BlockHeader, BlockHeaderWithoutHash, BlockNumber, BlockSignature, @@ -31,7 +31,7 @@ use starknet_api::transaction::{ Event, FullTransaction, Transaction, TransactionHash, TransactionOutput, }; -use super::{split_thin_state_diff, FetchBlockDataFromDb, P2PSyncServer, P2PSyncServerChannels}; +use super::{FetchBlockDataFromDb, P2PSyncServer, P2PSyncServerChannels, split_thin_state_diff}; use crate::server::register_query; const BUFFER_SIZE: usize = 10; const NUM_OF_BLOCKS: usize = 10; diff --git a/crates/papyrus_proc_macros/src/lib.rs b/crates/papyrus_proc_macros/src/lib.rs index ed9ecb4311..88b033d13f 100644 --- a/crates/papyrus_proc_macros/src/lib.rs +++ b/crates/papyrus_proc_macros/src/lib.rs @@ -1,11 +1,11 @@ use std::str::FromStr; use proc_macro::TokenStream; -use quote::{quote, ToTokens}; +use quote::{ToTokens, quote}; use syn::parse::{Parse, ParseStream, Result}; use syn::{ - parse_macro_input, DeriveInput, ExprLit, Ident, ItemFn, ItemTrait, LitBool, LitStr, Meta, - Token, TraitItem, + DeriveInput, ExprLit, Ident, ItemFn, ItemTrait, LitBool, LitStr, Meta, Token, TraitItem, + parse_macro_input, }; /// This macro is a wrapper around the "rpc" macro supplied by the jsonrpsee library that generates diff --git a/crates/papyrus_protobuf/build.rs b/crates/papyrus_protobuf/build.rs index f0e6ca9848..f6da55625d 100644 --- a/crates/papyrus_protobuf/build.rs +++ b/crates/papyrus_protobuf/build.rs @@ -18,11 +18,7 @@ fn get_valid_preinstalled_protoc_version() -> Option<(u32, u32)> { }; let (major, minor) = parse_protoc_version(protoc_version_str)?; // Protoc versions before 3.15 are not supported. - if (major < 3) || (major == 3 && minor < 15) { - None - } else { - Some((major, minor)) - } + if (major < 3) || (major == 3 && minor < 15) { None } else { Some((major, minor)) } } /// Return Result<(major, minor)> numbers. If the minor doesn't exist, return 0 as minor. If diff --git a/crates/papyrus_protobuf/src/converters/class.rs b/crates/papyrus_protobuf/src/converters/class.rs index 2a34a5d219..cf7a5eda70 100644 --- a/crates/papyrus_protobuf/src/converters/class.rs +++ b/crates/papyrus_protobuf/src/converters/class.rs @@ -17,8 +17,8 @@ use starknet_api::rpc_transaction::EntryPointByType; use starknet_api::{deprecated_contract_class, state}; use starknet_types_core::felt::Felt; -use super::common::volition_domain_to_enum_int; use super::ProtobufConversionError; +use super::common::volition_domain_to_enum_int; use crate::sync::{ClassQuery, DataOrFin, Query}; use crate::{auto_impl_into_and_try_from_vec_u8, protobuf}; diff --git a/crates/papyrus_protobuf/src/converters/class_test.rs b/crates/papyrus_protobuf/src/converters/class_test.rs index 1768f929fd..e85c470c29 100644 --- a/crates/papyrus_protobuf/src/converters/class_test.rs +++ b/crates/papyrus_protobuf/src/converters/class_test.rs @@ -1,4 +1,4 @@ -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use starknet_api::deprecated_contract_class::ContractClass; use crate::protobuf::Cairo0Class; diff --git a/crates/papyrus_protobuf/src/converters/consensus_test.rs b/crates/papyrus_protobuf/src/converters/consensus_test.rs index fa75b54b23..05b190aa79 100644 --- a/crates/papyrus_protobuf/src/converters/consensus_test.rs +++ b/crates/papyrus_protobuf/src/converters/consensus_test.rs @@ -1,4 +1,4 @@ -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use starknet_api::execution_resources::GasAmount; use starknet_api::transaction::fields::ValidResourceBounds; use starknet_api::transaction::{ diff --git a/crates/papyrus_protobuf/src/converters/event_test.rs b/crates/papyrus_protobuf/src/converters/event_test.rs index 4a0a3cce58..13dcec0180 100644 --- a/crates/papyrus_protobuf/src/converters/event_test.rs +++ b/crates/papyrus_protobuf/src/converters/event_test.rs @@ -1,4 +1,4 @@ -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use starknet_api::transaction::{Event, TransactionHash}; use crate::sync::DataOrFin; diff --git a/crates/papyrus_protobuf/src/converters/header.rs b/crates/papyrus_protobuf/src/converters/header.rs index 359d0a15cf..30562cc5a5 100644 --- a/crates/papyrus_protobuf/src/converters/header.rs +++ b/crates/papyrus_protobuf/src/converters/header.rs @@ -14,8 +14,8 @@ use starknet_api::core::{ use starknet_api::crypto::utils::Signature; use starknet_api::hash::PoseidonHash; -use super::common::{enum_int_to_l1_data_availability_mode, l1_data_availability_mode_to_enum_int}; use super::ProtobufConversionError; +use super::common::{enum_int_to_l1_data_availability_mode, l1_data_availability_mode_to_enum_int}; use crate::sync::{DataOrFin, HeaderQuery, Query, SignedBlockHeader}; use crate::{auto_impl_into_and_try_from_vec_u8, protobuf}; @@ -246,7 +246,7 @@ impl From<(BlockHeader, Vec)> for protobuf::SignedBlockHeader { .expect("Converting usize to u64 failed"), root: header .state_diff_commitment - .map(|state_diff_commitment| state_diff_commitment.0 .0.into()), + .map(|state_diff_commitment| state_diff_commitment.0.0.into()), }); Self { block_hash: Some(header.block_hash.into()), diff --git a/crates/papyrus_protobuf/src/converters/header_test.rs b/crates/papyrus_protobuf/src/converters/header_test.rs index 4afa000486..8e99eb364c 100644 --- a/crates/papyrus_protobuf/src/converters/header_test.rs +++ b/crates/papyrus_protobuf/src/converters/header_test.rs @@ -1,4 +1,4 @@ -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use crate::sync::{DataOrFin, HeaderQuery, SignedBlockHeader}; diff --git a/crates/papyrus_protobuf/src/converters/receipt.rs b/crates/papyrus_protobuf/src/converters/receipt.rs index 436039031e..7488a8abb1 100644 --- a/crates/papyrus_protobuf/src/converters/receipt.rs +++ b/crates/papyrus_protobuf/src/converters/receipt.rs @@ -10,8 +10,8 @@ use starknet_api::transaction::{ }; use starknet_types_core::felt::Felt; -use super::common::try_from_starkfelt_to_u128; use super::ProtobufConversionError; +use super::common::try_from_starkfelt_to_u128; use crate::protobuf; impl TryFrom for TransactionOutput { diff --git a/crates/papyrus_protobuf/src/converters/rpc_transaction_test.rs b/crates/papyrus_protobuf/src/converters/rpc_transaction_test.rs index 54bbc7b0d2..3252da7ca5 100644 --- a/crates/papyrus_protobuf/src/converters/rpc_transaction_test.rs +++ b/crates/papyrus_protobuf/src/converters/rpc_transaction_test.rs @@ -1,5 +1,5 @@ use lazy_static::lazy_static; -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use starknet_api::block::GasPrice; use starknet_api::execution_resources::GasAmount; use starknet_api::rpc_transaction::{ diff --git a/crates/papyrus_protobuf/src/converters/state_diff.rs b/crates/papyrus_protobuf/src/converters/state_diff.rs index 234ae7dd4b..4127dce6f7 100644 --- a/crates/papyrus_protobuf/src/converters/state_diff.rs +++ b/crates/papyrus_protobuf/src/converters/state_diff.rs @@ -8,8 +8,8 @@ use starknet_api::data_availability::DataAvailabilityMode; use starknet_api::state::{StorageKey, ThinStateDiff}; use starknet_types_core::felt::Felt; -use super::common::volition_domain_to_enum_int; use super::ProtobufConversionError; +use super::common::volition_domain_to_enum_int; use crate::sync::{ ContractDiff, DataOrFin, DeclaredClass, DeprecatedDeclaredClass, Query, StateDiffChunk, StateDiffQuery, diff --git a/crates/papyrus_protobuf/src/converters/state_diff_test.rs b/crates/papyrus_protobuf/src/converters/state_diff_test.rs index 3e472ba02e..631fc7b909 100644 --- a/crates/papyrus_protobuf/src/converters/state_diff_test.rs +++ b/crates/papyrus_protobuf/src/converters/state_diff_test.rs @@ -1,4 +1,4 @@ -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use crate::sync::{ ContractDiff, DataOrFin, DeclaredClass, DeprecatedDeclaredClass, StateDiffChunk, StateDiffQuery, diff --git a/crates/papyrus_protobuf/src/converters/test_instances.rs b/crates/papyrus_protobuf/src/converters/test_instances.rs index 1ed71e3614..062bd52ad1 100644 --- a/crates/papyrus_protobuf/src/converters/test_instances.rs +++ b/crates/papyrus_protobuf/src/converters/test_instances.rs @@ -1,4 +1,4 @@ -use papyrus_test_utils::{auto_impl_get_test_instance, get_number_of_variants, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, auto_impl_get_test_instance, get_number_of_variants}; use rand::Rng; use starknet_api::block::{BlockHash, BlockNumber}; use starknet_api::core::ContractAddress; diff --git a/crates/papyrus_protobuf/src/converters/transaction.rs b/crates/papyrus_protobuf/src/converters/transaction.rs index a2288dd8a0..15c9c1071d 100644 --- a/crates/papyrus_protobuf/src/converters/transaction.rs +++ b/crates/papyrus_protobuf/src/converters/transaction.rs @@ -20,11 +20,11 @@ use starknet_api::transaction::{ }; use starknet_types_core::felt::Felt; +use super::ProtobufConversionError; use super::common::{ - enum_int_to_volition_domain, try_from_starkfelt_to_u128, try_from_starkfelt_to_u32, + enum_int_to_volition_domain, try_from_starkfelt_to_u32, try_from_starkfelt_to_u128, volition_domain_to_enum_int, }; -use super::ProtobufConversionError; use crate::sync::{DataOrFin, Query, TransactionQuery}; use crate::{auto_impl_into_and_try_from_vec_u8, protobuf}; diff --git a/crates/papyrus_protobuf/src/converters/transaction_test.rs b/crates/papyrus_protobuf/src/converters/transaction_test.rs index f04f9d0637..f9dc505930 100644 --- a/crates/papyrus_protobuf/src/converters/transaction_test.rs +++ b/crates/papyrus_protobuf/src/converters/transaction_test.rs @@ -1,5 +1,5 @@ use lazy_static::lazy_static; -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use rand::random; use starknet_api::block::GasPrice; use starknet_api::execution_resources::{Builtin, ExecutionResources, GasAmount, GasVector}; diff --git a/crates/papyrus_protobuf/src/sync.rs b/crates/papyrus_protobuf/src/sync.rs index cd6a20d23f..e0eab1d3a1 100644 --- a/crates/papyrus_protobuf/src/sync.rs +++ b/crates/papyrus_protobuf/src/sync.rs @@ -2,7 +2,7 @@ use std::fmt::Debug; use indexmap::IndexMap; #[cfg(any(feature = "testing", test))] -use papyrus_test_utils::{auto_impl_get_test_instance, get_number_of_variants, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, auto_impl_get_test_instance, get_number_of_variants}; use starknet_api::block::{BlockHash, BlockHeader, BlockNumber, BlockSignature}; use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce}; use starknet_api::state::StorageKey; diff --git a/crates/papyrus_rpc/src/lib.rs b/crates/papyrus_rpc/src/lib.rs index 70e5abf222..c0308df84c 100644 --- a/crates/papyrus_rpc/src/lib.rs +++ b/crates/papyrus_rpc/src/lib.rs @@ -20,12 +20,12 @@ use std::sync::Arc; use jsonrpsee::core::RpcResult; use jsonrpsee::server::{ServerBuilder, ServerHandle}; +use jsonrpsee::types::ErrorObjectOwned; use jsonrpsee::types::error::ErrorCode::InternalError; use jsonrpsee::types::error::INTERNAL_ERROR_MSG; -use jsonrpsee::types::ErrorObjectOwned; pub use latest::error; use papyrus_common::pending_classes::PendingClasses; -use papyrus_config::dumping::{append_sub_config_name, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name, ser_param}; use papyrus_config::validators::validate_ascii; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use papyrus_execution::ExecutionConfig; @@ -38,9 +38,9 @@ use rpc_metrics::MetricLogger; use serde::{Deserialize, Serialize}; use starknet_api::block::{BlockHashAndNumber, BlockNumber, BlockStatus}; use starknet_api::core::ChainId; +use starknet_client::RetryConfig; use starknet_client::reader::PendingData; use starknet_client::writer::StarknetGatewayClient; -use starknet_client::RetryConfig; use tokio::sync::RwLock; use tracing::{debug, error, info, instrument}; // Aliasing the latest version of the RPC. diff --git a/crates/papyrus_rpc/src/middleware.rs b/crates/papyrus_rpc/src/middleware.rs index 9489fffc56..be8654c16c 100644 --- a/crates/papyrus_rpc/src/middleware.rs +++ b/crates/papyrus_rpc/src/middleware.rs @@ -4,8 +4,8 @@ use regex::Regex; use tower::BoxError; use tracing::{debug, instrument}; -use crate::version_config::{VersionState, VERSION_CONFIG, VERSION_PATTERN}; use crate::SERVER_MAX_BODY_SIZE; +use crate::version_config::{VERSION_CONFIG, VERSION_PATTERN, VersionState}; /// [`Tower`] middleware intended to proxy method requests to the right version of the API. /// The middleware reads the JsonRPC request body and request path diff --git a/crates/papyrus_rpc/src/rpc_metrics/mod.rs b/crates/papyrus_rpc/src/rpc_metrics/mod.rs index a5098f80e9..79dec77b17 100644 --- a/crates/papyrus_rpc/src/rpc_metrics/mod.rs +++ b/crates/papyrus_rpc/src/rpc_metrics/mod.rs @@ -5,9 +5,9 @@ use std::collections::HashSet; use std::net::SocketAddr; use std::time::Instant; +use jsonrpsee::Methods; use jsonrpsee::server::logger::{HttpRequest, Logger, MethodKind, TransportProtocol}; use jsonrpsee::types::Params; -use jsonrpsee::Methods; use metrics::{histogram, increment_counter, register_counter, register_histogram}; // Name of the metrics. diff --git a/crates/papyrus_rpc/src/rpc_metrics/rpc_metrics_test.rs b/crates/papyrus_rpc/src/rpc_metrics/rpc_metrics_test.rs index 378ce49c56..bb2f7e5cfe 100644 --- a/crates/papyrus_rpc/src/rpc_metrics/rpc_metrics_test.rs +++ b/crates/papyrus_rpc/src/rpc_metrics/rpc_metrics_test.rs @@ -1,8 +1,8 @@ use std::sync::Arc; use std::time::Instant; -use jsonrpsee::server::logger::{Logger, TransportProtocol}; use jsonrpsee::Methods; +use jsonrpsee::server::logger::{Logger, TransportProtocol}; use metrics_exporter_prometheus::PrometheusBuilder; use papyrus_storage::body::BodyStorageWriter; use papyrus_storage::class::ClassStorageWriter; @@ -16,8 +16,8 @@ use starknet_api::block::{BlockBody, BlockHeader, BlockNumber}; use starknet_api::state::ThinStateDiff; use crate::rpc_metrics::{ - get_method_and_version, MetricLogger, FAILED_REQUESTS, ILLEGAL_METHOD, INCOMING_REQUEST, - METHOD_LABEL, VERSION_LABEL, + FAILED_REQUESTS, ILLEGAL_METHOD, INCOMING_REQUEST, METHOD_LABEL, MetricLogger, VERSION_LABEL, + get_method_and_version, }; use crate::run_server; use crate::test_utils::{ diff --git a/crates/papyrus_rpc/src/rpc_test.rs b/crates/papyrus_rpc/src/rpc_test.rs index 7259b65a38..955db51830 100644 --- a/crates/papyrus_rpc/src/rpc_test.rs +++ b/crates/papyrus_rpc/src/rpc_test.rs @@ -3,7 +3,7 @@ use std::{panic, vec}; use assert_matches::assert_matches; use futures_util::future::join_all; -use hyper::{header, Body, Request}; +use hyper::{Body, Request, header}; use jsonrpsee::core::client::ClientT; use jsonrpsee::core::http_helpers::read_body; use jsonrpsee::core::{Error, RpcResult}; @@ -25,7 +25,7 @@ use crate::test_utils::{ get_test_highest_block, get_test_pending_classes, get_test_pending_data, get_test_rpc_config, }; use crate::version_config::VERSION_CONFIG; -use crate::{get_block_status, run_server, SERVER_MAX_BODY_SIZE}; +use crate::{SERVER_MAX_BODY_SIZE, get_block_status, run_server}; #[tokio::test] async fn run_server_no_blocks() { diff --git a/crates/papyrus_rpc/src/test_utils.rs b/crates/papyrus_rpc/src/test_utils.rs index 3f7716506f..b8dcfd8d85 100644 --- a/crates/papyrus_rpc/src/test_utils.rs +++ b/crates/papyrus_rpc/src/test_utils.rs @@ -22,9 +22,9 @@ use strum::IntoEnumIterator; use strum_macros::EnumIter; use tokio::sync::RwLock; -use crate::api::JsonRpcServerTrait; -use crate::version_config::{VersionId, VERSION_PATTERN}; use crate::RpcConfig; +use crate::api::JsonRpcServerTrait; +use crate::version_config::{VERSION_PATTERN, VersionId}; pub fn get_test_rpc_config() -> RpcConfig { RpcConfig { @@ -54,8 +54,8 @@ pub(crate) fn get_test_pending_classes() -> Arc> { Arc::new(RwLock::new(PendingClasses::default())) } -pub(crate) fn get_test_rpc_server_and_storage_writer( -) -> (RpcModule, StorageWriter) { +pub(crate) fn get_test_rpc_server_and_storage_writer() +-> (RpcModule, StorageWriter) { get_test_rpc_server_and_storage_writer_from_params(None, None, None, None, None) } diff --git a/crates/papyrus_rpc/src/v0_8/api/api_impl.rs b/crates/papyrus_rpc/src/v0_8/api/api_impl.rs index a2495dbd6a..0eedcc980e 100644 --- a/crates/papyrus_rpc/src/v0_8/api/api_impl.rs +++ b/crates/papyrus_rpc/src/v0_8/api/api_impl.rs @@ -1,25 +1,24 @@ use std::sync::Arc; use async_trait::async_trait; +use jsonrpsee::RpcModule; use jsonrpsee::core::RpcResult; use jsonrpsee::types::ErrorObjectOwned; -use jsonrpsee::RpcModule; use papyrus_common::pending_classes::{PendingClasses, PendingClassesTrait}; use papyrus_execution::objects::{FeeEstimation, PendingData as ExecutionPendingData}; use papyrus_execution::{ - estimate_fee as exec_estimate_fee, execute_call, execution_utils, - simulate_transactions as exec_simulate_transactions, ExecutableTransactionInput, - ExecutionConfig, + ExecutableTransactionInput, ExecutionConfig, estimate_fee as exec_estimate_fee, execute_call, + execution_utils, simulate_transactions as exec_simulate_transactions, }; use papyrus_storage::body::events::{EventIndex, EventsReader}; use papyrus_storage::body::{BodyStorageReader, TransactionIndex}; use papyrus_storage::compiled_class::CasmStorageReader; -use papyrus_storage::db::{TransactionKind, RO}; +use papyrus_storage::db::{RO, TransactionKind}; use papyrus_storage::state::StateStorageReader; use papyrus_storage::{StorageError, StorageReader, StorageTxn}; use starknet_api::block::{BlockHash, BlockHeaderWithoutHash, BlockNumber, BlockStatus}; use starknet_api::core::{ - ChainId, ClassHash, ContractAddress, GlobalRoot, Nonce, BLOCK_HASH_TABLE_ADDRESS, + BLOCK_HASH_TABLE_ADDRESS, ChainId, ClassHash, ContractAddress, GlobalRoot, Nonce, }; use starknet_api::execution_utils::format_panic_data; use starknet_api::hash::StarkHash; @@ -29,6 +28,8 @@ use starknet_api::transaction::{ EventContent, EventIndexInTransactionOutput, Transaction as StarknetApiTransaction, TransactionHash, TransactionOffsetInBlock, TransactionVersion, }; +use starknet_client::ClientError; +use starknet_client::reader::PendingData; use starknet_client::reader::objects::pending_data::{ DeprecatedPendingBlock, PendingBlockOrDeprecated, PendingStateUpdate as ClientPendingStateUpdate, @@ -36,33 +37,32 @@ use starknet_client::reader::objects::pending_data::{ use starknet_client::reader::objects::transaction::{ Transaction as ClientTransaction, TransactionReceipt as ClientTransactionReceipt, }; -use starknet_client::reader::PendingData; use starknet_client::writer::{StarknetWriter, WriterClientError}; -use starknet_client::ClientError; use starknet_types_core::felt::Felt; use tokio::sync::RwLock; use tracing::{instrument, trace, warn}; use super::super::block::{ - get_accepted_block_number, get_block_header_by_number, Block, BlockHeader, - BlockNotRevertedValidator, GeneralBlockHeader, PendingBlockHeader, ResourcePrice, + Block, BlockHeader, BlockNotRevertedValidator, GeneralBlockHeader, PendingBlockHeader, + ResourcePrice, get_accepted_block_number, get_block_header_by_number, }; use super::super::broadcasted_transaction::{ BroadcastedDeclareTransaction, BroadcastedTransaction, }; use super::super::error::{ - ContractError, JsonRpcError, TransactionExecutionError, BLOCK_NOT_FOUND, CLASS_HASH_NOT_FOUND, - CONTRACT_NOT_FOUND, INVALID_TRANSACTION_HASH, INVALID_TRANSACTION_INDEX, NO_BLOCKS, + BLOCK_NOT_FOUND, CLASS_HASH_NOT_FOUND, CONTRACT_NOT_FOUND, ContractError, + INVALID_TRANSACTION_HASH, INVALID_TRANSACTION_INDEX, JsonRpcError, NO_BLOCKS, PAGE_SIZE_TOO_BIG, TOO_MANY_KEYS_IN_FILTER, TRANSACTION_HASH_NOT_FOUND, + TransactionExecutionError, }; use super::super::execution::TransactionTrace; use super::super::state::{AcceptedStateUpdate, PendingStateUpdate, StateUpdate}; use super::super::transaction::{ - get_block_tx_hashes_by_number, get_block_txs_by_number, Event, GeneralTransactionReceipt, - L1HandlerMsgHash, L1L2MsgHash, MessageFromL1, PendingTransactionFinalityStatus, - PendingTransactionOutput, PendingTransactionReceipt, Transaction, TransactionOutput, - TransactionReceipt, TransactionStatus, TransactionWithHash, TransactionWithReceipt, - Transactions, TypedDeployAccountTransaction, TypedInvokeTransaction, + Event, GeneralTransactionReceipt, L1HandlerMsgHash, L1L2MsgHash, MessageFromL1, + PendingTransactionFinalityStatus, PendingTransactionOutput, PendingTransactionReceipt, + Transaction, TransactionOutput, TransactionReceipt, TransactionStatus, TransactionWithHash, + TransactionWithReceipt, Transactions, TypedDeployAccountTransaction, TypedInvokeTransaction, + get_block_tx_hashes_by_number, get_block_txs_by_number, }; use super::super::write_api_error::{ starknet_error_to_declare_error, starknet_error_to_deploy_account_error, @@ -72,18 +72,18 @@ use super::super::write_api_result::{ AddDeclareOkResult, AddDeployAccountOkResult, AddInvokeOkResult, }; use super::{ - execution_error_to_error_object_owned, stored_txn_to_executable_txn, BlockHashAndNumber, - BlockId, CallRequest, CompiledContractClass, ContinuationToken, EventFilter, EventsChunk, - GatewayContractClass, JsonRpcV0_8Server as JsonRpcServer, SimulatedTransaction, SimulationFlag, - TransactionTraceWithHash, + BlockHashAndNumber, BlockId, CallRequest, CompiledContractClass, ContinuationToken, + EventFilter, EventsChunk, GatewayContractClass, JsonRpcV0_8Server as JsonRpcServer, + SimulatedTransaction, SimulationFlag, TransactionTraceWithHash, + execution_error_to_error_object_owned, stored_txn_to_executable_txn, }; use crate::api::{BlockHashOrNumber, JsonRpcServerTrait, Tag}; use crate::pending::client_pending_data_to_execution_pending_data; -use crate::syncing_state::{get_last_synced_block, SyncStatus, SyncingState}; +use crate::syncing_state::{SyncStatus, SyncingState, get_last_synced_block}; use crate::version_config::VERSION_0_8 as VERSION; use crate::{ - get_block_status, get_latest_block_number, internal_server_error, verify_storage_scope, - ContinuationTokenAsStruct, GENESIS_HASH, + ContinuationTokenAsStruct, GENESIS_HASH, get_block_status, get_latest_block_number, + internal_server_error, verify_storage_scope, }; const DONT_IGNORE_L1_DA_MODE: bool = false; @@ -685,7 +685,7 @@ impl JsonRpcServer for JsonRpcServerImpl { // corresponding to the requested filter. If there are, we return a continuation token // pointing to the next relevant event. Otherwise, we return a continuation token None. let mut filtered_events = vec![]; - if start_event_index.0 .0 <= latest_block_number { + if start_event_index.0.0 <= latest_block_number { for ((from_address, event_index), content) in txn .iter_events(filter.address, start_event_index, to_block_number) .map_err(internal_server_error)? @@ -734,8 +734,8 @@ impl JsonRpcServer for JsonRpcServerImpl { let pending_block = read_pending_data(&self.pending_data, &txn).await?.block; let pending_transaction_receipts = pending_block.transaction_receipts(); // Extract the first transaction offset and event offset from the starting EventIndex. - let (transaction_start, event_start) = if start_event_index.0 .0 > latest_block_number { - (start_event_index.0 .1 .0, start_event_index.1 .0) + let (transaction_start, event_start) = if start_event_index.0.0 > latest_block_number { + (start_event_index.0.1.0, start_event_index.1.0) } else { (0, 0) }; diff --git a/crates/papyrus_rpc/src/v0_8/api/mod.rs b/crates/papyrus_rpc/src/v0_8/api/mod.rs index 2ea7103113..1a89514fd8 100644 --- a/crates/papyrus_rpc/src/v0_8/api/mod.rs +++ b/crates/papyrus_rpc/src/v0_8/api/mod.rs @@ -11,11 +11,11 @@ use papyrus_common::pending_classes::ApiContractClass; use papyrus_execution::objects::FeeEstimation; use papyrus_execution::{AbiSize, ExecutableTransactionInput, ExecutionError, SierraSize}; use papyrus_proc_macros::versioned_rpc; +use papyrus_storage::StorageTxn; use papyrus_storage::compiled_class::CasmStorageReader; -use papyrus_storage::db::serialization::StorageSerdeError; use papyrus_storage::db::RO; +use papyrus_storage::db::serialization::StorageSerdeError; use papyrus_storage::state::StateStorageReader; -use papyrus_storage::StorageTxn; use serde::{Deserialize, Serialize}; use starknet_api::block::{BlockHashAndNumber, BlockNumber}; use starknet_api::contract_class::SierraVersion; @@ -35,7 +35,7 @@ use super::broadcasted_transaction::{ }; use super::deprecated_contract_class::ContractClass as DeprecatedContractClass; use super::error::{ - ContractError, JsonRpcError, BLOCK_NOT_FOUND, CONTRACT_NOT_FOUND, INVALID_CONTINUATION_TOKEN, + BLOCK_NOT_FOUND, CONTRACT_NOT_FOUND, ContractError, INVALID_CONTINUATION_TOKEN, JsonRpcError, }; use super::execution::TransactionTrace; use super::state::{ContractClass, StateUpdate}; @@ -48,7 +48,7 @@ use super::transaction::{ use super::write_api_result::{AddDeclareOkResult, AddDeployAccountOkResult, AddInvokeOkResult}; use crate::api::{BlockId, CallRequest}; use crate::syncing_state::SyncingState; -use crate::{internal_server_error, ContinuationTokenAsStruct}; +use crate::{ContinuationTokenAsStruct, internal_server_error}; pub mod api_impl; #[cfg(test)] diff --git a/crates/papyrus_rpc/src/v0_8/api/test.rs b/crates/papyrus_rpc/src/v0_8/api/test.rs index 439f7166dc..f2748b2341 100644 --- a/crates/papyrus_rpc/src/v0_8/api/test.rs +++ b/crates/papyrus_rpc/src/v0_8/api/test.rs @@ -7,14 +7,15 @@ use std::ops::Index; use assert_matches::assert_matches; use async_trait::async_trait; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; -use indexmap::{indexmap, IndexMap}; +use indexmap::{IndexMap, indexmap}; use itertools::Itertools; -use jsonrpsee::core::Error; use jsonrpsee::Methods; +use jsonrpsee::core::Error; use jsonschema::JSONSchema; use lazy_static::lazy_static; use mockall::predicate::eq; use papyrus_common::pending_classes::{ApiContractClass, PendingClassesTrait}; +use papyrus_storage::StorageScope; use papyrus_storage::base_layer::BaseLayerStorageWriter; use papyrus_storage::body::events::EventIndex; use papyrus_storage::body::{BodyStorageWriter, TransactionIndex}; @@ -23,13 +24,12 @@ use papyrus_storage::compiled_class::CasmStorageWriter; use papyrus_storage::header::HeaderStorageWriter; use papyrus_storage::state::StateStorageWriter; use papyrus_storage::test_utils::get_test_storage; -use papyrus_storage::StorageScope; use papyrus_test_utils::{ - auto_impl_get_test_instance, get_number_of_variants, get_rng, get_test_block, get_test_body, - get_test_state_diff, send_request, GetTestInstance, + GetTestInstance, auto_impl_get_test_instance, get_number_of_variants, get_rng, get_test_block, + get_test_body, get_test_state_diff, send_request, }; use pretty_assertions::assert_eq; -use rand::{random, RngCore}; +use rand::{RngCore, random}; use rand_chacha::ChaCha8Rng; use reqwest::StatusCode; use serde::{Deserialize, Serialize}; @@ -38,8 +38,8 @@ use starknet_api::block::{ BlockNumber, BlockStatus, BlockTimestamp, GasPrice, GasPricePerToken, StarknetVersion, }; use starknet_api::core::{ - ClassHash, CompiledClassHash, ContractAddress, GlobalRoot, Nonce, SequencerContractAddress, - BLOCK_HASH_TABLE_ADDRESS, + BLOCK_HASH_TABLE_ADDRESS, ClassHash, CompiledClassHash, ContractAddress, GlobalRoot, Nonce, + SequencerContractAddress, }; use starknet_api::data_availability::L1DataAvailabilityMode; use starknet_api::deprecated_contract_class::{ @@ -53,6 +53,7 @@ use starknet_api::transaction::{ TransactionOutput as StarknetApiTransactionOutput, }; use starknet_api::{class_hash, contract_address, felt, storage_key, tx_hash}; +use starknet_client::ClientError; use starknet_client::reader::objects::pending_data::{ DeprecatedPendingBlock, PendingBlockOrDeprecated, PendingStateUpdate as ClientPendingStateUpdate, @@ -75,7 +76,6 @@ use starknet_client::writer::objects::transaction::{ InvokeTransaction as ClientInvokeTransaction, }; use starknet_client::writer::{MockStarknetWriter, WriterClientError, WriterClientResult}; -use starknet_client::ClientError; use starknet_types_core::felt::Felt; use super::super::api::EventsChunk; @@ -83,9 +83,9 @@ use super::super::block::{Block, GeneralBlockHeader, PendingBlockHeader, Resourc use super::super::broadcasted_transaction::BroadcastedDeclareTransaction; use super::super::deprecated_contract_class::ContractClass as DeprecatedContractClass; use super::super::error::{ - unexpected_error, JsonRpcError, BLOCK_NOT_FOUND, CLASS_HASH_NOT_FOUND, COMPILATION_FAILED, - CONTRACT_NOT_FOUND, DUPLICATE_TX, INVALID_CONTINUATION_TOKEN, INVALID_TRANSACTION_INDEX, - NO_BLOCKS, PAGE_SIZE_TOO_BIG, TOO_MANY_KEYS_IN_FILTER, TRANSACTION_HASH_NOT_FOUND, + BLOCK_NOT_FOUND, CLASS_HASH_NOT_FOUND, COMPILATION_FAILED, CONTRACT_NOT_FOUND, DUPLICATE_TX, + INVALID_CONTINUATION_TOKEN, INVALID_TRANSACTION_INDEX, JsonRpcError, NO_BLOCKS, + PAGE_SIZE_TOO_BIG, TOO_MANY_KEYS_IN_FILTER, TRANSACTION_HASH_NOT_FOUND, unexpected_error, }; use super::super::state::{ AcceptedStateUpdate, ClassHashes, ContractClass, ContractNonce, DeployedContract, @@ -106,18 +106,19 @@ use super::{ContinuationToken, EventFilter, GatewayContractClass}; use crate::api::{BlockHashOrNumber, BlockId, Tag}; use crate::syncing_state::SyncStatus; use crate::test_utils::{ - call_and_validate_schema_for_result, call_api_then_assert_and_validate_schema_for_err, + SpecFile, call_and_validate_schema_for_result, + call_api_then_assert_and_validate_schema_for_err, call_api_then_assert_and_validate_schema_for_result, get_method_names_from_spec, get_starknet_spec_api_schema_for_components, get_starknet_spec_api_schema_for_method_results, get_test_highest_block, get_test_pending_classes, get_test_pending_data, get_test_rpc_config, get_test_rpc_server_and_storage_writer, get_test_rpc_server_and_storage_writer_from_params, - method_name_to_spec_method_name, raw_call, validate_schema, SpecFile, + method_name_to_spec_method_name, raw_call, validate_schema, }; use crate::v0_8::api::CompiledContractClass; use crate::version_config::VERSION_0_8 as VERSION; use crate::{ - internal_server_error, internal_server_error_with_msg, run_server, ContinuationTokenAsStruct, - GENESIS_HASH, + ContinuationTokenAsStruct, GENESIS_HASH, internal_server_error, internal_server_error_with_msg, + run_server, }; const NODE_VERSION: &str = "NODE VERSION"; @@ -345,12 +346,9 @@ async fn get_block_transaction_count() { // Get block by number. let res = module - .call::<_, usize>( - method_name, - [BlockId::HashOrNumber(BlockHashOrNumber::Number( - block.header.block_header_without_hash.block_number, - ))], - ) + .call::<_, usize>(method_name, [BlockId::HashOrNumber(BlockHashOrNumber::Number( + block.header.block_header_without_hash.block_number, + ))]) .await .unwrap(); assert_eq!(res, transaction_count); @@ -390,10 +388,9 @@ async fn get_block_transaction_count() { // Ask for an invalid block number. let err = module - .call::<_, usize>( - method_name, - [BlockId::HashOrNumber(BlockHashOrNumber::Number(BlockNumber(1)))], - ) + .call::<_, usize>(method_name, [BlockId::HashOrNumber(BlockHashOrNumber::Number( + BlockNumber(1), + ))]) .await .unwrap_err(); assert_matches!(err, Error::Call(err) if err == BLOCK_NOT_FOUND.into()); @@ -460,10 +457,9 @@ async fn get_block_w_full_transactions() { // Get block by number. let block = module - .call::<_, Block>( - method_name, - [BlockId::HashOrNumber(BlockHashOrNumber::Number(expected_block_header.block_number))], - ) + .call::<_, Block>(method_name, [BlockId::HashOrNumber(BlockHashOrNumber::Number( + expected_block_header.block_number, + ))]) .await .unwrap(); assert_eq!(block, expected_block); @@ -481,32 +477,27 @@ async fn get_block_w_full_transactions() { .commit() .unwrap(); let block = module - .call::<_, Block>( - method_name, - [BlockId::HashOrNumber(BlockHashOrNumber::Hash(expected_block_header.block_hash))], - ) + .call::<_, Block>(method_name, [BlockId::HashOrNumber(BlockHashOrNumber::Hash( + expected_block_header.block_hash, + ))]) .await .unwrap(); assert_eq!(block.status, Some(BlockStatus::AcceptedOnL1)); // Ask for an invalid block hash. let err = module - .call::<_, Block>( - method_name, - [BlockId::HashOrNumber(BlockHashOrNumber::Hash(BlockHash(felt!( - "0x642b629ad8ce233b55798c83bb629a59bf0a0092f67da28d6d66776680d5484" - ))))], - ) + .call::<_, Block>(method_name, [BlockId::HashOrNumber(BlockHashOrNumber::Hash(BlockHash( + felt!("0x642b629ad8ce233b55798c83bb629a59bf0a0092f67da28d6d66776680d5484"), + )))]) .await .unwrap_err(); assert_matches!(err, Error::Call(err) if err == BLOCK_NOT_FOUND.into()); // Ask for an invalid block number. let err = module - .call::<_, Block>( - method_name, - [BlockId::HashOrNumber(BlockHashOrNumber::Number(BlockNumber(1)))], - ) + .call::<_, Block>(method_name, [BlockId::HashOrNumber(BlockHashOrNumber::Number( + BlockNumber(1), + ))]) .await .unwrap_err(); assert_matches!(err, Error::Call(err) if err == BLOCK_NOT_FOUND.into()); @@ -648,10 +639,9 @@ async fn get_block_w_full_transactions_and_receipts() { // Get block by number. let block = module - .call::<_, Block>( - method_name, - [BlockId::HashOrNumber(BlockHashOrNumber::Number(block_number))], - ) + .call::<_, Block>(method_name, [BlockId::HashOrNumber(BlockHashOrNumber::Number( + block_number, + ))]) .await .unwrap(); assert_eq!(block.header, expected_block_header); @@ -676,22 +666,18 @@ async fn get_block_w_full_transactions_and_receipts() { // Ask for an invalid block hash. let err = module - .call::<_, Block>( - method_name, - [BlockId::HashOrNumber(BlockHashOrNumber::Hash(BlockHash(felt!( - "0x642b629ad8ce233b55798c83bb629a59bf0a0092f67da28d6d66776680d5484" - ))))], - ) + .call::<_, Block>(method_name, [BlockId::HashOrNumber(BlockHashOrNumber::Hash(BlockHash( + felt!("0x642b629ad8ce233b55798c83bb629a59bf0a0092f67da28d6d66776680d5484"), + )))]) .await .unwrap_err(); assert_matches!(err, Error::Call(err) if err == BLOCK_NOT_FOUND.into()); // Ask for an invalid block number. let err = module - .call::<_, Block>( - method_name, - [BlockId::HashOrNumber(BlockHashOrNumber::Number(BlockNumber(1)))], - ) + .call::<_, Block>(method_name, [BlockId::HashOrNumber(BlockHashOrNumber::Number( + BlockNumber(1), + ))]) .await .unwrap_err(); assert_matches!(err, Error::Call(err) if err == BLOCK_NOT_FOUND.into()); @@ -843,10 +829,9 @@ async fn get_block_w_transaction_hashes() { // Get block by number. let block = module - .call::<_, Block>( - method_name, - [BlockId::HashOrNumber(BlockHashOrNumber::Number(expected_block_header.block_number))], - ) + .call::<_, Block>(method_name, [BlockId::HashOrNumber(BlockHashOrNumber::Number( + expected_block_header.block_number, + ))]) .await .unwrap(); assert_eq!(block, expected_block); @@ -864,10 +849,9 @@ async fn get_block_w_transaction_hashes() { .commit() .unwrap(); let block = module - .call::<_, Block>( - method_name, - [BlockId::HashOrNumber(BlockHashOrNumber::Hash(expected_block_header.block_hash))], - ) + .call::<_, Block>(method_name, [BlockId::HashOrNumber(BlockHashOrNumber::Hash( + expected_block_header.block_hash, + ))]) .await .unwrap(); assert_eq!(block.status, Some(BlockStatus::AcceptedOnL1)); @@ -887,10 +871,9 @@ async fn get_block_w_transaction_hashes() { // Ask for an invalid block number. let err = module - .call::<_, Block>( - method_name, - [BlockId::HashOrNumber(BlockHashOrNumber::Number(BlockNumber(1)))], - ) + .call::<_, Block>(method_name, [BlockId::HashOrNumber(BlockHashOrNumber::Number( + BlockNumber(1), + ))]) .await .unwrap_err(); assert_matches!(err, Error::Call(err) if err == BLOCK_NOT_FOUND.into()); @@ -1197,10 +1180,9 @@ async fn get_transaction_status() { assert_eq!(res.unwrap(), expected_status); assert!(validate_schema( &get_starknet_spec_api_schema_for_method_results( - &[( - SpecFile::StarknetApiOpenrpc, - &[method_name_to_spec_method_name(method_name).as_str()] - )], + &[(SpecFile::StarknetApiOpenrpc, &[ + method_name_to_spec_method_name(method_name).as_str() + ])], &VERSION, ), &json_response["result"], @@ -1233,20 +1215,17 @@ async fn get_transaction_status() { pending_block.transactions_mutable().push(client_transaction.clone()); pending_block.transaction_receipts_mutable().push(client_transaction_receipt.clone()); } - let (json_response, result) = raw_call::<_, _, TransactionStatus>( - &module, - method_name, - &[client_transaction_receipt.transaction_hash], - ) + let (json_response, result) = raw_call::<_, _, TransactionStatus>(&module, method_name, &[ + client_transaction_receipt.transaction_hash, + ]) .await; assert_eq!(result.unwrap(), expected_status); // Validating schema again since pending has a different schema assert!(validate_schema( &get_starknet_spec_api_schema_for_method_results( - &[( - SpecFile::StarknetApiOpenrpc, - &[method_name_to_spec_method_name(method_name).as_str()] - )], + &[(SpecFile::StarknetApiOpenrpc, &[ + method_name_to_spec_method_name(method_name).as_str() + ])], &VERSION, ), &json_response["result"], @@ -1255,11 +1234,9 @@ async fn get_transaction_status() { // Ask for transaction status when the pending block is not up to date. *pending_data.write().await.block.parent_block_hash_mutable() = BlockHash(random::().into()); - let (_, res) = raw_call::<_, _, TransactionStatus>( - &module, - method_name, - &[client_transaction_receipt.transaction_hash], - ) + let (_, res) = raw_call::<_, _, TransactionStatus>(&module, method_name, &[ + client_transaction_receipt.transaction_hash, + ]) .await; assert_eq!(res.unwrap_err(), TRANSACTION_HASH_NOT_FOUND.into()); @@ -1353,12 +1330,11 @@ async fn get_transaction_receipt() { } let expected_result = GeneralTransactionReceipt::PendingTransactionReceipt(expected_receipt); - let (json_response, result) = raw_call::<_, _, PendingTransactionReceipt>( - &module, - method_name, - &[client_transaction_receipt.transaction_hash], - ) - .await; + let (json_response, result) = + raw_call::<_, _, PendingTransactionReceipt>(&module, method_name, &[ + client_transaction_receipt.transaction_hash, + ]) + .await; // See above for explanation why we compare the json strings. assert_eq!( serde_json::to_value(result.unwrap()).unwrap(), @@ -1367,10 +1343,9 @@ async fn get_transaction_receipt() { // Validating schema again since pending has a different schema assert!(validate_schema( &get_starknet_spec_api_schema_for_method_results( - &[( - SpecFile::StarknetApiOpenrpc, - &[method_name_to_spec_method_name(method_name).as_str()] - )], + &[(SpecFile::StarknetApiOpenrpc, &[ + method_name_to_spec_method_name(method_name).as_str() + ])], &VERSION, ), &json_response["result"], @@ -1379,11 +1354,9 @@ async fn get_transaction_receipt() { // Ask for transaction receipt when the pending block is not up to date. *pending_data.write().await.block.parent_block_hash_mutable() = BlockHash(random::().into()); - let (_, res) = raw_call::<_, _, TransactionReceipt>( - &module, - method_name, - &[client_transaction_receipt.transaction_hash], - ) + let (_, res) = raw_call::<_, _, TransactionReceipt>(&module, method_name, &[ + client_transaction_receipt.transaction_hash, + ]) .await; assert_eq!(res.unwrap_err(), TRANSACTION_HASH_NOT_FOUND.into()); @@ -2151,16 +2124,11 @@ fn generate_client_transaction_client_receipt_rpc_transaction_and_rpc_receipt( }; // rpc_transaction contains no hash so no need to change it. *client_transaction.transaction_hash_mut() = pending_transaction_hash; - ( - client_transaction, - client_transaction_receipt, - rpc_transaction, - PendingTransactionReceipt { - finality_status: PendingTransactionFinalityStatus::AcceptedOnL2, - transaction_hash: pending_transaction_hash, - output, - }, - ) + (client_transaction, client_transaction_receipt, rpc_transaction, PendingTransactionReceipt { + finality_status: PendingTransactionFinalityStatus::AcceptedOnL2, + transaction_hash: pending_transaction_hash, + output, + }) } fn generate_client_transaction_and_rpc_transaction( @@ -2179,10 +2147,10 @@ fn generate_client_transaction_and_rpc_transaction( continue; }; let transaction_hash = client_transaction.transaction_hash(); - break ( - client_transaction, - TransactionWithHash { transaction: rpc_transaction, transaction_hash }, - ); + break (client_transaction, TransactionWithHash { + transaction: rpc_transaction, + transaction_hash, + }); } } @@ -2470,12 +2438,9 @@ async fn get_state_update() { // Get state update by block number. let res = module - .call::<_, StateUpdate>( - method_name, - [BlockId::HashOrNumber(BlockHashOrNumber::Number( - header.block_header_without_hash.block_number, - ))], - ) + .call::<_, StateUpdate>(method_name, [BlockId::HashOrNumber(BlockHashOrNumber::Number( + header.block_header_without_hash.block_number, + ))]) .await .unwrap(); assert_eq!(res, expected_update); @@ -2566,10 +2531,9 @@ async fn get_state_update() { // Ask for an invalid block number. let err = module - .call::<_, StateUpdate>( - method_name, - [BlockId::HashOrNumber(BlockHashOrNumber::Number(BlockNumber(2)))], - ) + .call::<_, StateUpdate>(method_name, [BlockId::HashOrNumber(BlockHashOrNumber::Number( + BlockNumber(2), + ))]) .await .unwrap_err(); assert_matches!(err, Error::Call(err) if err == BLOCK_NOT_FOUND.into()); @@ -3400,19 +3364,16 @@ async fn serialize_returns_valid_json() { .unwrap(); let schema = get_starknet_spec_api_schema_for_components( - &[( - SpecFile::StarknetApiOpenrpc, - &[ - "BLOCK_WITH_TXS", - "BLOCK_WITH_TX_HASHES", - "STATE_UPDATE", - "CONTRACT_CLASS", - "DEPRECATED_CONTRACT_CLASS", - "TXN", - "TXN_RECEIPT", - "EVENTS_CHUNK", - ], - )], + &[(SpecFile::StarknetApiOpenrpc, &[ + "BLOCK_WITH_TXS", + "BLOCK_WITH_TX_HASHES", + "STATE_UPDATE", + "CONTRACT_CLASS", + "DEPRECATED_CONTRACT_CLASS", + "TXN", + "TXN_RECEIPT", + "EVENTS_CHUNK", + ])], &VERSION, ); validate_state(&state_diff, server_address, &schema).await; @@ -3557,14 +3518,10 @@ async fn get_deprecated_class_state_mutability() { .unwrap() .append_state_diff(header.block_header_without_hash.block_number, state_diff) .unwrap() - .append_classes( - header.block_header_without_hash.block_number, - &[], - &[ - (class_hash!("0x0"), &class_without_state_mutability), - (class_hash!("0x1"), &class_with_state_mutability), - ], - ) + .append_classes(header.block_header_without_hash.block_number, &[], &[ + (class_hash!("0x0"), &class_without_state_mutability), + (class_hash!("0x1"), &class_with_state_mutability), + ]) .unwrap() .commit() .unwrap(); diff --git a/crates/papyrus_rpc/src/v0_8/block.rs b/crates/papyrus_rpc/src/v0_8/block.rs index 7aab0728c0..2659535a3b 100644 --- a/crates/papyrus_rpc/src/v0_8/block.rs +++ b/crates/papyrus_rpc/src/v0_8/block.rs @@ -173,10 +173,6 @@ impl BlockNotRevertedValidator { .map_err(internal_server_error)? .ok_or(error.clone())? .block_hash; - if new_block_hash == self.old_block_hash { - Ok(()) - } else { - Err(error) - } + if new_block_hash == self.old_block_hash { Ok(()) } else { Err(error) } } } diff --git a/crates/papyrus_rpc/src/v0_8/broadcasted_transaction.rs b/crates/papyrus_rpc/src/v0_8/broadcasted_transaction.rs index 3fdf490a5d..89f4472ab1 100644 --- a/crates/papyrus_rpc/src/v0_8/broadcasted_transaction.rs +++ b/crates/papyrus_rpc/src/v0_8/broadcasted_transaction.rs @@ -15,10 +15,10 @@ use papyrus_storage::db::serialization::StorageSerdeError; use serde::{Deserialize, Serialize}; use starknet_api::core::{CompiledClassHash, ContractAddress, Nonce}; use starknet_api::data_availability::DataAvailabilityMode; +use starknet_api::transaction::TransactionVersion; use starknet_api::transaction::fields::{ AccountDeploymentData, Fee, PaymasterData, Tip, TransactionSignature, }; -use starknet_api::transaction::TransactionVersion; use starknet_client::writer::objects::transaction as client_transaction; use starknet_client::writer::objects::transaction::DeprecatedContractClass; diff --git a/crates/papyrus_rpc/src/v0_8/broadcasted_transaction_test.rs b/crates/papyrus_rpc/src/v0_8/broadcasted_transaction_test.rs index 394ceda496..6b8aab4d3d 100644 --- a/crates/papyrus_rpc/src/v0_8/broadcasted_transaction_test.rs +++ b/crates/papyrus_rpc/src/v0_8/broadcasted_transaction_test.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use jsonschema::JSONSchema; use lazy_static::lazy_static; use papyrus_test_utils::{ - auto_impl_get_test_instance, get_number_of_variants, get_rng, GetTestInstance, + GetTestInstance, auto_impl_get_test_instance, get_number_of_variants, get_rng, }; use starknet_api::contract_class::EntryPointType; use starknet_api::core::{CompiledClassHash, ContractAddress, Nonce}; @@ -25,7 +25,7 @@ use super::{ BroadcastedDeclareV2Transaction, BroadcastedDeclareV3Transaction, DeclareType, ResourceBoundsMapping, }; -use crate::test_utils::{get_starknet_spec_api_schema_for_components, SpecFile}; +use crate::test_utils::{SpecFile, get_starknet_spec_api_schema_for_components}; use crate::version_config::VERSION_0_8 as Version; fn validate_tx_fits_rpc(tx: BroadcastedDeclareTransaction) { @@ -125,18 +125,15 @@ fn declare_v1_fits_rpc() { contract_class: DeprecatedContractClass { abi, entry_points_by_type: HashMap::from([ - ( - EntryPointType::Constructor, - vec![DeprecatedEntryPoint::get_test_instance(&mut rng)], - ), - ( - EntryPointType::External, - vec![DeprecatedEntryPoint::get_test_instance(&mut rng)], - ), - ( - EntryPointType::L1Handler, - vec![DeprecatedEntryPoint::get_test_instance(&mut rng)], - ), + (EntryPointType::Constructor, vec![DeprecatedEntryPoint::get_test_instance( + &mut rng, + )]), + (EntryPointType::External, vec![DeprecatedEntryPoint::get_test_instance( + &mut rng, + )]), + (EntryPointType::L1Handler, vec![DeprecatedEntryPoint::get_test_instance( + &mut rng, + )]), ]), ..GetTestInstance::get_test_instance(&mut rng) }, diff --git a/crates/papyrus_rpc/src/v0_8/execution_test.rs b/crates/papyrus_rpc/src/v0_8/execution_test.rs index e059359466..196669bb18 100644 --- a/crates/papyrus_rpc/src/v0_8/execution_test.rs +++ b/crates/papyrus_rpc/src/v0_8/execution_test.rs @@ -4,29 +4,29 @@ use std::sync::Arc; use assert_matches::assert_matches; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; use indexmap::indexmap; -use jsonrpsee::core::Error; use jsonrpsee::RpcModule; +use jsonrpsee::core::Error; use lazy_static::lazy_static; use papyrus_common::pending_classes::{ApiContractClass, PendingClasses, PendingClassesTrait}; use papyrus_common::state::{ DeclaredClassHashEntry, DeployedContract as CommonDeployedContract, StorageEntry as CommonStorageEntry, }; +use papyrus_execution::ExecutableTransactionInput; use papyrus_execution::execution_utils::selector_from_name; use papyrus_execution::objects::{ CallType, FeeEstimation, FunctionCall, OrderedEvent, OrderedL2ToL1Message, PriceUnit, Retdata, RevertReason, }; use papyrus_execution::testing_instances::get_storage_var_address; -use papyrus_execution::ExecutableTransactionInput; +use papyrus_storage::StorageWriter; use papyrus_storage::body::BodyStorageWriter; use papyrus_storage::class::ClassStorageWriter; use papyrus_storage::compiled_class::CasmStorageWriter; use papyrus_storage::header::HeaderStorageWriter; use papyrus_storage::state::StateStorageWriter; -use papyrus_storage::StorageWriter; use papyrus_test_utils::{ - auto_impl_get_test_instance, get_number_of_variants, get_rng, GetTestInstance, + GetTestInstance, auto_impl_get_test_instance, get_number_of_variants, get_rng, }; use pretty_assertions::assert_eq; use starknet_api::block::{ @@ -48,6 +48,7 @@ use starknet_api::transaction::{ L1HandlerTransaction, TransactionHash, TransactionOffsetInBlock, TransactionVersion, }; use starknet_api::{calldata, class_hash, contract_address, felt, nonce, tx_hash}; +use starknet_client::reader::PendingData; use starknet_client::reader::objects::pending_data::{ PendingBlock, PendingBlockOrDeprecated, PendingStateUpdate, }; @@ -56,18 +57,17 @@ use starknet_client::reader::objects::transaction::{ IntermediateInvokeTransaction as ClientInvokeTransaction, Transaction as ClientTransaction, TransactionReceipt as ClientTransactionReceipt, }; -use starknet_client::reader::PendingData; use starknet_types_core::felt::Felt; use tokio::sync::RwLock; use super::api::api_impl::JsonRpcServerImpl; use super::api::{ - decompress_program, SimulatedTransaction, SimulationFlag, TransactionTraceWithHash, + SimulatedTransaction, SimulationFlag, TransactionTraceWithHash, decompress_program, }; use super::broadcasted_transaction::{ BroadcastedDeclareTransaction, BroadcastedDeclareV1Transaction, BroadcastedTransaction, }; -use super::error::{TransactionExecutionError, BLOCK_NOT_FOUND, CONTRACT_NOT_FOUND}; +use super::error::{BLOCK_NOT_FOUND, CONTRACT_NOT_FOUND, TransactionExecutionError}; use super::execution::{ DeclareTransactionTrace, DeployAccountTransactionTrace, FunctionInvocation, FunctionInvocationResult, InvokeTransactionTrace, L1HandlerTransactionTrace, TransactionTrace, @@ -82,11 +82,12 @@ use super::transaction::{ }; use crate::api::{BlockHashOrNumber, BlockId, CallRequest, Tag}; use crate::test_utils::{ - call_and_validate_schema_for_result, call_api_then_assert_and_validate_schema_for_result, + SpecFile, call_and_validate_schema_for_result, + call_api_then_assert_and_validate_schema_for_result, get_starknet_spec_api_schema_for_components, get_starknet_spec_api_schema_for_method_results, get_test_pending_classes, get_test_pending_data, get_test_rpc_config, get_test_rpc_server_and_storage_writer, get_test_rpc_server_and_storage_writer_from_params, - validate_schema, SpecFile, + validate_schema, }; use crate::version_config::VERSION_0_8 as VERSION; @@ -745,44 +746,35 @@ async fn trace_block_transactions_regular_and_pending() { writer .begin_rw_txn() .unwrap() - .append_header( - BlockNumber(3), - &BlockHeader { - block_hash: BlockHash(felt!("0x3")), - block_header_without_hash: BlockHeaderWithoutHash { - l1_gas_price: *GAS_PRICE, - sequencer: *SEQUENCER_ADDRESS, - timestamp: *BLOCK_TIMESTAMP, - parent_hash: BlockHash(felt!("0x2")), - ..Default::default() - }, + .append_header(BlockNumber(3), &BlockHeader { + block_hash: BlockHash(felt!("0x3")), + block_header_without_hash: BlockHeaderWithoutHash { + l1_gas_price: *GAS_PRICE, + sequencer: *SEQUENCER_ADDRESS, + timestamp: *BLOCK_TIMESTAMP, + parent_hash: BlockHash(felt!("0x2")), ..Default::default() }, - ) + ..Default::default() + }) .unwrap() - .append_body( - BlockNumber(3), - BlockBody { - transactions: vec![tx1, tx2], - transaction_outputs: vec![ - starknet_api::transaction::TransactionOutput::Invoke( - starknet_api::transaction::InvokeTransactionOutput::default(), - ), - starknet_api::transaction::TransactionOutput::Invoke( - starknet_api::transaction::InvokeTransactionOutput::default(), - ), - ], - transaction_hashes: vec![tx_hash1, tx_hash2], - }, - ) + .append_body(BlockNumber(3), BlockBody { + transactions: vec![tx1, tx2], + transaction_outputs: vec![ + starknet_api::transaction::TransactionOutput::Invoke( + starknet_api::transaction::InvokeTransactionOutput::default(), + ), + starknet_api::transaction::TransactionOutput::Invoke( + starknet_api::transaction::InvokeTransactionOutput::default(), + ), + ], + transaction_hashes: vec![tx_hash1, tx_hash2], + }) .unwrap() - .append_state_diff( - BlockNumber(3), - StarknetApiStateDiff { - nonces: indexmap!(*ACCOUNT_ADDRESS => nonce!(2_u128)), - ..Default::default() - }, - ) + .append_state_diff(BlockNumber(3), StarknetApiStateDiff { + nonces: indexmap!(*ACCOUNT_ADDRESS => nonce!(2_u128)), + ..Default::default() + }) .unwrap() .append_classes(BlockNumber(3), &[], &[]) .unwrap() @@ -864,10 +856,9 @@ async fn trace_block_transactions_regular_and_pending() { prepare_storage_for_execution(storage_writer); let res = module - .call::<_, Vec>( - "starknet_V0_8_traceBlockTransactions", - [BlockId::Tag(Tag::Pending)], - ) + .call::<_, Vec>("starknet_V0_8_traceBlockTransactions", [ + BlockId::Tag(Tag::Pending), + ]) .await .unwrap(); @@ -951,45 +942,36 @@ async fn trace_block_transactions_and_trace_transaction_execution_context() { writer .begin_rw_txn() .unwrap() - .append_header( - BlockNumber(3), - &BlockHeader { - block_hash: BlockHash(felt!("0x3")), - block_header_without_hash: BlockHeaderWithoutHash { - block_number: BlockNumber(3), - l1_gas_price: *GAS_PRICE, - sequencer: *SEQUENCER_ADDRESS, - timestamp: *BLOCK_TIMESTAMP, - parent_hash: BlockHash(felt!("0x2")), - ..Default::default() - }, + .append_header(BlockNumber(3), &BlockHeader { + block_hash: BlockHash(felt!("0x3")), + block_header_without_hash: BlockHeaderWithoutHash { + block_number: BlockNumber(3), + l1_gas_price: *GAS_PRICE, + sequencer: *SEQUENCER_ADDRESS, + timestamp: *BLOCK_TIMESTAMP, + parent_hash: BlockHash(felt!("0x2")), ..Default::default() }, - ) + ..Default::default() + }) .unwrap() - .append_body( - BlockNumber(3), - BlockBody { - transactions: vec![tx1, tx2], - transaction_outputs: vec![ - starknet_api::transaction::TransactionOutput::Invoke( - starknet_api::transaction::InvokeTransactionOutput::default(), - ), - starknet_api::transaction::TransactionOutput::Invoke( - starknet_api::transaction::InvokeTransactionOutput::default(), - ), - ], - transaction_hashes: vec![tx_hash1, tx_hash2], - }, - ) + .append_body(BlockNumber(3), BlockBody { + transactions: vec![tx1, tx2], + transaction_outputs: vec![ + starknet_api::transaction::TransactionOutput::Invoke( + starknet_api::transaction::InvokeTransactionOutput::default(), + ), + starknet_api::transaction::TransactionOutput::Invoke( + starknet_api::transaction::InvokeTransactionOutput::default(), + ), + ], + transaction_hashes: vec![tx_hash1, tx_hash2], + }) .unwrap() - .append_state_diff( - BlockNumber(3), - StarknetApiStateDiff { - nonces: indexmap!(*ACCOUNT_ADDRESS => nonce!(2_u128)), - ..Default::default() - }, - ) + .append_state_diff(BlockNumber(3), StarknetApiStateDiff { + nonces: indexmap!(*ACCOUNT_ADDRESS => nonce!(2_u128)), + ..Default::default() + }) .unwrap() .append_classes(BlockNumber(3), &[], &[]) .unwrap() @@ -1019,10 +1001,9 @@ async fn trace_block_transactions_and_trace_transaction_execution_context() { ); let res = module - .call::<_, Vec>( - "starknet_V0_8_traceBlockTransactions", - [BlockId::HashOrNumber(BlockHashOrNumber::Number(BlockNumber(3)))], - ) + .call::<_, Vec>("starknet_V0_8_traceBlockTransactions", [ + BlockId::HashOrNumber(BlockHashOrNumber::Number(BlockNumber(3))), + ]) .await .unwrap(); validate_result(res[0].trace_root.clone()); @@ -1138,10 +1119,9 @@ async fn pending_trace_block_transactions_and_trace_transaction_execution_contex ); let res = module - .call::<_, Vec>( - "starknet_V0_8_traceBlockTransactions", - [BlockId::Tag(Tag::Pending)], - ) + .call::<_, Vec>("starknet_V0_8_traceBlockTransactions", [ + BlockId::Tag(Tag::Pending), + ]) .await .unwrap(); validate_result(res[0].trace_root.clone()); @@ -1433,7 +1413,7 @@ fn get_calldata_for_test_execution_info( let entry_point_selector = selector_from_name("test_get_execution_info"); let expected_block_number = felt!(expected_block_number.0); let expected_block_timestamp = felt!(expected_block_timestamp.0); - let expected_sequencer_address = *(expected_sequencer_address.0 .0.key()); + let expected_sequencer_address = *(expected_sequencer_address.0.0.key()); let expected_caller_address = *(invoke_tx.sender_address.0.key()); let expected_contract_address = *CONTRACT_ADDRESS.0.key(); let expected_transaction_version = override_tx_version.unwrap_or(Felt::ONE); @@ -1623,81 +1603,68 @@ fn prepare_storage_for_execution(mut storage_writer: StorageWriter) -> StorageWr storage_writer .begin_rw_txn() .unwrap() - .append_header( - BlockNumber(0), - &BlockHeader { - block_header_without_hash: BlockHeaderWithoutHash { - l1_gas_price: *GAS_PRICE, - l1_data_gas_price: *DATA_GAS_PRICE, - sequencer: *SEQUENCER_ADDRESS, - timestamp: *BLOCK_TIMESTAMP, - ..Default::default() - }, + .append_header(BlockNumber(0), &BlockHeader { + block_header_without_hash: BlockHeaderWithoutHash { + l1_gas_price: *GAS_PRICE, + l1_data_gas_price: *DATA_GAS_PRICE, + sequencer: *SEQUENCER_ADDRESS, + timestamp: *BLOCK_TIMESTAMP, ..Default::default() }, - ) + ..Default::default() + }) .unwrap() .append_body(BlockNumber(0), BlockBody::default()) .unwrap() - .append_state_diff( - BlockNumber(0), - StarknetApiStateDiff { - deployed_contracts: indexmap!( - *DEPRECATED_CONTRACT_ADDRESS => class_hash1, - *CONTRACT_ADDRESS => class_hash2, - *ACCOUNT_ADDRESS => *ACCOUNT_CLASS_HASH, - *TEST_ERC20_CONTRACT_ADDRESS => *TEST_ERC20_CONTRACT_CLASS_HASH, - ), - storage_diffs: indexmap!( - *TEST_ERC20_CONTRACT_ADDRESS => indexmap!( - // Give the accounts some balance. - account_balance_key => *ACCOUNT_INITIAL_BALANCE, - // Give the first account mint permission (what is this?). - minter_var_address => *ACCOUNT_ADDRESS.0.key() - ), - ), - declared_classes: indexmap!(class_hash2 => compiled_class_hash), - deprecated_declared_classes: vec![ - class_hash1, - *ACCOUNT_CLASS_HASH, - *TEST_ERC20_CONTRACT_CLASS_HASH, - ], - nonces: indexmap!( - *TEST_ERC20_CONTRACT_ADDRESS => Nonce::default(), - *CONTRACT_ADDRESS => Nonce::default(), - *DEPRECATED_CONTRACT_ADDRESS => Nonce::default(), - *ACCOUNT_ADDRESS => Nonce::default(), + .append_state_diff(BlockNumber(0), StarknetApiStateDiff { + deployed_contracts: indexmap!( + *DEPRECATED_CONTRACT_ADDRESS => class_hash1, + *CONTRACT_ADDRESS => class_hash2, + *ACCOUNT_ADDRESS => *ACCOUNT_CLASS_HASH, + *TEST_ERC20_CONTRACT_ADDRESS => *TEST_ERC20_CONTRACT_CLASS_HASH, + ), + storage_diffs: indexmap!( + *TEST_ERC20_CONTRACT_ADDRESS => indexmap!( + // Give the accounts some balance. + account_balance_key => *ACCOUNT_INITIAL_BALANCE, + // Give the first account mint permission (what is this?). + minter_var_address => *ACCOUNT_ADDRESS.0.key() ), - replaced_classes: indexmap!(), - }, - ) - .unwrap() - .append_classes( - BlockNumber(0), - &[(class_hash2, &class2)], - &[ - (class_hash1, &class1), - (*ACCOUNT_CLASS_HASH, &account_class), - (*TEST_ERC20_CONTRACT_CLASS_HASH, &fee_contract_class), + ), + declared_classes: indexmap!(class_hash2 => compiled_class_hash), + deprecated_declared_classes: vec![ + class_hash1, + *ACCOUNT_CLASS_HASH, + *TEST_ERC20_CONTRACT_CLASS_HASH, ], - ) + nonces: indexmap!( + *TEST_ERC20_CONTRACT_ADDRESS => Nonce::default(), + *CONTRACT_ADDRESS => Nonce::default(), + *DEPRECATED_CONTRACT_ADDRESS => Nonce::default(), + *ACCOUNT_ADDRESS => Nonce::default(), + ), + replaced_classes: indexmap!(), + }) + .unwrap() + .append_classes(BlockNumber(0), &[(class_hash2, &class2)], &[ + (class_hash1, &class1), + (*ACCOUNT_CLASS_HASH, &account_class), + (*TEST_ERC20_CONTRACT_CLASS_HASH, &fee_contract_class), + ]) .unwrap() .append_casm(&class_hash2, &casm) .unwrap() - .append_header( - BlockNumber(1), - &BlockHeader { - block_hash: BlockHash(felt!("0x1")), - block_header_without_hash: BlockHeaderWithoutHash { - l1_gas_price: different_gas_price, - sequencer: *SEQUENCER_ADDRESS, - timestamp: *BLOCK_TIMESTAMP, - block_number: BlockNumber(1), - ..Default::default() - }, + .append_header(BlockNumber(1), &BlockHeader { + block_hash: BlockHash(felt!("0x1")), + block_header_without_hash: BlockHeaderWithoutHash { + l1_gas_price: different_gas_price, + sequencer: *SEQUENCER_ADDRESS, + timestamp: *BLOCK_TIMESTAMP, + block_number: BlockNumber(1), ..Default::default() }, - ) + ..Default::default() + }) .unwrap() .append_body(BlockNumber(1), BlockBody::default()) .unwrap() @@ -1705,22 +1672,19 @@ fn prepare_storage_for_execution(mut storage_writer: StorageWriter) -> StorageWr .unwrap() .append_classes(BlockNumber(1), &[], &[]) .unwrap() - .append_header( - BlockNumber(2), - &BlockHeader { - block_hash: BlockHash(felt!("0x2")), - block_header_without_hash: BlockHeaderWithoutHash { - l1_gas_price: *GAS_PRICE, - sequencer: *SEQUENCER_ADDRESS, - timestamp: *BLOCK_TIMESTAMP, - // Test that l1_da_mode affects the fee. - l1_da_mode: L1DataAvailabilityMode::Blob, - block_number: BlockNumber(2), - ..Default::default() - }, + .append_header(BlockNumber(2), &BlockHeader { + block_hash: BlockHash(felt!("0x2")), + block_header_without_hash: BlockHeaderWithoutHash { + l1_gas_price: *GAS_PRICE, + sequencer: *SEQUENCER_ADDRESS, + timestamp: *BLOCK_TIMESTAMP, + // Test that l1_da_mode affects the fee. + l1_da_mode: L1DataAvailabilityMode::Blob, + block_number: BlockNumber(2), ..Default::default() }, - ) + ..Default::default() + }) .unwrap() .append_body(BlockNumber(2), BlockBody::default()) .unwrap() @@ -1738,19 +1702,16 @@ fn write_empty_block(mut storage_writer: StorageWriter) { storage_writer .begin_rw_txn() .unwrap() - .append_header( - BlockNumber(0), - &BlockHeader { - block_header_without_hash: BlockHeaderWithoutHash { - l1_gas_price: *GAS_PRICE, - l1_data_gas_price: *DATA_GAS_PRICE, - sequencer: *SEQUENCER_ADDRESS, - timestamp: *BLOCK_TIMESTAMP, - ..Default::default() - }, + .append_header(BlockNumber(0), &BlockHeader { + block_header_without_hash: BlockHeaderWithoutHash { + l1_gas_price: *GAS_PRICE, + l1_data_gas_price: *DATA_GAS_PRICE, + sequencer: *SEQUENCER_ADDRESS, + timestamp: *BLOCK_TIMESTAMP, ..Default::default() }, - ) + ..Default::default() + }) .unwrap() .append_body(BlockNumber(0), BlockBody::default()) .unwrap() diff --git a/crates/papyrus_rpc/src/v0_8/transaction.rs b/crates/papyrus_rpc/src/v0_8/transaction.rs index 0b6a4a650d..0de7bdd302 100644 --- a/crates/papyrus_rpc/src/v0_8/transaction.rs +++ b/crates/papyrus_rpc/src/v0_8/transaction.rs @@ -7,13 +7,13 @@ use std::num::NonZeroU64; use std::ops::Add; use std::sync::Arc; -use ethers::core::abi::{encode_packed, Token}; +use ethers::core::abi::{Token, encode_packed}; use ethers::core::utils::keccak256; use jsonrpsee::types::ErrorObjectOwned; use papyrus_execution::objects::PriceUnit; +use papyrus_storage::StorageTxn; use papyrus_storage::body::BodyStorageReader; use papyrus_storage::db::TransactionKind; -use papyrus_storage::StorageTxn; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use starknet_api::block::{BlockHash, BlockNumber, BlockStatus}; use starknet_api::core::{ diff --git a/crates/papyrus_rpc/src/v0_8/transaction_test.rs b/crates/papyrus_rpc/src/v0_8/transaction_test.rs index f9543bd518..6a5cb5b991 100644 --- a/crates/papyrus_rpc/src/v0_8/transaction_test.rs +++ b/crates/papyrus_rpc/src/v0_8/transaction_test.rs @@ -1,5 +1,5 @@ use papyrus_test_utils::{ - auto_impl_get_test_instance, get_number_of_variants, get_rng, GetTestInstance, + GetTestInstance, auto_impl_get_test_instance, get_number_of_variants, get_rng, }; use pretty_assertions::assert_eq; use starknet_api::core::{ClassHash, ContractAddress, EntryPointSelector, Nonce}; diff --git a/crates/papyrus_rpc/src/v0_8/write_api_error.rs b/crates/papyrus_rpc/src/v0_8/write_api_error.rs index 5b7db6963b..c0bf343c23 100644 --- a/crates/papyrus_rpc/src/v0_8/write_api_error.rs +++ b/crates/papyrus_rpc/src/v0_8/write_api_error.rs @@ -1,11 +1,11 @@ use starknet_client::starknet_error::{KnownStarknetErrorCode, StarknetError, StarknetErrorCode}; use super::error::{ - unexpected_error, validation_failure, JsonRpcError, CLASS_ALREADY_DECLARED, - CLASS_HASH_NOT_FOUND, COMPILATION_FAILED, COMPILED_CLASS_HASH_MISMATCH, + CLASS_ALREADY_DECLARED, CLASS_HASH_NOT_FOUND, COMPILATION_FAILED, COMPILED_CLASS_HASH_MISMATCH, CONTRACT_CLASS_SIZE_IS_TOO_LARGE, DUPLICATE_TX, INSUFFICIENT_ACCOUNT_BALANCE, - INSUFFICIENT_MAX_FEE, INVALID_TRANSACTION_NONCE, NON_ACCOUNT, - UNSUPPORTED_CONTRACT_CLASS_VERSION, UNSUPPORTED_TX_VERSION, + INSUFFICIENT_MAX_FEE, INVALID_TRANSACTION_NONCE, JsonRpcError, NON_ACCOUNT, + UNSUPPORTED_CONTRACT_CLASS_VERSION, UNSUPPORTED_TX_VERSION, unexpected_error, + validation_failure, }; #[cfg(test)] diff --git a/crates/papyrus_rpc/src/v0_8/write_api_error_test.rs b/crates/papyrus_rpc/src/v0_8/write_api_error_test.rs index e19ad6e6a1..40698df280 100644 --- a/crates/papyrus_rpc/src/v0_8/write_api_error_test.rs +++ b/crates/papyrus_rpc/src/v0_8/write_api_error_test.rs @@ -9,7 +9,7 @@ use super::{ starknet_error_to_declare_error, starknet_error_to_deploy_account_error, starknet_error_to_invoke_error, }; -use crate::test_utils::{get_starknet_spec_api_schema_for_method_errors, SpecFile}; +use crate::test_utils::{SpecFile, get_starknet_spec_api_schema_for_method_errors}; use crate::version_config::VERSION_0_8 as Version; const MESSAGE: &str = "message"; diff --git a/crates/papyrus_rpc/src/v0_8/write_api_result_test.rs b/crates/papyrus_rpc/src/v0_8/write_api_result_test.rs index ea6ff39f90..e0a115845a 100644 --- a/crates/papyrus_rpc/src/v0_8/write_api_result_test.rs +++ b/crates/papyrus_rpc/src/v0_8/write_api_result_test.rs @@ -1,4 +1,4 @@ -use papyrus_test_utils::{auto_impl_get_test_instance, get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, auto_impl_get_test_instance, get_rng}; use serde::Serialize; use starknet_api::core::{ClassHash, ContractAddress, PatriciaKey}; use starknet_api::transaction::TransactionHash; @@ -8,7 +8,7 @@ use starknet_client::writer::objects::response::{ }; use super::{AddDeclareOkResult, AddDeployAccountOkResult, AddInvokeOkResult}; -use crate::test_utils::{get_starknet_spec_api_schema_for_method_results, SpecFile}; +use crate::test_utils::{SpecFile, get_starknet_spec_api_schema_for_method_results}; use crate::version_config::VERSION_0_8 as VERSION; auto_impl_get_test_instance! { diff --git a/crates/papyrus_rpc/src/version_config_test.rs b/crates/papyrus_rpc/src/version_config_test.rs index f1e3f349b0..a6fb850a04 100644 --- a/crates/papyrus_rpc/src/version_config_test.rs +++ b/crates/papyrus_rpc/src/version_config_test.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use pretty_assertions::assert_eq; -use super::{VersionState, VERSION_CONFIG}; +use super::{VERSION_CONFIG, VersionState}; #[tokio::test] async fn validate_version_configuration() { diff --git a/crates/papyrus_state_reader/src/papyrus_state.rs b/crates/papyrus_state_reader/src/papyrus_state.rs index 14bc9887c4..7fe5dd7180 100644 --- a/crates/papyrus_state_reader/src/papyrus_state.rs +++ b/crates/papyrus_state_reader/src/papyrus_state.rs @@ -4,10 +4,10 @@ use blockifier::execution::contract_class::{ use blockifier::state::errors::StateError; use blockifier::state::global_cache::GlobalContractCache; use blockifier::state::state_api::{StateReader, StateResult}; +use papyrus_storage::StorageReader; use papyrus_storage::compiled_class::CasmStorageReader; use papyrus_storage::db::RO; use papyrus_storage::state::StateStorageReader; -use papyrus_storage::StorageReader; use starknet_api::block::BlockNumber; use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce}; use starknet_api::state::{StateNumber, StorageKey}; diff --git a/crates/papyrus_state_reader/src/papyrus_state_test.rs b/crates/papyrus_state_reader/src/papyrus_state_test.rs index 0f398f00af..ed7e0c7c17 100644 --- a/crates/papyrus_state_reader/src/papyrus_state_test.rs +++ b/crates/papyrus_state_reader/src/papyrus_state_test.rs @@ -3,10 +3,10 @@ use blockifier::execution::call_info::CallExecution; use blockifier::execution::entry_point::CallEntryPoint; use blockifier::retdata; use blockifier::state::cached_state::CachedState; -use blockifier::state::global_cache::{GlobalContractCache, GLOBAL_CONTRACT_CACHE_SIZE_FOR_TEST}; +use blockifier::state::global_cache::{GLOBAL_CONTRACT_CACHE_SIZE_FOR_TEST, GlobalContractCache}; use blockifier::state::state_api::StateReader; use blockifier::test_utils::contracts::FeatureContract; -use blockifier::test_utils::{trivial_external_entry_point_new, CairoVersion}; +use blockifier::test_utils::{CairoVersion, trivial_external_entry_point_new}; use indexmap::IndexMap; use papyrus_storage::class::ClassStorageWriter; use papyrus_storage::state::StateStorageWriter; diff --git a/crates/papyrus_storage/src/base_layer.rs b/crates/papyrus_storage/src/base_layer.rs index 90ca7ea8a0..c14072866d 100644 --- a/crates/papyrus_storage/src/base_layer.rs +++ b/crates/papyrus_storage/src/base_layer.rs @@ -42,7 +42,7 @@ mod base_layer_test; use starknet_api::block::BlockNumber; use crate::db::table_types::Table; -use crate::db::{TransactionKind, RW}; +use crate::db::{RW, TransactionKind}; use crate::{MarkerKind, StorageResult, StorageTxn}; /// Interface for reading data related to the base layer. diff --git a/crates/papyrus_storage/src/bin/storage_benchmark.rs b/crates/papyrus_storage/src/bin/storage_benchmark.rs index d8d164929e..566b259f80 100644 --- a/crates/papyrus_storage/src/bin/storage_benchmark.rs +++ b/crates/papyrus_storage/src/bin/storage_benchmark.rs @@ -1,11 +1,11 @@ -use std::fs::{read_to_string, File}; +use std::fs::{File, read_to_string}; use std::time::Duration; use clap::{Arg, Command}; use papyrus_common::storage_query::StorageQuery; +use papyrus_storage::StorageConfig; use papyrus_storage::db::DbConfig; use papyrus_storage::state::StateStorageReader; -use papyrus_storage::StorageConfig; use serde::{Deserialize, Serialize}; use starknet_api::core::ChainId; use statistical::median; diff --git a/crates/papyrus_storage/src/body/body_test.rs b/crates/papyrus_storage/src/body/body_test.rs index 36b2609236..052d549b12 100644 --- a/crates/papyrus_storage/src/body/body_test.rs +++ b/crates/papyrus_storage/src/body/body_test.rs @@ -246,44 +246,46 @@ async fn get_reverted_body_returns_none() { append_2_bodies(&mut writer); // Verify that we can get block 1's transactions before the revert. - assert!(reader - .begin_ro_txn() - .unwrap() - .get_block_transactions(BlockNumber(1)) - .unwrap() - .is_some()); - assert!(reader - .begin_ro_txn() - .unwrap() - .get_block_transaction_hashes(BlockNumber(1)) - .unwrap() - .is_some()); - assert!(reader - .begin_ro_txn() - .unwrap() - .get_block_transaction_outputs(BlockNumber(1)) - .unwrap() - .is_some()); + assert!( + reader.begin_ro_txn().unwrap().get_block_transactions(BlockNumber(1)).unwrap().is_some() + ); + assert!( + reader + .begin_ro_txn() + .unwrap() + .get_block_transaction_hashes(BlockNumber(1)) + .unwrap() + .is_some() + ); + assert!( + reader + .begin_ro_txn() + .unwrap() + .get_block_transaction_outputs(BlockNumber(1)) + .unwrap() + .is_some() + ); writer.begin_rw_txn().unwrap().revert_body(BlockNumber(1)).unwrap().0.commit().unwrap(); - assert!(reader - .begin_ro_txn() - .unwrap() - .get_block_transactions(BlockNumber(1)) - .unwrap() - .is_none()); - assert!(reader - .begin_ro_txn() - .unwrap() - .get_block_transaction_hashes(BlockNumber(1)) - .unwrap() - .is_none()); - assert!(reader - .begin_ro_txn() - .unwrap() - .get_block_transaction_outputs(BlockNumber(1)) - .unwrap() - .is_none()); + assert!( + reader.begin_ro_txn().unwrap().get_block_transactions(BlockNumber(1)).unwrap().is_none() + ); + assert!( + reader + .begin_ro_txn() + .unwrap() + .get_block_transaction_hashes(BlockNumber(1)) + .unwrap() + .is_none() + ); + assert!( + reader + .begin_ro_txn() + .unwrap() + .get_block_transaction_outputs(BlockNumber(1)) + .unwrap() + .is_none() + ); } #[tokio::test] @@ -313,24 +315,25 @@ async fn revert_transactions() { tx_hash ); } - assert!(reader - .begin_ro_txn() - .unwrap() - .get_block_transactions(BlockNumber(0)) - .unwrap() - .is_some()); - assert!(reader - .begin_ro_txn() - .unwrap() - .get_block_transaction_hashes(BlockNumber(0)) - .unwrap() - .is_some()); - assert!(reader - .begin_ro_txn() - .unwrap() - .get_block_transaction_outputs(BlockNumber(0)) - .unwrap() - .is_some()); + assert!( + reader.begin_ro_txn().unwrap().get_block_transactions(BlockNumber(0)).unwrap().is_some() + ); + assert!( + reader + .begin_ro_txn() + .unwrap() + .get_block_transaction_hashes(BlockNumber(0)) + .unwrap() + .is_some() + ); + assert!( + reader + .begin_ro_txn() + .unwrap() + .get_block_transaction_outputs(BlockNumber(0)) + .unwrap() + .is_some() + ); writer.begin_rw_txn().unwrap().revert_body(BlockNumber(0)).unwrap().0.commit().unwrap(); @@ -340,37 +343,37 @@ async fn revert_transactions() { assert!(reader.begin_ro_txn().unwrap().get_transaction(tx_index).unwrap().is_none()); assert!(reader.begin_ro_txn().unwrap().get_transaction_output(tx_index).unwrap().is_none()); - assert!(reader + assert!( + reader.begin_ro_txn().unwrap().get_transaction_idx_by_hash(&tx_hash).unwrap().is_none() + ); + assert!( + reader + .begin_ro_txn() + .unwrap() + .get_transaction_hash_by_idx(&tx_index) + .unwrap() + .is_none() + ); + } + assert!( + reader.begin_ro_txn().unwrap().get_block_transactions(BlockNumber(0)).unwrap().is_none() + ); + assert!( + reader .begin_ro_txn() .unwrap() - .get_transaction_idx_by_hash(&tx_hash) + .get_block_transaction_hashes(BlockNumber(0)) .unwrap() - .is_none()); - assert!(reader + .is_none() + ); + assert!( + reader .begin_ro_txn() .unwrap() - .get_transaction_hash_by_idx(&tx_index) + .get_block_transaction_outputs(BlockNumber(0)) .unwrap() - .is_none()); - } - assert!(reader - .begin_ro_txn() - .unwrap() - .get_block_transactions(BlockNumber(0)) - .unwrap() - .is_none()); - assert!(reader - .begin_ro_txn() - .unwrap() - .get_block_transaction_hashes(BlockNumber(0)) - .unwrap() - .is_none()); - assert!(reader - .begin_ro_txn() - .unwrap() - .get_block_transaction_outputs(BlockNumber(0)) - .unwrap() - .is_none()); + .is_none() + ); } fn append_2_bodies(writer: &mut StorageWriter) { diff --git a/crates/papyrus_storage/src/body/events.rs b/crates/papyrus_storage/src/body/events.rs index acba70b006..8ff402a0bc 100644 --- a/crates/papyrus_storage/src/body/events.rs +++ b/crates/papyrus_storage/src/body/events.rs @@ -265,7 +265,7 @@ where let events_table = self.open_table(&self.tables.events)?; let mut cursor = events_table.cursor(&self.txn)?; let events_queue = if let Some((contract_address, tx_index)) = - cursor.lower_bound(&(key.0, key.1 .0))?.map(|(key, _)| key) + cursor.lower_bound(&(key.0, key.1.0))?.map(|(key, _)| key) { let tx_metadata = transaction_metadata_table.get(&self.txn, &tx_index)?.unwrap_or_else(|| { @@ -277,7 +277,7 @@ where // In case of we get tx_index different from the key, it means we need to start a new // transaction which means the first event. - let start_event_index = if tx_index == key.1 .0 { key.1 .1 .0 } else { 0 }; + let start_event_index = if tx_index == key.1.0 { key.1.1.0 } else { 0 }; // TODO(dvir): don't clone the events here. get_events_from_tx( tx_output.events().into(), diff --git a/crates/papyrus_storage/src/body/events_test.rs b/crates/papyrus_storage/src/body/events_test.rs index 388d4dd655..0285ba76bb 100644 --- a/crates/papyrus_storage/src/body/events_test.rs +++ b/crates/papyrus_storage/src/body/events_test.rs @@ -8,7 +8,7 @@ use starknet_api::transaction::{ Event, EventContent, EventData, EventIndexInTransactionOutput, TransactionOffsetInBlock, }; -use crate::body::events::{get_events_from_tx, EventIndex, EventsReader}; +use crate::body::events::{EventIndex, EventsReader, get_events_from_tx}; use crate::body::{BodyStorageWriter, TransactionIndex}; use crate::db::table_types::Table; use crate::header::HeaderStorageWriter; @@ -146,13 +146,15 @@ fn revert_events() { ); // Test iter events using the storage reader. - assert!(storage_reader - .begin_ro_txn() - .unwrap() - .iter_events(None, event_index, block_number) - .unwrap() - .last() - .is_some()); + assert!( + storage_reader + .begin_ro_txn() + .unwrap() + .iter_events(None, event_index, block_number) + .unwrap() + .last() + .is_some() + ); // Test events raw table. let txn = storage_reader.begin_ro_txn().unwrap(); @@ -178,13 +180,15 @@ fn revert_events() { .0 .commit() .unwrap(); - assert!(storage_reader - .begin_ro_txn() - .unwrap() - .iter_events(None, event_index, block_number) - .unwrap() - .last() - .is_none()); + assert!( + storage_reader + .begin_ro_txn() + .unwrap() + .iter_events(None, event_index, block_number) + .unwrap() + .last() + .is_none() + ); let txn = storage_reader.begin_ro_txn().unwrap(); let events_table = txn.txn.open_table(&txn.tables.events).unwrap(); @@ -227,10 +231,10 @@ fn get_events_from_tx_test() { ((ca1, EventIndex(tx_index, EventIndexInTransactionOutput(2))), e3.content.clone()); // All events. - assert_eq!( - get_events_from_tx(events.clone(), tx_index, ca1, 0), - vec![e1_output.clone(), e3_output.clone()] - ); + assert_eq!(get_events_from_tx(events.clone(), tx_index, ca1, 0), vec![ + e1_output.clone(), + e3_output.clone() + ]); assert_eq!(get_events_from_tx(events.clone(), tx_index, ca2, 0), vec![e2_output.clone()]); // All events of starting from the second event. diff --git a/crates/papyrus_storage/src/body/mod.rs b/crates/papyrus_storage/src/body/mod.rs index 7122ce6ab7..0bdef5b67b 100644 --- a/crates/papyrus_storage/src/body/mod.rs +++ b/crates/papyrus_storage/src/body/mod.rs @@ -56,7 +56,7 @@ use tracing::debug; use crate::db::serialization::{NoVersionValueWrapper, VersionZeroWrapper}; use crate::db::table_types::{CommonPrefix, DbCursorTrait, NoValue, SimpleTable, Table}; -use crate::db::{DbTransaction, TableHandle, TransactionKind, RW}; +use crate::db::{DbTransaction, RW, TableHandle, TransactionKind}; use crate::{ FileHandlers, MarkerKind, MarkersTable, OffsetKind, StorageError, StorageResult, StorageScope, StorageTxn, TransactionMetadata, @@ -446,11 +446,11 @@ fn write_transactions<'env>( let tx_output_location = file_handlers.append_transaction_output(tx_output); write_events(tx_output, txn, events_table, transaction_index)?; transaction_hash_to_idx_table.insert(txn, tx_hash, &transaction_index)?; - transaction_metadata_table.append( - txn, - &transaction_index, - &TransactionMetadata { tx_location, tx_output_location, tx_hash: *tx_hash }, - )?; + transaction_metadata_table.append(txn, &transaction_index, &TransactionMetadata { + tx_location, + tx_output_location, + tx_hash: *tx_hash, + })?; // If this is the last iteration, update the file offset table. if index == block_body.transactions.len() - 1 { diff --git a/crates/papyrus_storage/src/class.rs b/crates/papyrus_storage/src/class.rs index cc12fe22f4..a31080afdc 100644 --- a/crates/papyrus_storage/src/class.rs +++ b/crates/papyrus_storage/src/class.rs @@ -74,7 +74,7 @@ use starknet_api::deprecated_contract_class::ContractClass as DeprecatedContract use starknet_api::state::SierraContractClass; use crate::db::table_types::Table; -use crate::db::{TransactionKind, RW}; +use crate::db::{RW, TransactionKind}; use crate::state::{DeclaredClassesTable, DeprecatedDeclaredClassesTable, FileOffsetTable}; use crate::{ DbTransaction, FileHandlers, IndexedDeprecatedContractClass, MarkerKind, OffsetKind, diff --git a/crates/papyrus_storage/src/class_test.rs b/crates/papyrus_storage/src/class_test.rs index d9e6bff074..5e4c4ac3eb 100644 --- a/crates/papyrus_storage/src/class_test.rs +++ b/crates/papyrus_storage/src/class_test.rs @@ -9,9 +9,9 @@ use starknet_api::state::{SierraContractClass, StateNumber, ThinStateDiff}; use starknet_api::test_utils::read_json_file; use super::{ClassStorageReader, ClassStorageWriter}; +use crate::StorageError; use crate::state::{StateStorageReader, StateStorageWriter}; use crate::test_utils::get_test_storage; -use crate::StorageError; #[test] fn append_classes_writes_correct_data() { @@ -28,20 +28,16 @@ fn append_classes_writes_correct_data() { writer .begin_rw_txn() .unwrap() - .append_state_diff( - BlockNumber(0), - ThinStateDiff { - declared_classes: indexmap! { class_hash => CompiledClassHash::default() }, - deprecated_declared_classes: vec![deprecated_class_hash], - ..Default::default() - }, - ) + .append_state_diff(BlockNumber(0), ThinStateDiff { + declared_classes: indexmap! { class_hash => CompiledClassHash::default() }, + deprecated_declared_classes: vec![deprecated_class_hash], + ..Default::default() + }) .unwrap() - .append_classes( - BlockNumber(0), - &[(class_hash, &expected_class)], - &[(deprecated_class_hash, &expected_deprecated_class)], - ) + .append_classes(BlockNumber(0), &[(class_hash, &expected_class)], &[( + deprecated_class_hash, + &expected_deprecated_class, + )]) .unwrap() .commit() .unwrap(); @@ -105,10 +101,12 @@ fn append_deprecated_class_not_in_state_diff() { let statetxn = txn.get_state_reader().unwrap(); let state0 = StateNumber::right_after_block(BlockNumber(0)).unwrap(); - assert!(statetxn - .get_deprecated_class_definition_at(state0, &deprecated_class_hash) - .unwrap() - .is_none()); + assert!( + statetxn + .get_deprecated_class_definition_at(state0, &deprecated_class_hash) + .unwrap() + .is_none() + ); let state1 = StateNumber::right_after_block(BlockNumber(1)).unwrap(); assert_eq!( diff --git a/crates/papyrus_storage/src/compiled_class.rs b/crates/papyrus_storage/src/compiled_class.rs index d0e2b656aa..853f193ab9 100644 --- a/crates/papyrus_storage/src/compiled_class.rs +++ b/crates/papyrus_storage/src/compiled_class.rs @@ -53,7 +53,7 @@ use starknet_api::core::ClassHash; use crate::db::serialization::VersionZeroWrapper; use crate::db::table_types::{SimpleTable, Table}; -use crate::db::{DbTransaction, TableHandle, TransactionKind, RW}; +use crate::db::{DbTransaction, RW, TableHandle, TransactionKind}; use crate::mmap_file::LocationInFile; use crate::{FileHandlers, MarkerKind, MarkersTable, OffsetKind, StorageResult, StorageTxn}; diff --git a/crates/papyrus_storage/src/compiled_class_test.rs b/crates/papyrus_storage/src/compiled_class_test.rs index 204cada574..b0724e02e5 100644 --- a/crates/papyrus_storage/src/compiled_class_test.rs +++ b/crates/papyrus_storage/src/compiled_class_test.rs @@ -4,10 +4,10 @@ use pretty_assertions::assert_eq; use starknet_api::core::ClassHash; use starknet_api::test_utils::read_json_file; +use crate::StorageError; use crate::compiled_class::{CasmStorageReader, CasmStorageWriter}; use crate::db::{DbError, KeyAlreadyExistsError}; use crate::test_utils::get_test_storage; -use crate::StorageError; #[test] fn append_casm() { @@ -34,25 +34,21 @@ fn casm_rewrite() { writer .begin_rw_txn() .unwrap() - .append_casm( - &ClassHash::default(), - &CasmContractClass { - prime: Default::default(), - compiler_version: Default::default(), - bytecode: Default::default(), - bytecode_segment_lengths: Default::default(), - hints: Default::default(), - pythonic_hints: Default::default(), - entry_points_by_type: Default::default(), - }, - ) + .append_casm(&ClassHash::default(), &CasmContractClass { + prime: Default::default(), + compiler_version: Default::default(), + bytecode: Default::default(), + bytecode_segment_lengths: Default::default(), + hints: Default::default(), + pythonic_hints: Default::default(), + entry_points_by_type: Default::default(), + }) .unwrap() .commit() .unwrap(); - let Err(err) = writer.begin_rw_txn().unwrap().append_casm( - &ClassHash::default(), - &CasmContractClass { + let Err(err) = + writer.begin_rw_txn().unwrap().append_casm(&ClassHash::default(), &CasmContractClass { prime: Default::default(), compiler_version: Default::default(), bytecode: Default::default(), @@ -60,8 +56,8 @@ fn casm_rewrite() { hints: Default::default(), pythonic_hints: Default::default(), entry_points_by_type: Default::default(), - }, - ) else { + }) + else { panic!("Unexpected Ok."); }; diff --git a/crates/papyrus_storage/src/compression_utils.rs b/crates/papyrus_storage/src/compression_utils.rs index 66c5d789f1..a23ccc40d8 100644 --- a/crates/papyrus_storage/src/compression_utils.rs +++ b/crates/papyrus_storage/src/compression_utils.rs @@ -12,7 +12,7 @@ use crate::db::serialization::{StorageSerde, StorageSerdeError}; // TODO(Dvir): consider defining this for each type separately and pass it as an argument to the // decompress function. pub(crate) const MAX_DECOMPRESSED_SIZE: usize = 1 << 28; // 256 MB - // The compression level to use. Higher levels are slower but compress better. +// The compression level to use. Higher levels are slower but compress better. const COMPRESSION_LEVEL: i32 = zstd::DEFAULT_COMPRESSION_LEVEL; /// Returns the compressed data in a vector. diff --git a/crates/papyrus_storage/src/db/db_test.rs b/crates/papyrus_storage/src/db/db_test.rs index 747d88f458..760a22b4ba 100644 --- a/crates/papyrus_storage/src/db/db_test.rs +++ b/crates/papyrus_storage/src/db/db_test.rs @@ -5,7 +5,7 @@ use tempfile::TempDir; use crate::db::serialization::{NoVersionValueWrapper, ValueSerde, VersionZeroWrapper}; use crate::db::table_types::Table; -use crate::db::{get_page_size, open_env, DbError, DbIter, DbReader, DbResult, DbWriter}; +use crate::db::{DbError, DbIter, DbReader, DbResult, DbWriter, get_page_size, open_env}; use crate::test_utils::get_test_config; pub(crate) fn get_test_env() -> ((DbReader, DbWriter), TempDir) { diff --git a/crates/papyrus_storage/src/db/mod.rs b/crates/papyrus_storage/src/db/mod.rs index c1b5da78ac..cb445de6c9 100644 --- a/crates/papyrus_storage/src/db/mod.rs +++ b/crates/papyrus_storage/src/db/mod.rs @@ -30,7 +30,7 @@ use std::result; use std::sync::Arc; use libmdbx::{DatabaseFlags, Geometry, PageSize, WriteMap}; -use papyrus_config::dumping::{ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_param}; use papyrus_config::validators::{validate_ascii, validate_path_exists}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use papyrus_proc_macros::latency_histogram; diff --git a/crates/papyrus_storage/src/db/table_types/dup_sort_tables.rs b/crates/papyrus_storage/src/db/table_types/dup_sort_tables.rs index 5d267f9dba..714f8e4bdb 100644 --- a/crates/papyrus_storage/src/db/table_types/dup_sort_tables.rs +++ b/crates/papyrus_storage/src/db/table_types/dup_sort_tables.rs @@ -12,7 +12,7 @@ use super::{DbResult, Table, TableType}; use crate::db::serialization::{Key as KeyTrait, StorageSerde, StorageSerdeEx, ValueSerde}; use crate::db::{ DbCursor, DbCursorTrait, DbError, DbKeyType, DbTransaction, DbValueType, DbWriter, - KeyAlreadyExistsError, TableHandle, TableIdentifier, TransactionKind, RW, + KeyAlreadyExistsError, RW, TableHandle, TableIdentifier, TransactionKind, }; // NOTICE: If a write operation fails (insert, upsert, append, delete, append_greater_sub_key), the @@ -144,12 +144,8 @@ impl DbWriter { } } -impl< - 'env, - K: KeyTrait + Debug, - V: ValueSerde + Debug, - T: DupSortTableType + DupSortUtils, - > Table<'env> for TableHandle<'env, K, V, T> +impl<'env, K: KeyTrait + Debug, V: ValueSerde + Debug, T: DupSortTableType + DupSortUtils> + Table<'env> for TableHandle<'env, K, V, T> { type Key = K; type Value = V; @@ -361,12 +357,8 @@ impl< // TODO(dvir): consider adding unchecked version of the append function. #[allow(private_bounds)] -impl< - 'env, - K: KeyTrait + Debug, - V: ValueSerde + Debug, - T: DupSortTableType + DupSortUtils, - > TableHandle<'env, K, V, T> +impl<'env, K: KeyTrait + Debug, V: ValueSerde + Debug, T: DupSortTableType + DupSortUtils> + TableHandle<'env, K, V, T> { // Append a new value to the given key. The sub-key must be bigger than the last sub-key for the // given main-key, otherwise an error will be returned. @@ -407,11 +399,11 @@ impl< } impl< - Mode: TransactionKind, - K: KeyTrait + Debug, - V: ValueSerde + Debug, - T: DupSortTableType + DupSortUtils, - > DbCursorTrait for DbCursor<'_, Mode, K, V, T> + Mode: TransactionKind, + K: KeyTrait + Debug, + V: ValueSerde + Debug, + T: DupSortTableType + DupSortUtils, +> DbCursorTrait for DbCursor<'_, Mode, K, V, T> { type Key = K; type Value = V; diff --git a/crates/papyrus_storage/src/db/table_types/dup_sort_tables_test.rs b/crates/papyrus_storage/src/db/table_types/dup_sort_tables_test.rs index c8c01a9275..1dc76c9284 100644 --- a/crates/papyrus_storage/src/db/table_types/dup_sort_tables_test.rs +++ b/crates/papyrus_storage/src/db/table_types/dup_sort_tables_test.rs @@ -3,9 +3,9 @@ use assert_matches::assert_matches; use super::{DupSortTableType, DupSortUtils}; use crate::db::db_test::get_test_env; use crate::db::serialization::NoVersionValueWrapper; -use crate::db::table_types::dup_sort_tables::add_one; -use crate::db::table_types::test_utils::{random_table_test, table_test, TableKey, TableValue}; use crate::db::table_types::Table; +use crate::db::table_types::dup_sort_tables::add_one; +use crate::db::table_types::test_utils::{TableKey, TableValue, random_table_test, table_test}; use crate::db::{DbError, DbResult, DbWriter, TableIdentifier}; #[test] diff --git a/crates/papyrus_storage/src/db/table_types/mod.rs b/crates/papyrus_storage/src/db/table_types/mod.rs index 78113259da..b5d1d2e47a 100644 --- a/crates/papyrus_storage/src/db/table_types/mod.rs +++ b/crates/papyrus_storage/src/db/table_types/mod.rs @@ -4,7 +4,7 @@ use std::marker::PhantomData; use libmdbx::Cursor; use super::serialization::{Key as KeyTrait, ValueSerde}; -use super::{DbResult, DbTransaction, TransactionKind, RW}; +use super::{DbResult, DbTransaction, RW, TransactionKind}; mod dup_sort_tables; mod simple_table; diff --git a/crates/papyrus_storage/src/db/table_types/simple_table.rs b/crates/papyrus_storage/src/db/table_types/simple_table.rs index 4d70965fd1..b54621e660 100644 --- a/crates/papyrus_storage/src/db/table_types/simple_table.rs +++ b/crates/papyrus_storage/src/db/table_types/simple_table.rs @@ -12,8 +12,8 @@ use super::{DbResult, Table, TableType}; use crate::db::serialization::{Key as KeyTrait, ValueSerde}; use crate::db::table_types::DbCursorTrait; use crate::db::{ - DbCursor, DbError, DbKeyType, DbTransaction, DbValueType, DbWriter, KeyAlreadyExistsError, - TableHandle, TableIdentifier, TransactionKind, RW, + DbCursor, DbError, DbKeyType, DbTransaction, DbValueType, DbWriter, KeyAlreadyExistsError, RW, + TableHandle, TableIdentifier, TransactionKind, }; // A simple mapping between key and value. diff --git a/crates/papyrus_storage/src/db/table_types/simple_table_test.rs b/crates/papyrus_storage/src/db/table_types/simple_table_test.rs index 855c70dcc6..ee9720ad37 100644 --- a/crates/papyrus_storage/src/db/table_types/simple_table_test.rs +++ b/crates/papyrus_storage/src/db/table_types/simple_table_test.rs @@ -1,5 +1,5 @@ -use crate::db::table_types::test_utils::table_test; use crate::db::DbWriter; +use crate::db::table_types::test_utils::table_test; #[test] fn simple_table_test() { diff --git a/crates/papyrus_storage/src/db/table_types/test_utils.rs b/crates/papyrus_storage/src/db/table_types/test_utils.rs index 579f405b97..7925afce01 100644 --- a/crates/papyrus_storage/src/db/table_types/test_utils.rs +++ b/crates/papyrus_storage/src/db/table_types/test_utils.rs @@ -1,15 +1,15 @@ use assert_matches::assert_matches; -use rand::rngs::ThreadRng; use rand::Rng; +use rand::rngs::ThreadRng; use tracing::debug; use super::{Table, TableType}; +use crate::DbError; use crate::db::db_test::get_test_env; use crate::db::serialization::{NoVersionValueWrapper, StorageSerde, StorageSerdeError}; use crate::db::table_types::{DbCursor, DbCursorTrait}; -use crate::db::{DbReader, DbResult, DbWriter, TableHandle, TableIdentifier, RO, RW}; +use crate::db::{DbReader, DbResult, DbWriter, RO, RW, TableHandle, TableIdentifier}; use crate::serialization::serializers::auto_storage_serde; -use crate::DbError; // TODO(dvir): consider adding tests with keys and values in different sizes. diff --git a/crates/papyrus_storage/src/header.rs b/crates/papyrus_storage/src/header.rs index e8c24fed0a..2ef4aa3b70 100644 --- a/crates/papyrus_storage/src/header.rs +++ b/crates/papyrus_storage/src/header.rs @@ -52,7 +52,7 @@ use tracing::debug; use crate::db::serialization::NoVersionValueWrapper; use crate::db::table_types::{DbCursorTrait, SimpleTable, Table}; -use crate::db::{DbTransaction, TableHandle, TransactionKind, RW}; +use crate::db::{DbTransaction, RW, TableHandle, TransactionKind}; use crate::{MarkerKind, MarkersTable, StorageError, StorageResult, StorageTxn}; #[derive(Debug, Default, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord)] diff --git a/crates/papyrus_storage/src/header_test.rs b/crates/papyrus_storage/src/header_test.rs index d6ee6c0bf2..bfe2f4eeff 100644 --- a/crates/papyrus_storage/src/header_test.rs +++ b/crates/papyrus_storage/src/header_test.rs @@ -114,35 +114,29 @@ async fn get_reverted_block_number_by_hash_returns_none() { let block_hash = BlockHash(felt!("0x1")); // Verify that we can get block 1 by hash before the revert. - assert!(reader - .begin_ro_txn() - .unwrap() - .get_block_number_by_hash(&block_hash) - .unwrap() - .is_some()); + assert!( + reader.begin_ro_txn().unwrap().get_block_number_by_hash(&block_hash).unwrap().is_some() + ); writer.begin_rw_txn().unwrap().revert_header(BlockNumber(1)).unwrap().0.commit().unwrap(); - assert!(reader - .begin_ro_txn() - .unwrap() - .get_block_number_by_hash(&block_hash) - .unwrap() - .is_none()); + assert!( + reader.begin_ro_txn().unwrap().get_block_number_by_hash(&block_hash).unwrap().is_none() + ); } fn append_2_headers(writer: &mut StorageWriter) { writer .begin_rw_txn() .unwrap() - .append_header( - BlockNumber(0), - &BlockHeader { block_hash: BlockHash(felt!("0x0")), ..BlockHeader::default() }, - ) + .append_header(BlockNumber(0), &BlockHeader { + block_hash: BlockHash(felt!("0x0")), + ..BlockHeader::default() + }) .unwrap() - .append_header( - BlockNumber(1), - &BlockHeader { block_hash: BlockHash(felt!("0x1")), ..BlockHeader::default() }, - ) + .append_header(BlockNumber(1), &BlockHeader { + block_hash: BlockHash(felt!("0x1")), + ..BlockHeader::default() + }) .unwrap() .commit() .unwrap(); diff --git a/crates/papyrus_storage/src/lib.rs b/crates/papyrus_storage/src/lib.rs index 31968b03dd..745bd2bf79 100644 --- a/crates/papyrus_storage/src/lib.rs +++ b/crates/papyrus_storage/src/lib.rs @@ -110,9 +110,9 @@ use db::db_stats::{DbTableStats, DbWholeStats}; use db::serialization::{Key, NoVersionValueWrapper, ValueSerde, VersionZeroWrapper}; use db::table_types::{CommonPrefix, NoValue, Table, TableType}; use mmap_file::{ - open_file, FileHandler, LocationInFile, MMapFileError, MmapFileConfig, Reader, Writer, + FileHandler, LocationInFile, MMapFileError, MmapFileConfig, Reader, Writer, open_file, }; -use papyrus_config::dumping::{append_sub_config_name, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use papyrus_proc_macros::latency_histogram; use serde::{Deserialize, Serialize}; @@ -129,8 +129,8 @@ use version::{StorageVersionError, Version}; use crate::body::TransactionIndex; use crate::db::table_types::SimpleTable; use crate::db::{ - open_env, DbConfig, DbError, DbReader, DbTransaction, DbWriter, TableHandle, TableIdentifier, - TransactionKind, RO, RW, + DbConfig, DbError, DbReader, DbTransaction, DbWriter, RO, RW, TableHandle, TableIdentifier, + TransactionKind, open_env, }; use crate::header::StorageBlockHeader; use crate::mmap_file::MMapFileStats; diff --git a/crates/papyrus_storage/src/mmap_file/mod.rs b/crates/papyrus_storage/src/mmap_file/mod.rs index 2d61fa9901..660ac82483 100644 --- a/crates/papyrus_storage/src/mmap_file/mod.rs +++ b/crates/papyrus_storage/src/mmap_file/mod.rs @@ -16,7 +16,7 @@ use std::result; use std::sync::{Arc, Mutex}; use memmap2::{MmapMut, MmapOptions}; -use papyrus_config::dumping::{ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; #[cfg(test)] use papyrus_test_utils::GetTestInstance; @@ -28,7 +28,7 @@ use tracing::{debug, instrument, trace}; use validator::{Validate, ValidationError}; use crate::db::serialization::{StorageSerde, StorageSerdeError, ValueSerde}; -use crate::db::{TransactionKind, RO, RW}; +use crate::db::{RO, RW, TransactionKind}; type MmapFileResult = result::Result; diff --git a/crates/papyrus_storage/src/serialization/serializers.rs b/crates/papyrus_storage/src/serialization/serializers.rs index 57d3bf8384..5fe439f36d 100644 --- a/crates/papyrus_storage/src/serialization/serializers.rs +++ b/crates/papyrus_storage/src/serialization/serializers.rs @@ -6,10 +6,10 @@ use std::sync::Arc; use byteorder::BigEndian; use cairo_lang_casm::hints::Hint; +use cairo_lang_starknet_classes::NestedIntList; use cairo_lang_starknet_classes::casm_contract_class::{ CasmContractClass, CasmContractEntryPoint, CasmContractEntryPoints, }; -use cairo_lang_starknet_classes::NestedIntList; use cairo_lang_utils::bigint::BigUintAsHex; use indexmap::IndexMap; use integer_encoding::*; @@ -58,17 +58,17 @@ use starknet_api::transaction::{ use starknet_types_core::felt::Felt; use tracing::warn; -use crate::body::events::EventIndex; use crate::body::TransactionIndex; +use crate::body::events::EventIndex; use crate::compression_utils::{ - compress, decompress, decompress_from_reader, serialize_and_compress, IsCompressed, + IsCompressed, compress, decompress, decompress_from_reader, serialize_and_compress, }; use crate::db::serialization::{StorageSerde, StorageSerdeError}; use crate::db::table_types::NoValue; use crate::header::StorageBlockHeader; use crate::mmap_file::LocationInFile; #[cfg(test)] -use crate::serialization::serializers_test::{create_storage_serde_test, StorageSerdeTest}; +use crate::serialization::serializers_test::{StorageSerdeTest, create_storage_serde_test}; use crate::state::data::IndexedDeprecatedContractClass; use crate::version::Version; use crate::{MarkerKind, OffsetKind, TransactionMetadata}; diff --git a/crates/papyrus_storage/src/serialization/serializers_test.rs b/crates/papyrus_storage/src/serialization/serializers_test.rs index f39ba4414e..ad3b5be4c6 100644 --- a/crates/papyrus_storage/src/serialization/serializers_test.rs +++ b/crates/papyrus_storage/src/serialization/serializers_test.rs @@ -6,7 +6,7 @@ use std::path::Path; use cairo_lang_casm::hints::CoreHintBase; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use pretty_assertions::assert_eq; use starknet_api::block::BlockNumber; use starknet_api::core::ContractAddress; diff --git a/crates/papyrus_storage/src/state/mod.rs b/crates/papyrus_storage/src/state/mod.rs index b184d3a49f..30558160d7 100644 --- a/crates/papyrus_storage/src/state/mod.rs +++ b/crates/papyrus_storage/src/state/mod.rs @@ -68,9 +68,9 @@ use tracing::debug; use crate::db::serialization::{NoVersionValueWrapper, VersionZeroWrapper}; use crate::db::table_types::{CommonPrefix, DbCursorTrait, SimpleTable, Table}; -use crate::db::{DbTransaction, TableHandle, TransactionKind, RW}; +use crate::db::{DbTransaction, RW, TableHandle, TransactionKind}; #[cfg(feature = "document_calls")] -use crate::document_calls::{add_query, StorageQuery}; +use crate::document_calls::{StorageQuery, add_query}; use crate::mmap_file::LocationInFile; use crate::state::data::IndexedDeprecatedContractClass; use crate::{ diff --git a/crates/papyrus_storage/src/state/state_test.rs b/crates/papyrus_storage/src/state/state_test.rs index cd0eac4e4e..217572ae9b 100644 --- a/crates/papyrus_storage/src/state/state_test.rs +++ b/crates/papyrus_storage/src/state/state_test.rs @@ -1,6 +1,6 @@ use assert_matches::assert_matches; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; -use indexmap::{indexmap, IndexMap}; +use indexmap::{IndexMap, indexmap}; use papyrus_test_utils::get_test_state_diff; use pretty_assertions::assert_eq; use starknet_api::block::BlockNumber; @@ -11,11 +11,11 @@ use starknet_api::state::{SierraContractClass, StateNumber, ThinStateDiff}; use starknet_api::{class_hash, contract_address, felt, storage_key}; use starknet_types_core::felt::Felt; +use crate::StorageWriter; use crate::class::{ClassStorageReader, ClassStorageWriter}; use crate::compiled_class::{CasmStorageReader, CasmStorageWriter}; use crate::state::{StateStorageReader, StateStorageWriter}; use crate::test_utils::get_test_storage; -use crate::StorageWriter; #[test] fn get_class_definition_at() { @@ -44,11 +44,10 @@ fn get_class_definition_at() { txn = txn.append_state_diff(BlockNumber(0), diff0).unwrap(); txn = txn.append_state_diff(BlockNumber(1), diff1).unwrap(); txn = txn - .append_classes( - BlockNumber(0), - &[(nc0, &new_class)], - &[(dc0, &dep_class), (dc1, &dep_class)], - ) + .append_classes(BlockNumber(0), &[(nc0, &new_class)], &[ + (dc0, &dep_class), + (dc1, &dep_class), + ]) .unwrap(); txn = txn.append_classes(BlockNumber(1), &[(nc1, &new_class)], &[(dc0, &dep_class)]).unwrap(); txn.commit().unwrap(); @@ -272,14 +271,11 @@ fn test_get_class_after_append_thin_state_diff() { let mut txn = writer.begin_rw_txn().unwrap(); // Append an empty state diff. txn = txn - .append_state_diff( - BlockNumber(0), - ThinStateDiff { - declared_classes: indexmap! { CLASS_HASH => CompiledClassHash::default() }, - deprecated_declared_classes: vec![DEPRECATED_CLASS_HASH], - ..Default::default() - }, - ) + .append_state_diff(BlockNumber(0), ThinStateDiff { + declared_classes: indexmap! { CLASS_HASH => CompiledClassHash::default() }, + deprecated_declared_classes: vec![DEPRECATED_CLASS_HASH], + ..Default::default() + }) .unwrap(); assert_eq!(txn.get_class_marker().unwrap(), BlockNumber(0)); @@ -291,10 +287,12 @@ fn test_get_class_after_append_thin_state_diff() { Some(BlockNumber(0)) ); assert!(state_reader.get_class_definition_at(state_number, &CLASS_HASH).unwrap().is_none()); - assert!(state_reader - .get_deprecated_class_definition_at(state_number, &DEPRECATED_CLASS_HASH) - .unwrap() - .is_none()); + assert!( + state_reader + .get_deprecated_class_definition_at(state_number, &DEPRECATED_CLASS_HASH) + .unwrap() + .is_none() + ); } #[test] @@ -492,11 +490,10 @@ fn revert_state() { .collect::>(), ) .unwrap() - .append_classes( - BlockNumber(1), - &[(class2, &SierraContractClass::default())], - &[(class1, &DeprecatedContractClass::default())], - ) + .append_classes(BlockNumber(1), &[(class2, &SierraContractClass::default())], &[( + class1, + &DeprecatedContractClass::default(), + )]) .unwrap() .append_casm(&class2, &compiled_class2) .unwrap() @@ -527,18 +524,15 @@ fn revert_state() { let expected_deleted_deprecated_classes = IndexMap::from([(class1, DeprecatedContractClass::default())]); let expected_deleted_classes = IndexMap::from([(class2, SierraContractClass::default())]); - let expected_deleted_compiled_classes = IndexMap::from([( - class2, - CasmContractClass { - prime: Default::default(), - compiler_version: Default::default(), - bytecode: Default::default(), - bytecode_segment_lengths: Default::default(), - hints: Default::default(), - pythonic_hints: Default::default(), - entry_points_by_type: Default::default(), - }, - )]); + let expected_deleted_compiled_classes = IndexMap::from([(class2, CasmContractClass { + prime: Default::default(), + compiler_version: Default::default(), + bytecode: Default::default(), + bytecode_segment_lengths: Default::default(), + hints: Default::default(), + pythonic_hints: Default::default(), + entry_points_by_type: Default::default(), + })]); assert_matches!( deleted_data, Some((thin_state_diff, class_definitions, deprecated_class_definitions, compiled_classes)) @@ -726,11 +720,10 @@ fn declare_revert_declare_scenario() { .unwrap() .append_state_diff(BlockNumber(0), diff0.clone()) .unwrap() - .append_classes( - BlockNumber(0), - &[(class_hash, &class)], - &[(deprecated_class_hash, &deprecated_class)], - ) + .append_classes(BlockNumber(0), &[(class_hash, &class)], &[( + deprecated_class_hash, + &deprecated_class, + )]) .unwrap() .commit() .unwrap(); @@ -740,10 +733,12 @@ fn declare_revert_declare_scenario() { let txn = reader.begin_ro_txn().unwrap(); let state_reader = txn.get_state_reader().unwrap(); assert!(state_reader.get_class_definition_at(state_number, &class_hash).unwrap().is_some()); - assert!(state_reader - .get_deprecated_class_definition_at(state_number, &deprecated_class_hash) - .unwrap() - .is_some()); + assert!( + state_reader + .get_deprecated_class_definition_at(state_number, &deprecated_class_hash) + .unwrap() + .is_some() + ); // Revert the block and assert that the classes are no longer declared. let (txn, _) = writer.begin_rw_txn().unwrap().revert_state_diff(BlockNumber(0)).unwrap(); @@ -751,10 +746,12 @@ fn declare_revert_declare_scenario() { let txn = reader.begin_ro_txn().unwrap(); let state_reader = txn.get_state_reader().unwrap(); assert!(state_reader.get_class_definition_at(state_number, &class_hash).unwrap().is_none()); - assert!(state_reader - .get_deprecated_class_definition_at(state_number, &deprecated_class_hash) - .unwrap() - .is_none()); + assert!( + state_reader + .get_deprecated_class_definition_at(state_number, &deprecated_class_hash) + .unwrap() + .is_none() + ); // Re-declaring reverted classes should be possible. writer @@ -762,11 +759,10 @@ fn declare_revert_declare_scenario() { .unwrap() .append_state_diff(BlockNumber(0), diff0.clone()) .unwrap() - .append_classes( - BlockNumber(0), - &[(class_hash, &class)], - &[(deprecated_class_hash, &deprecated_class)], - ) + .append_classes(BlockNumber(0), &[(class_hash, &class)], &[( + deprecated_class_hash, + &deprecated_class, + )]) .unwrap() .commit() .unwrap(); @@ -776,8 +772,10 @@ fn declare_revert_declare_scenario() { let txn = reader.begin_ro_txn().unwrap(); let state_reader = txn.get_state_reader().unwrap(); assert!(state_reader.get_class_definition_at(state_number, &class_hash).unwrap().is_some()); - assert!(state_reader - .get_deprecated_class_definition_at(state_number, &deprecated_class_hash) - .unwrap() - .is_some()); + assert!( + state_reader + .get_deprecated_class_definition_at(state_number, &deprecated_class_hash) + .unwrap() + .is_some() + ); } diff --git a/crates/papyrus_storage/src/test_instances.rs b/crates/papyrus_storage/src/test_instances.rs index 3ba2956242..fd77b12d34 100644 --- a/crates/papyrus_storage/src/test_instances.rs +++ b/crates/papyrus_storage/src/test_instances.rs @@ -1,4 +1,4 @@ -use papyrus_test_utils::{auto_impl_get_test_instance, get_number_of_variants, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, auto_impl_get_test_instance, get_number_of_variants}; use starknet_api::block::{BlockHash, BlockNumber, BlockTimestamp, GasPricePerToken}; use starknet_api::core::{ EventCommitment, GlobalRoot, ReceiptCommitment, SequencerContractAddress, StateDiffCommitment, diff --git a/crates/papyrus_storage/src/test_utils.rs b/crates/papyrus_storage/src/test_utils.rs index 1ea60bed92..99e17f7a39 100644 --- a/crates/papyrus_storage/src/test_utils.rs +++ b/crates/papyrus_storage/src/test_utils.rs @@ -4,11 +4,11 @@ use std::sync::LazyLock; use starknet_api::core::ChainId; -use tempfile::{tempdir, TempDir}; +use tempfile::{TempDir, tempdir}; use crate::db::DbConfig; use crate::mmap_file::MmapFileConfig; -use crate::{open_storage, StorageConfig, StorageReader, StorageScope, StorageWriter}; +use crate::{StorageConfig, StorageReader, StorageScope, StorageWriter, open_storage}; /// A chain id for tests. pub static CHAIN_ID_FOR_TESTS: LazyLock = diff --git a/crates/papyrus_storage/src/version.rs b/crates/papyrus_storage/src/version.rs index d70a45741a..a1a5b1e642 100644 --- a/crates/papyrus_storage/src/version.rs +++ b/crates/papyrus_storage/src/version.rs @@ -3,7 +3,7 @@ mod version_test; use crate::db::table_types::Table; -use crate::db::{TransactionKind, RW}; +use crate::db::{RW, TransactionKind}; use crate::{StorageError, StorageResult, StorageTxn}; const VERSION_STATE_KEY: &str = "storage_version_state"; diff --git a/crates/papyrus_storage/src/version_test.rs b/crates/papyrus_storage/src/version_test.rs index 6a879af1cc..b41c309116 100644 --- a/crates/papyrus_storage/src/version_test.rs +++ b/crates/papyrus_storage/src/version_test.rs @@ -7,12 +7,12 @@ use crate::test_utils::{ get_test_storage, get_test_storage_by_scope, get_test_storage_with_config_by_scope, }; use crate::version::{ - StorageVersionError, Version, VersionStorageReader, VersionStorageWriter, VERSION_BLOCKS_KEY, - VERSION_STATE_KEY, + StorageVersionError, VERSION_BLOCKS_KEY, VERSION_STATE_KEY, Version, VersionStorageReader, + VersionStorageWriter, }; use crate::{ - open_storage, set_version_if_needed, verify_storage_version, StorageError, StorageScope, - StorageWriter, STORAGE_VERSION_BLOCKS, STORAGE_VERSION_STATE, + STORAGE_VERSION_BLOCKS, STORAGE_VERSION_STATE, StorageError, StorageScope, StorageWriter, + open_storage, set_version_if_needed, verify_storage_version, }; // TODO: Add this test for set_blocks_version or combine the logic. @@ -81,16 +81,14 @@ fn version_migration() { get_test_storage_with_config_by_scope(StorageScope::FullArchive); // Set the storage version on a lower minor version. - change_storage_version( - &mut writer, - VERSION_STATE_KEY, - &Version { major: STORAGE_VERSION_STATE.major, minor: 0 }, - ); - change_storage_version( - &mut writer, - VERSION_BLOCKS_KEY, - &Version { major: STORAGE_VERSION_BLOCKS.major, minor: 0 }, - ); + change_storage_version(&mut writer, VERSION_STATE_KEY, &Version { + major: STORAGE_VERSION_STATE.major, + minor: 0, + }); + change_storage_version(&mut writer, VERSION_BLOCKS_KEY, &Version { + major: STORAGE_VERSION_BLOCKS.major, + minor: 0, + }); drop(reader); drop(writer); diff --git a/crates/papyrus_sync/src/lib.rs b/crates/papyrus_sync/src/lib.rs index c9553823cf..57adb84649 100644 --- a/crates/papyrus_sync/src/lib.rs +++ b/crates/papyrus_sync/src/lib.rs @@ -16,12 +16,12 @@ use std::time::Duration; use async_stream::try_stream; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; use chrono::{TimeZone, Utc}; -use futures_util::{pin_mut, select, Stream, StreamExt}; +use futures_util::{Stream, StreamExt, pin_mut, select}; use indexmap::IndexMap; use papyrus_common::metrics as papyrus_metrics; use papyrus_common::pending_classes::PendingClasses; use papyrus_config::converters::deserialize_seconds_to_duration; -use papyrus_config::dumping::{ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use papyrus_proc_macros::latency_histogram; use papyrus_storage::base_layer::{BaseLayerStorageReader, BaseLayerStorageWriter}; @@ -227,10 +227,10 @@ pub enum SyncEvent { } impl< - TCentralSource: CentralSourceTrait + Sync + Send + 'static, - TPendingSource: PendingSourceTrait + Sync + Send + 'static, - TBaseLayerSource: BaseLayerSourceTrait + Sync + Send, - > GenericStateSync + TCentralSource: CentralSourceTrait + Sync + Send + 'static, + TPendingSource: PendingSourceTrait + Sync + Send + 'static, + TBaseLayerSource: BaseLayerSourceTrait + Sync + Send, +> GenericStateSync { pub async fn run(mut self) -> StateSyncResult { info!("State sync started."); diff --git a/crates/papyrus_sync/src/pending_sync.rs b/crates/papyrus_sync/src/pending_sync.rs index 0a6afbce3d..de858215c5 100644 --- a/crates/papyrus_sync/src/pending_sync.rs +++ b/crates/papyrus_sync/src/pending_sync.rs @@ -5,8 +5,8 @@ use std::time::Duration; use futures::stream::FuturesUnordered; use futures_util::{FutureExt, StreamExt}; use papyrus_common::pending_classes::{PendingClasses, PendingClassesTrait}; -use papyrus_storage::header::HeaderStorageReader; use papyrus_storage::StorageReader; +use papyrus_storage::header::HeaderStorageReader; use starknet_api::block::{BlockHash, BlockNumber}; use starknet_api::core::ClassHash; use starknet_client::reader::{DeclaredClassHashEntry, PendingData}; @@ -14,9 +14,9 @@ use starknet_types_core::felt::Felt; use tokio::sync::RwLock; use tracing::{debug, trace}; +use crate::StateSyncError; use crate::sources::central::CentralSourceTrait; use crate::sources::pending::PendingSourceTrait; -use crate::StateSyncError; // Update the pending data and return when a new block is discovered. pub(crate) async fn sync_pending_data< diff --git a/crates/papyrus_sync/src/sources/base_layer.rs b/crates/papyrus_sync/src/sources/base_layer.rs index c76b8588c0..81954aaec2 100644 --- a/crates/papyrus_sync/src/sources/base_layer.rs +++ b/crates/papyrus_sync/src/sources/base_layer.rs @@ -1,8 +1,8 @@ use async_trait::async_trait; #[cfg(test)] use mockall::automock; -use papyrus_base_layer::ethereum_base_layer_contract::EthereumBaseLayerContract; use papyrus_base_layer::BaseLayerContract; +use papyrus_base_layer::ethereum_base_layer_contract::EthereumBaseLayerContract; use starknet_api::block::{BlockHash, BlockNumber}; pub type EthereumBaseLayerSource = EthereumBaseLayerContract; @@ -29,9 +29,9 @@ pub trait BaseLayerSourceTrait { #[async_trait] impl< - Error: std::error::Error + 'static + Sync + Send, - BaseLayerSource: BaseLayerContract + Sync + Send, - > BaseLayerSourceTrait for BaseLayerSource + Error: std::error::Error + 'static + Sync + Send, + BaseLayerSource: BaseLayerContract + Sync + Send, +> BaseLayerSourceTrait for BaseLayerSource { async fn latest_proved_block( &self, diff --git a/crates/papyrus_sync/src/sources/central.rs b/crates/papyrus_sync/src/sources/central.rs index ebd6385e16..1b8b171229 100644 --- a/crates/papyrus_sync/src/sources/central.rs +++ b/crates/papyrus_sync/src/sources/central.rs @@ -19,17 +19,17 @@ use lru::LruCache; use mockall::automock; use papyrus_common::pending_classes::ApiContractClass; use papyrus_config::converters::{deserialize_optional_map, serialize_optional_map}; -use papyrus_config::dumping::{append_sub_config_name, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use papyrus_storage::state::StateStorageReader; use papyrus_storage::{StorageError, StorageReader}; use serde::{Deserialize, Serialize}; +use starknet_api::StarknetApiError; use starknet_api::block::{Block, BlockHash, BlockHashAndNumber, BlockNumber, BlockSignature}; use starknet_api::core::{ClassHash, CompiledClassHash, SequencerPublicKey}; use starknet_api::crypto::utils::Signature; use starknet_api::deprecated_contract_class::ContractClass as DeprecatedContractClass; use starknet_api::state::StateDiff; -use starknet_api::StarknetApiError; use starknet_client::reader::{ BlockSignatureData, ReaderClientError, StarknetFeederGatewayClient, StarknetReader, }; diff --git a/crates/papyrus_sync/src/sources/central/state_update_stream.rs b/crates/papyrus_sync/src/sources/central/state_update_stream.rs index db811567c6..82d5b72391 100644 --- a/crates/papyrus_sync/src/sources/central/state_update_stream.rs +++ b/crates/papyrus_sync/src/sources/central/state_update_stream.rs @@ -7,8 +7,8 @@ use futures_util::stream::FuturesOrdered; use futures_util::{Future, Stream, StreamExt}; use indexmap::IndexMap; use lru::LruCache; -use papyrus_storage::state::StateStorageReader; use papyrus_storage::StorageReader; +use papyrus_storage::state::StateStorageReader; use starknet_api::block::BlockNumber; use starknet_api::core::ClassHash; use starknet_api::state::{StateDiff, StateNumber}; diff --git a/crates/papyrus_sync/src/sources/central_test.rs b/crates/papyrus_sync/src/sources/central_test.rs index 620e2ff3bb..56f289678f 100644 --- a/crates/papyrus_sync/src/sources/central_test.rs +++ b/crates/papyrus_sync/src/sources/central_test.rs @@ -4,7 +4,7 @@ use std::sync::{Arc, Mutex}; use assert_matches::assert_matches; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; use futures_util::pin_mut; -use indexmap::{indexmap, IndexMap}; +use indexmap::{IndexMap, indexmap}; use lru::LruCache; use mockall::predicate; use papyrus_storage::class::ClassStorageWriter; @@ -19,17 +19,17 @@ use starknet_api::deprecated_contract_class::ContractClass as DeprecatedContract use starknet_api::hash::StarkHash; use starknet_api::state::{SierraContractClass as sn_api_ContractClass, ThinStateDiff}; use starknet_api::{class_hash, contract_address, felt, storage_key}; +use starknet_client::ClientError; use starknet_client::reader::objects::block::BlockPostV0_13_1; use starknet_client::reader::{ Block, BlockSignatureData, ContractClass, DeclaredClassHashEntry, DeployedContract, GenericContractClass, MockStarknetReader, ReaderClientError, ReplacedClass, StateUpdate, StorageEntry, }; -use starknet_client::ClientError; use tokio_stream::StreamExt; -use super::state_update_stream::StateUpdateStreamConfig; use super::ApiContractClass; +use super::state_update_stream::StateUpdateStreamConfig; use crate::sources::central::{CentralError, CentralSourceTrait, GenericCentralSource}; const TEST_CONCURRENT_REQUESTS: usize = 300; @@ -452,35 +452,29 @@ async fn stream_compiled_classes() { writer .begin_rw_txn() .unwrap() - .append_state_diff( - BlockNumber(0), - ThinStateDiff { - deployed_contracts: indexmap! {}, - storage_diffs: indexmap! {}, - declared_classes: indexmap! { - class_hash!("0x0") => CompiledClassHash(felt!("0x0")), - class_hash!("0x1") => CompiledClassHash(felt!("0x1")), - }, - deprecated_declared_classes: vec![], - nonces: indexmap! {}, - replaced_classes: indexmap! {}, + .append_state_diff(BlockNumber(0), ThinStateDiff { + deployed_contracts: indexmap! {}, + storage_diffs: indexmap! {}, + declared_classes: indexmap! { + class_hash!("0x0") => CompiledClassHash(felt!("0x0")), + class_hash!("0x1") => CompiledClassHash(felt!("0x1")), }, - ) + deprecated_declared_classes: vec![], + nonces: indexmap! {}, + replaced_classes: indexmap! {}, + }) .unwrap() - .append_state_diff( - BlockNumber(1), - ThinStateDiff { - deployed_contracts: indexmap! {}, - storage_diffs: indexmap! {}, - declared_classes: indexmap! { - class_hash!("0x2") => CompiledClassHash(felt!("0x2")), - class_hash!("0x3") => CompiledClassHash(felt!("0x3")), - }, - deprecated_declared_classes: vec![], - nonces: indexmap! {}, - replaced_classes: indexmap! {}, + .append_state_diff(BlockNumber(1), ThinStateDiff { + deployed_contracts: indexmap! {}, + storage_diffs: indexmap! {}, + declared_classes: indexmap! { + class_hash!("0x2") => CompiledClassHash(felt!("0x2")), + class_hash!("0x3") => CompiledClassHash(felt!("0x3")), }, - ) + deprecated_declared_classes: vec![], + nonces: indexmap! {}, + replaced_classes: indexmap! {}, + }) .unwrap() .append_classes( BlockNumber(0), diff --git a/crates/papyrus_sync/src/sources/pending.rs b/crates/papyrus_sync/src/sources/pending.rs index 53b5cf53b1..ef23eae471 100644 --- a/crates/papyrus_sync/src/sources/pending.rs +++ b/crates/papyrus_sync/src/sources/pending.rs @@ -7,10 +7,10 @@ use std::sync::Arc; use async_trait::async_trait; #[cfg(test)] use mockall::automock; +use starknet_client::ClientCreationError; use starknet_client::reader::{ PendingData, ReaderClientError, StarknetFeederGatewayClient, StarknetReader, }; -use starknet_client::ClientCreationError; // TODO(dvir): add pending config. use super::central::CentralSourceConfig; diff --git a/crates/papyrus_sync/src/sync_test.rs b/crates/papyrus_sync/src/sync_test.rs index 8e45bd2080..ee34915524 100644 --- a/crates/papyrus_sync/src/sync_test.rs +++ b/crates/papyrus_sync/src/sync_test.rs @@ -10,7 +10,7 @@ use papyrus_storage::base_layer::BaseLayerStorageReader; use papyrus_storage::header::HeaderStorageWriter; use papyrus_storage::test_utils::get_test_storage; use papyrus_storage::{StorageReader, StorageWriter}; -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use pretty_assertions::assert_eq; use starknet_api::block::{BlockHash, BlockHeader, BlockHeaderWithoutHash, BlockNumber}; use starknet_api::core::{ClassHash, CompiledClassHash, Nonce}; @@ -30,8 +30,8 @@ use crate::sources::base_layer::MockBaseLayerSourceTrait; use crate::sources::central::MockCentralSourceTrait; use crate::sources::pending::MockPendingSourceTrait; use crate::{ - sort_state_diff, stream_new_base_layer_block, sync_pending_data, GenericStateSync, - StateSyncError, SyncConfig, SyncEvent, GENESIS_HASH, + GENESIS_HASH, GenericStateSync, StateSyncError, SyncConfig, SyncEvent, sort_state_diff, + stream_new_base_layer_block, sync_pending_data, }; // TODO(anatg): Add a test to check that the sync calls the sort_state_diff function @@ -362,18 +362,15 @@ async fn pending_sync_new_data_has_more_advanced_hash_and_less_transactions() { writer .begin_rw_txn() .unwrap() - .append_header( - BlockNumber(0), - &BlockHeader { - block_hash: FIRST_BLOCK_HASH, - block_header_without_hash: BlockHeaderWithoutHash { - parent_hash: genesis_hash, - block_number: BlockNumber(0), - ..Default::default() - }, + .append_header(BlockNumber(0), &BlockHeader { + block_hash: FIRST_BLOCK_HASH, + block_header_without_hash: BlockHeaderWithoutHash { + parent_hash: genesis_hash, + block_number: BlockNumber(0), ..Default::default() }, - ) + ..Default::default() + }) .unwrap() .commit() .unwrap(); @@ -479,18 +476,15 @@ async fn pending_sync_doesnt_stop_when_data_has_block_hash_field_with_the_same_h writer .begin_rw_txn() .unwrap() - .append_header( - BlockNumber(0), - &BlockHeader { - block_hash: FIRST_BLOCK_HASH, - block_header_without_hash: BlockHeaderWithoutHash { - parent_hash: genesis_hash, - block_number: BlockNumber(0), - ..Default::default() - }, + .append_header(BlockNumber(0), &BlockHeader { + block_hash: FIRST_BLOCK_HASH, + block_header_without_hash: BlockHeaderWithoutHash { + parent_hash: genesis_hash, + block_number: BlockNumber(0), ..Default::default() }, - ) + ..Default::default() + }) .unwrap() .commit() .unwrap(); @@ -547,8 +541,8 @@ async fn pending_sync_doesnt_stop_when_data_has_block_hash_field_with_the_same_h } #[tokio::test] -async fn pending_sync_updates_when_data_has_block_hash_field_with_the_same_hash_and_more_transactions( -) { +async fn pending_sync_updates_when_data_has_block_hash_field_with_the_same_hash_and_more_transactions() + { const FIRST_BLOCK_HASH: BlockHash = BlockHash(StarkHash::ONE); let genesis_hash = BlockHash(felt!(GENESIS_HASH)); // Storage with one block header. @@ -556,18 +550,15 @@ async fn pending_sync_updates_when_data_has_block_hash_field_with_the_same_hash_ writer .begin_rw_txn() .unwrap() - .append_header( - BlockNumber(0), - &BlockHeader { - block_hash: FIRST_BLOCK_HASH, - block_header_without_hash: BlockHeaderWithoutHash { - parent_hash: genesis_hash, - block_number: BlockNumber(0), - ..Default::default() - }, + .append_header(BlockNumber(0), &BlockHeader { + block_hash: FIRST_BLOCK_HASH, + block_header_without_hash: BlockHeaderWithoutHash { + parent_hash: genesis_hash, + block_number: BlockNumber(0), ..Default::default() }, - ) + ..Default::default() + }) .unwrap() .commit() .unwrap(); @@ -712,18 +703,15 @@ async fn pending_sync_classes_are_cleaned_on_first_pending_data_from_latest_bloc writer .begin_rw_txn() .unwrap() - .append_header( - BlockNumber(0), - &BlockHeader { - block_hash: FIRST_BLOCK_HASH, - block_header_without_hash: BlockHeaderWithoutHash { - parent_hash: genesis_hash, - block_number: BlockNumber(0), - ..Default::default() - }, + .append_header(BlockNumber(0), &BlockHeader { + block_hash: FIRST_BLOCK_HASH, + block_header_without_hash: BlockHeaderWithoutHash { + parent_hash: genesis_hash, + block_number: BlockNumber(0), ..Default::default() }, - ) + ..Default::default() + }) .unwrap() .commit() .unwrap(); diff --git a/crates/papyrus_test_utils/src/lib.rs b/crates/papyrus_test_utils/src/lib.rs index a3808b00b4..d098903f75 100644 --- a/crates/papyrus_test_utils/src/lib.rs +++ b/crates/papyrus_test_utils/src/lib.rs @@ -15,10 +15,10 @@ use cairo_lang_casm::hints::{CoreHint, CoreHintBase, Hint}; use cairo_lang_casm::operand::{ BinOpOperand, CellRef, DerefOrImmediate, Operation, Register, ResOperand, }; +use cairo_lang_starknet_classes::NestedIntList; use cairo_lang_starknet_classes::casm_contract_class::{ CasmContractClass, CasmContractEntryPoint, CasmContractEntryPoints, }; -use cairo_lang_starknet_classes::NestedIntList; use cairo_lang_utils::bigint::BigUintAsHex; use indexmap::IndexMap; use num_bigint::BigUint; diff --git a/crates/sequencing/papyrus_consensus/src/config.rs b/crates/sequencing/papyrus_consensus/src/config.rs index ce5f6e3adf..c8720e4fcf 100644 --- a/crates/sequencing/papyrus_consensus/src/config.rs +++ b/crates/sequencing/papyrus_consensus/src/config.rs @@ -8,7 +8,7 @@ use std::time::Duration; use papyrus_config::converters::{ deserialize_float_seconds_to_duration, deserialize_seconds_to_duration, }; -use papyrus_config::dumping::{append_sub_config_name, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use papyrus_network::NetworkConfig; use serde::{Deserialize, Serialize}; diff --git a/crates/sequencing/papyrus_consensus/src/manager_test.rs b/crates/sequencing/papyrus_consensus/src/manager_test.rs index 026f650c25..c22034c7c9 100644 --- a/crates/sequencing/papyrus_consensus/src/manager_test.rs +++ b/crates/sequencing/papyrus_consensus/src/manager_test.rs @@ -2,27 +2,27 @@ use std::time::Duration; use std::vec; use async_trait::async_trait; -use futures::channel::{mpsc, oneshot}; use futures::SinkExt; +use futures::channel::{mpsc, oneshot}; use lazy_static::lazy_static; use mockall::mock; use mockall::predicate::eq; use papyrus_network::network_manager::test_utils::{ - mock_register_broadcast_topic, MockBroadcastedMessagesSender, TestSubscriberChannels, + MockBroadcastedMessagesSender, TestSubscriberChannels, mock_register_broadcast_topic, }; use papyrus_network_types::network_types::BroadcastedMessageMetadata; use papyrus_protobuf::consensus::{ ConsensusMessage, ProposalFin, ProposalInit, ProposalPart, Vote, }; -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use starknet_api::block::{BlockHash, BlockNumber}; use starknet_types_core::felt::Felt; -use super::{run_consensus, MultiHeightManager}; +use super::{MultiHeightManager, run_consensus}; use crate::config::TimeoutsConfig; use crate::test_utils::{precommit, prevote, proposal_init}; use crate::types::{ - ConsensusContext, ConsensusError, ProposalContentId, Round, ValidatorId, DEFAULT_VALIDATOR_ID, + ConsensusContext, ConsensusError, DEFAULT_VALIDATOR_ID, ProposalContentId, Round, ValidatorId, }; lazy_static! { @@ -102,10 +102,9 @@ fn expect_validate_proposal(context: &mut MockTestContext, block_hash: Felt) { .return_once(move |_, _, _, _, _| { let (block_sender, block_receiver) = oneshot::channel(); block_sender - .send(( - BlockHash(block_hash), - ProposalFin { proposal_content_id: BlockHash(block_hash) }, - )) + .send((BlockHash(block_hash), ProposalFin { + proposal_content_id: BlockHash(block_hash), + })) .unwrap(); block_receiver }) @@ -123,24 +122,18 @@ async fn manager_multiple_heights_unordered() { mpsc::channel(CHANNEL_SIZE); // Send messages for height 2 followed by those for height 1. - send_proposal( - &mut proposal_receiver_sender, - vec![ - ProposalPart::Init(proposal_init(2, 0, *PROPOSER_ID)), - ProposalPart::Fin(ProposalFin { proposal_content_id: BlockHash(Felt::TWO) }), - ], - ) + send_proposal(&mut proposal_receiver_sender, vec![ + ProposalPart::Init(proposal_init(2, 0, *PROPOSER_ID)), + ProposalPart::Fin(ProposalFin { proposal_content_id: BlockHash(Felt::TWO) }), + ]) .await; send(&mut sender, prevote(Some(Felt::TWO), 2, 0, *PROPOSER_ID)).await; send(&mut sender, precommit(Some(Felt::TWO), 2, 0, *PROPOSER_ID)).await; - send_proposal( - &mut proposal_receiver_sender, - vec![ - ProposalPart::Init(proposal_init(1, 0, *PROPOSER_ID)), - ProposalPart::Fin(ProposalFin { proposal_content_id: BlockHash(Felt::ONE) }), - ], - ) + send_proposal(&mut proposal_receiver_sender, vec![ + ProposalPart::Init(proposal_init(1, 0, *PROPOSER_ID)), + ProposalPart::Fin(ProposalFin { proposal_content_id: BlockHash(Felt::ONE) }), + ]) .await; send(&mut sender, prevote(Some(Felt::ONE), 1, 0, *PROPOSER_ID)).await; send(&mut sender, precommit(Some(Felt::ONE), 1, 0, *PROPOSER_ID)).await; @@ -204,10 +197,11 @@ async fn run_consensus_sync() { }); // Send messages for height 2. - send_proposal( - &mut proposal_receiver_sender, - vec![ProposalPart::Init(proposal_init(2, 0, *PROPOSER_ID))], - ) + send_proposal(&mut proposal_receiver_sender, vec![ProposalPart::Init(proposal_init( + 2, + 0, + *PROPOSER_ID, + ))]) .await; let TestSubscriberChannels { mock_network, subscriber_channels } = mock_register_broadcast_topic().unwrap(); @@ -295,10 +289,11 @@ async fn run_consensus_sync_cancellation_safety() { let mut network_sender = mock_network.broadcasted_messages_sender; // Send a proposal for height 1. - send_proposal( - &mut proposal_receiver_sender, - vec![ProposalPart::Init(proposal_init(1, 0, *PROPOSER_ID))], - ) + send_proposal(&mut proposal_receiver_sender, vec![ProposalPart::Init(proposal_init( + 1, + 0, + *PROPOSER_ID, + ))]) .await; proposal_handled_rx.await.unwrap(); @@ -327,10 +322,11 @@ async fn test_timeouts() { let (mut proposal_receiver_sender, mut proposal_receiver_receiver) = mpsc::channel(CHANNEL_SIZE); - send_proposal( - &mut proposal_receiver_sender, - vec![ProposalPart::Init(proposal_init(1, 0, *PROPOSER_ID))], - ) + send_proposal(&mut proposal_receiver_sender, vec![ProposalPart::Init(proposal_init( + 1, + 0, + *PROPOSER_ID, + ))]) .await; send(&mut sender, prevote(None, 1, 0, *VALIDATOR_ID_2)).await; send(&mut sender, prevote(None, 1, 0, *VALIDATOR_ID_3)).await; @@ -382,10 +378,11 @@ async fn test_timeouts() { timeout_receive.await.unwrap(); // Show that after the timeout is triggered we can still precommit in favor of the block and // reach a decision. - send_proposal( - &mut proposal_receiver_sender, - vec![ProposalPart::Init(proposal_init(1, 1, *PROPOSER_ID))], - ) + send_proposal(&mut proposal_receiver_sender, vec![ProposalPart::Init(proposal_init( + 1, + 1, + *PROPOSER_ID, + ))]) .await; send(&mut sender, prevote(Some(Felt::ONE), 1, 1, *PROPOSER_ID)).await; send(&mut sender, prevote(Some(Felt::ONE), 1, 1, *VALIDATOR_ID_2)).await; diff --git a/crates/sequencing/papyrus_consensus/src/simulation_network_receiver_test.rs b/crates/sequencing/papyrus_consensus/src/simulation_network_receiver_test.rs index f1c041d6eb..909218c5a7 100644 --- a/crates/sequencing/papyrus_consensus/src/simulation_network_receiver_test.rs +++ b/crates/sequencing/papyrus_consensus/src/simulation_network_receiver_test.rs @@ -1,10 +1,10 @@ use futures::{SinkExt, StreamExt}; use papyrus_network::network_manager::test_utils::{ - mock_register_broadcast_topic, TestSubscriberChannels, + TestSubscriberChannels, mock_register_broadcast_topic, }; use papyrus_network_types::network_types::BroadcastedMessageMetadata; use papyrus_protobuf::consensus::ConsensusMessage; -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use test_case::test_case; use super::NetworkReceiver; diff --git a/crates/sequencing/papyrus_consensus/src/single_height_consensus.rs b/crates/sequencing/papyrus_consensus/src/single_height_consensus.rs index 13ccb0152a..ef178a3dfe 100644 --- a/crates/sequencing/papyrus_consensus/src/single_height_consensus.rs +++ b/crates/sequencing/papyrus_consensus/src/single_height_consensus.rs @@ -573,11 +573,7 @@ impl SingleHeightConsensus { .iter() .filter_map(|v| { let vote = self.precommits.get(&(round, *v))?; - if vote.block_hash == Some(proposal_id) { - Some(vote.clone()) - } else { - None - } + if vote.block_hash == Some(proposal_id) { Some(vote.clone()) } else { None } }) .collect(); // TODO(matan): Check actual weights. diff --git a/crates/sequencing/papyrus_consensus/src/single_height_consensus_test.rs b/crates/sequencing/papyrus_consensus/src/single_height_consensus_test.rs index dcbf36f7ac..b4b0a80990 100644 --- a/crates/sequencing/papyrus_consensus/src/single_height_consensus_test.rs +++ b/crates/sequencing/papyrus_consensus/src/single_height_consensus_test.rs @@ -1,5 +1,5 @@ -use futures::channel::{mpsc, oneshot}; use futures::SinkExt; +use futures::channel::{mpsc, oneshot}; use lazy_static::lazy_static; use papyrus_protobuf::consensus::{ConsensusMessage, ProposalFin, ProposalInit}; use starknet_api::block::{BlockHash, BlockNumber}; @@ -11,8 +11,8 @@ use super::SingleHeightConsensus; use crate::config::TimeoutsConfig; use crate::single_height_consensus::{ShcEvent, ShcReturn, ShcTask}; use crate::state_machine::StateMachineEvent; -use crate::test_utils::{precommit, prevote, MockProposalPart, MockTestContext, TestBlock}; -use crate::types::{ConsensusError, ValidatorId, DEFAULT_VALIDATOR_ID}; +use crate::test_utils::{MockProposalPart, MockTestContext, TestBlock, precommit, prevote}; +use crate::types::{ConsensusError, DEFAULT_VALIDATOR_ID, ValidatorId}; lazy_static! { static ref PROPOSER_ID: ValidatorId = DEFAULT_VALIDATOR_ID.into(); @@ -149,10 +149,12 @@ async fn proposer() { panic!("Expected decision"); }; assert_eq!(decision.block, BLOCK.id); - assert!(decision - .precommits - .into_iter() - .all(|item| precommits.contains(&ConsensusMessage::Vote(item)))); + assert!( + decision + .precommits + .into_iter() + .all(|item| precommits.contains(&ConsensusMessage::Vote(item))) + ); } #[test_case(false; "single_proposal")] @@ -228,10 +230,12 @@ async fn validator(repeat_proposal: bool) { panic!("Expected decision"); }; assert_eq!(decision.block, BLOCK.id); - assert!(decision - .precommits - .into_iter() - .all(|item| precommits.contains(&ConsensusMessage::Vote(item)))); + assert!( + decision + .precommits + .into_iter() + .all(|item| precommits.contains(&ConsensusMessage::Vote(item))) + ); } #[test_case(true; "repeat")] @@ -455,8 +459,10 @@ async fn repropose() { panic!("Expected decision"); }; assert_eq!(decision.block, BLOCK.id); - assert!(decision - .precommits - .into_iter() - .all(|item| precommits.contains(&ConsensusMessage::Vote(item)))); + assert!( + decision + .precommits + .into_iter() + .all(|item| precommits.contains(&ConsensusMessage::Vote(item))) + ); } diff --git a/crates/sequencing/papyrus_consensus/src/state_machine_test.rs b/crates/sequencing/papyrus_consensus/src/state_machine_test.rs index 817807aba6..61341eb825 100644 --- a/crates/sequencing/papyrus_consensus/src/state_machine_test.rs +++ b/crates/sequencing/papyrus_consensus/src/state_machine_test.rs @@ -7,7 +7,7 @@ use test_case::test_case; use super::Round; use crate::state_machine::{StateMachine, StateMachineEvent}; -use crate::types::{ProposalContentId, ValidatorId, DEFAULT_VALIDATOR_ID}; +use crate::types::{DEFAULT_VALIDATOR_ID, ProposalContentId, ValidatorId}; lazy_static! { static ref PROPOSER_ID: ValidatorId = DEFAULT_VALIDATOR_ID.into(); diff --git a/crates/sequencing/papyrus_consensus/src/stream_handler.rs b/crates/sequencing/papyrus_consensus/src/stream_handler.rs index 8bd0bcfe3c..96ca88c85b 100644 --- a/crates/sequencing/papyrus_consensus/src/stream_handler.rs +++ b/crates/sequencing/papyrus_consensus/src/stream_handler.rs @@ -5,8 +5,8 @@ use std::collections::btree_map::Entry as BTreeEntry; use std::collections::hash_map::Entry as HashMapEntry; use std::collections::{BTreeMap, HashMap}; -use futures::channel::mpsc; use futures::StreamExt; +use futures::channel::mpsc; use papyrus_network::network_manager::{ BroadcastTopicClient, BroadcastTopicClientTrait, BroadcastTopicServer, }; diff --git a/crates/sequencing/papyrus_consensus/src/stream_handler_test.rs b/crates/sequencing/papyrus_consensus/src/stream_handler_test.rs index d061abb2b0..e1e991bd86 100644 --- a/crates/sequencing/papyrus_consensus/src/stream_handler_test.rs +++ b/crates/sequencing/papyrus_consensus/src/stream_handler_test.rs @@ -1,15 +1,15 @@ use std::time::Duration; +use futures::SinkExt; use futures::channel::mpsc; use futures::stream::StreamExt; -use futures::SinkExt; +use papyrus_network::network_manager::BroadcastTopicChannels; use papyrus_network::network_manager::test_utils::{ - mock_register_broadcast_topic, MockBroadcastedMessagesSender, TestSubscriberChannels, + MockBroadcastedMessagesSender, TestSubscriberChannels, mock_register_broadcast_topic, }; -use papyrus_network::network_manager::BroadcastTopicChannels; use papyrus_network_types::network_types::BroadcastedMessageMetadata; use papyrus_protobuf::consensus::{ConsensusMessage, Proposal, StreamMessage, StreamMessageBody}; -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use super::{MessageId, StreamHandler, StreamId}; @@ -247,11 +247,13 @@ mod tests { let mut stream_handler = join_handle.await.expect("Task should succeed"); let values = [(peer_id.clone(), 1), (peer_id.clone(), 10), (peer_id.clone(), 127)]; - assert!(stream_handler - .inbound_stream_data - .clone() - .into_keys() - .all(|item| values.contains(&item))); + assert!( + stream_handler + .inbound_stream_data + .clone() + .into_keys() + .all(|item| values.contains(&item)) + ); // We have all message from 1 to 9 buffered. assert!(do_vecs_match( @@ -319,11 +321,13 @@ mod tests { // stream_id1 should be gone let values = [(peer_id.clone(), 1), (peer_id.clone(), 10)]; - assert!(stream_handler - .inbound_stream_data - .clone() - .into_keys() - .all(|item| values.contains(&item))); + assert!( + stream_handler + .inbound_stream_data + .clone() + .into_keys() + .all(|item| values.contains(&item)) + ); // Send the last message on stream_id2: send(&mut network_sender, &inbound_metadata, make_test_message(stream_id2, 0, false)).await; @@ -344,11 +348,13 @@ mod tests { // Stream_id2 should also be gone. let values = [(peer_id.clone(), 1)]; - assert!(stream_handler - .inbound_stream_data - .clone() - .into_keys() - .all(|item| values.contains(&item))); + assert!( + stream_handler + .inbound_stream_data + .clone() + .into_keys() + .all(|item| values.contains(&item)) + ); // Send the last message on stream_id3: send(&mut network_sender, &inbound_metadata, make_test_message(stream_id3, 0, false)).await; @@ -367,16 +373,18 @@ mod tests { // Stream_id3 should still be there, because we didn't send a fin. let values = [(peer_id.clone(), 1)]; - assert!(stream_handler - .inbound_stream_data - .clone() - .into_keys() - .all(|item| values.contains(&item))); + assert!( + stream_handler + .inbound_stream_data + .clone() + .into_keys() + .all(|item| values.contains(&item)) + ); // But the buffer should be empty, as we've successfully drained it all. - assert!(stream_handler.inbound_stream_data[&(peer_id, stream_id3)] - .message_buffer - .is_empty()); + assert!( + stream_handler.inbound_stream_data[&(peer_id, stream_id3)].message_buffer.is_empty() + ); } // This test does two things: @@ -421,10 +429,9 @@ mod tests { assert_eq!(broadcasted_message.message_id, 0); // Check that internally, stream_handler holds this receiver. - assert_eq!( - stream_handler.outbound_stream_receivers.keys().collect::>(), - vec![&stream_id1] - ); + assert_eq!(stream_handler.outbound_stream_receivers.keys().collect::>(), vec![ + &stream_id1 + ]); // Check that the number of messages sent on this stream is 1. assert_eq!(stream_handler.outbound_stream_number[&stream_id1], 1); @@ -495,9 +502,8 @@ mod tests { let stream_handler = join_handle.await.expect("Task should succeed"); // Check that the information about this stream is gone. - assert_eq!( - stream_handler.outbound_stream_receivers.keys().collect::>(), - vec![&stream_id2] - ); + assert_eq!(stream_handler.outbound_stream_receivers.keys().collect::>(), vec![ + &stream_id2 + ]); } } diff --git a/crates/sequencing/papyrus_consensus/src/test_utils.rs b/crates/sequencing/papyrus_consensus/src/test_utils.rs index 6e4a06c1b5..e5657e1b66 100644 --- a/crates/sequencing/papyrus_consensus/src/test_utils.rs +++ b/crates/sequencing/papyrus_consensus/src/test_utils.rs @@ -9,7 +9,7 @@ use starknet_api::block::{BlockHash, BlockNumber}; use starknet_types_core::felt::Felt; use crate::types::{ - ConsensusContext, ConsensusError, ProposalContentId, Round, ValidatorId, DEFAULT_VALIDATOR_ID, + ConsensusContext, ConsensusError, DEFAULT_VALIDATOR_ID, ProposalContentId, Round, ValidatorId, }; /// Define a consensus block which can be used to enable auto mocking Context. diff --git a/crates/sequencing/papyrus_consensus_orchestrator/src/papyrus_consensus_context.rs b/crates/sequencing/papyrus_consensus_orchestrator/src/papyrus_consensus_context.rs index a7c61c21af..0d4f936b47 100644 --- a/crates/sequencing/papyrus_consensus_orchestrator/src/papyrus_consensus_context.rs +++ b/crates/sequencing/papyrus_consensus_orchestrator/src/papyrus_consensus_context.rs @@ -16,7 +16,7 @@ use async_trait::async_trait; use futures::channel::{mpsc, oneshot}; use futures::{SinkExt, StreamExt}; use papyrus_consensus::types::{ - ConsensusContext, ConsensusError, ProposalContentId, Round, ValidatorId, DEFAULT_VALIDATOR_ID, + ConsensusContext, ConsensusError, DEFAULT_VALIDATOR_ID, ProposalContentId, Round, ValidatorId, }; use papyrus_network::network_manager::{BroadcastTopicClient, BroadcastTopicClientTrait}; use papyrus_protobuf::consensus::{ @@ -27,7 +27,7 @@ use papyrus_storage::header::HeaderStorageReader; use papyrus_storage::{StorageError, StorageReader}; use starknet_api::block::BlockNumber; use starknet_api::transaction::Transaction; -use tracing::{debug, debug_span, info, warn, Instrument}; +use tracing::{Instrument, debug, debug_span, info, warn}; // TODO: add debug messages and span to the tasks. diff --git a/crates/sequencing/papyrus_consensus_orchestrator/src/papyrus_consensus_context_test.rs b/crates/sequencing/papyrus_consensus_orchestrator/src/papyrus_consensus_context_test.rs index b56fc2c582..d10e07c135 100644 --- a/crates/sequencing/papyrus_consensus_orchestrator/src/papyrus_consensus_context_test.rs +++ b/crates/sequencing/papyrus_consensus_orchestrator/src/papyrus_consensus_context_test.rs @@ -1,13 +1,13 @@ use std::time::Duration; -use futures::channel::{mpsc, oneshot}; use futures::StreamExt; +use futures::channel::{mpsc, oneshot}; use papyrus_consensus::stream_handler::StreamHandler; -use papyrus_consensus::types::{ConsensusContext, ValidatorId, DEFAULT_VALIDATOR_ID}; +use papyrus_consensus::types::{ConsensusContext, DEFAULT_VALIDATOR_ID, ValidatorId}; +use papyrus_network::network_manager::BroadcastTopicChannels; use papyrus_network::network_manager::test_utils::{ - mock_register_broadcast_topic, BroadcastNetworkMock, TestSubscriberChannels, + BroadcastNetworkMock, TestSubscriberChannels, mock_register_broadcast_topic, }; -use papyrus_network::network_manager::BroadcastTopicChannels; use papyrus_protobuf::consensus::{ ConsensusMessage, ProposalFin, ProposalInit, ProposalPart, StreamMessage, TransactionBatch, Vote, diff --git a/crates/sequencing/papyrus_consensus_orchestrator/src/sequencer_consensus_context.rs b/crates/sequencing/papyrus_consensus_orchestrator/src/sequencer_consensus_context.rs index 3cc7566ffd..ab3b4f8936 100644 --- a/crates/sequencing/papyrus_consensus_orchestrator/src/sequencer_consensus_context.rs +++ b/crates/sequencing/papyrus_consensus_orchestrator/src/sequencer_consensus_context.rs @@ -13,7 +13,7 @@ use async_trait::async_trait; use futures::channel::{mpsc, oneshot}; use futures::{SinkExt, StreamExt}; use papyrus_consensus::types::{ - ConsensusContext, ConsensusError, ProposalContentId, Round, ValidatorId, DEFAULT_VALIDATOR_ID, + ConsensusContext, ConsensusError, DEFAULT_VALIDATOR_ID, ProposalContentId, Round, ValidatorId, }; use papyrus_network::network_manager::{BroadcastTopicClient, BroadcastTopicClientTrait}; use papyrus_protobuf::consensus::{ @@ -32,7 +32,7 @@ use starknet_batcher_types::batcher_types::{ use starknet_batcher_types::communication::BatcherClient; use tokio::sync::Notify; use tokio::task::JoinHandle; -use tracing::{debug, debug_span, error, info, trace, warn, Instrument}; +use tracing::{Instrument, debug, debug_span, error, info, trace, warn}; // TODO(Dan, Matan): Remove this once and replace with real gas prices. const TEMPORARY_GAS_PRICES: GasPrices = GasPrices { @@ -446,7 +446,7 @@ async fn stream_build_proposal( .expect("Failed to broadcast proposal content"); } GetProposalContent::Finished(id) => { - let proposal_content_id = BlockHash(id.state_diff_commitment.0 .0); + let proposal_content_id = BlockHash(id.state_diff_commitment.0.0); info!( "Finished building proposal {:?}: content_id = {:?}, num_txs = {:?}, height = \ {:?}", @@ -542,7 +542,7 @@ async fn stream_validate_proposal( } status => panic!("Unexpected status: for {proposal_id:?}, {status:?}"), }; - let batcher_block_id = BlockHash(response_id.state_diff_commitment.0 .0); + let batcher_block_id = BlockHash(response_id.state_diff_commitment.0.0); info!( "Finished validating proposal {:?}: network_block_id: {:?}, batcher_block_id = {:?}, \ num_txs = {:?}, height = {:?}", diff --git a/crates/sequencing/papyrus_consensus_orchestrator/src/sequencer_consensus_context_test.rs b/crates/sequencing/papyrus_consensus_orchestrator/src/sequencer_consensus_context_test.rs index 25eba811d0..5e188f2db9 100644 --- a/crates/sequencing/papyrus_consensus_orchestrator/src/sequencer_consensus_context_test.rs +++ b/crates/sequencing/papyrus_consensus_orchestrator/src/sequencer_consensus_context_test.rs @@ -6,11 +6,11 @@ use futures::channel::mpsc; use futures::{FutureExt, SinkExt}; use lazy_static::lazy_static; use papyrus_consensus::stream_handler::StreamHandler; -use papyrus_consensus::types::{ConsensusContext, ValidatorId, DEFAULT_VALIDATOR_ID}; +use papyrus_consensus::types::{ConsensusContext, DEFAULT_VALIDATOR_ID, ValidatorId}; +use papyrus_network::network_manager::BroadcastTopicChannels; use papyrus_network::network_manager::test_utils::{ - mock_register_broadcast_topic, BroadcastNetworkMock, TestSubscriberChannels, + BroadcastNetworkMock, TestSubscriberChannels, mock_register_broadcast_topic, }; -use papyrus_network::network_manager::BroadcastTopicChannels; use papyrus_protobuf::consensus::{ ConsensusMessage, ProposalFin, ProposalInit, ProposalPart, StreamMessage, TransactionBatch, }; @@ -18,7 +18,7 @@ use starknet_api::block::{BlockHash, BlockNumber}; use starknet_api::core::StateDiffCommitment; use starknet_api::executable_transaction::Transaction as ExecutableTransaction; use starknet_api::hash::PoseidonHash; -use starknet_api::test_utils::invoke::{executable_invoke_tx, invoke_tx, InvokeTxArgs}; +use starknet_api::test_utils::invoke::{InvokeTxArgs, executable_invoke_tx, invoke_tx}; use starknet_api::transaction::{Transaction, TransactionHash}; use starknet_batcher_types::batcher_types::{ GetProposalContent, GetProposalContentResponse, ProposalCommitment, ProposalId, ProposalStatus, @@ -120,7 +120,7 @@ async fn build_proposal() { ProposalInit { proposer: ValidatorId::from(DEFAULT_VALIDATOR_ID), ..Default::default() }; // TODO(Asmaa): Test proposal content. let fin_receiver = context.build_proposal(init, TIMEOUT).await; - assert_eq!(fin_receiver.await.unwrap().0, STATE_DIFF_COMMITMENT.0 .0); + assert_eq!(fin_receiver.await.unwrap().0, STATE_DIFF_COMMITMENT.0.0); } #[tokio::test] @@ -177,7 +177,7 @@ async fn validate_proposal_success() { .unwrap(); content_sender .send(ProposalPart::Fin(ProposalFin { - proposal_content_id: BlockHash(STATE_DIFF_COMMITMENT.0 .0), + proposal_content_id: BlockHash(STATE_DIFF_COMMITMENT.0.0), })) .await .unwrap(); @@ -191,7 +191,7 @@ async fn validate_proposal_success() { ) .await; content_sender.close_channel(); - assert_eq!(fin_receiver.await.unwrap().0 .0, STATE_DIFF_COMMITMENT.0 .0); + assert_eq!(fin_receiver.await.unwrap().0.0, STATE_DIFF_COMMITMENT.0.0); } #[tokio::test] @@ -235,7 +235,7 @@ async fn repropose() { .unwrap(); content_sender .send(ProposalPart::Fin(ProposalFin { - proposal_content_id: BlockHash(STATE_DIFF_COMMITMENT.0 .0), + proposal_content_id: BlockHash(STATE_DIFF_COMMITMENT.0.0), })) .await .unwrap(); @@ -249,14 +249,14 @@ async fn repropose() { ) .await; content_sender.close_channel(); - assert_eq!(fin_receiver.await.unwrap().0 .0, STATE_DIFF_COMMITMENT.0 .0); + assert_eq!(fin_receiver.await.unwrap().0.0, STATE_DIFF_COMMITMENT.0.0); // Re-proposal: Just asserts this is a known valid proposal. context - .repropose( - BlockHash(STATE_DIFF_COMMITMENT.0 .0), - ProposalInit { height: BlockNumber(0), ..Default::default() }, - ) + .repropose(BlockHash(STATE_DIFF_COMMITMENT.0.0), ProposalInit { + height: BlockNumber(0), + ..Default::default() + }) .await; } @@ -307,7 +307,7 @@ async fn proposals_from_different_rounds() { tx_hashes: vec![TX_BATCH[0].tx_hash()], }); let prop_part_fin = ProposalPart::Fin(ProposalFin { - proposal_content_id: BlockHash(STATE_DIFF_COMMITMENT.0 .0), + proposal_content_id: BlockHash(STATE_DIFF_COMMITMENT.0.0), }); // The proposal from the past round is ignored. @@ -339,7 +339,7 @@ async fn proposals_from_different_rounds() { content_receiver, ) .await; - assert_eq!(fin_receiver_curr_round.await.unwrap().0 .0, STATE_DIFF_COMMITMENT.0 .0); + assert_eq!(fin_receiver_curr_round.await.unwrap().0.0, STATE_DIFF_COMMITMENT.0.0); // The proposal from the future round should not be processed. let (mut content_sender, content_receiver) = mpsc::channel(CHANNEL_SIZE); @@ -427,7 +427,7 @@ async fn interrupt_active_proposal() { .unwrap(); content_sender_1 .send(ProposalPart::Fin(ProposalFin { - proposal_content_id: BlockHash(STATE_DIFF_COMMITMENT.0 .0), + proposal_content_id: BlockHash(STATE_DIFF_COMMITMENT.0.0), })) .await .unwrap(); @@ -445,5 +445,5 @@ async fn interrupt_active_proposal() { // Interrupt active proposal. assert!(fin_receiver_0.await.is_err()); - assert_eq!(fin_receiver_1.await.unwrap().0 .0, STATE_DIFF_COMMITMENT.0 .0); + assert_eq!(fin_receiver_1.await.unwrap().0.0, STATE_DIFF_COMMITMENT.0.0); } diff --git a/crates/starknet_api/src/abi/abi_utils.rs b/crates/starknet_api/src/abi/abi_utils.rs index 22f9d7ac41..b33621f700 100644 --- a/crates/starknet_api/src/abi/abi_utils.rs +++ b/crates/starknet_api/src/abi/abi_utils.rs @@ -3,7 +3,7 @@ use starknet_types_core::felt::{Felt, NonZeroFelt}; use starknet_types_core::hash::{Pedersen, StarkHash}; use crate::abi::constants; -use crate::core::{ContractAddress, EntryPointSelector, PatriciaKey, L2_ADDRESS_UPPER_BOUND}; +use crate::core::{ContractAddress, EntryPointSelector, L2_ADDRESS_UPPER_BOUND, PatriciaKey}; use crate::state::StorageKey; #[cfg(test)] diff --git a/crates/starknet_api/src/block.rs b/crates/starknet_api/src/block.rs index 177051838c..783f4647f0 100644 --- a/crates/starknet_api/src/block.rs +++ b/crates/starknet_api/src/block.rs @@ -8,18 +8,18 @@ use starknet_types_core::felt::Felt; use starknet_types_core::hash::{Poseidon, StarkHash as CoreStarkHash}; use strum_macros::EnumIter; +use crate::StarknetApiError; use crate::core::{ ContractAddress, EventCommitment, GlobalRoot, ReceiptCommitment, SequencerContractAddress, SequencerPublicKey, StateDiffCommitment, TransactionCommitment, }; -use crate::crypto::utils::{verify_message_hash_signature, CryptoError, Signature}; +use crate::crypto::utils::{CryptoError, Signature, verify_message_hash_signature}; use crate::data_availability::L1DataAvailabilityMode; use crate::execution_resources::GasAmount; use crate::hash::StarkHash; use crate::serde_utils::{BytesAsHex, PrefixedBytesAsHex}; use crate::transaction::fields::Fee; use crate::transaction::{Transaction, TransactionHash, TransactionOutput}; -use crate::StarknetApiError; /// A block. #[derive(Debug, Default, Clone, Eq, PartialEq, Deserialize, Serialize)] diff --git a/crates/starknet_api/src/block_hash/block_hash_calculator.rs b/crates/starknet_api/src/block_hash/block_hash_calculator.rs index ad452185c7..9a71d1a58b 100644 --- a/crates/starknet_api/src/block_hash/block_hash_calculator.rs +++ b/crates/starknet_api/src/block_hash/block_hash_calculator.rs @@ -4,13 +4,13 @@ use serde::{Deserialize, Serialize}; use starknet_types_core::felt::Felt; use starknet_types_core::hash::Poseidon; -use super::event_commitment::{calculate_event_commitment, EventLeafElement}; -use super::receipt_commitment::{calculate_receipt_commitment, ReceiptElement}; +use super::event_commitment::{EventLeafElement, calculate_event_commitment}; +use super::receipt_commitment::{ReceiptElement, calculate_receipt_commitment}; use super::state_diff_hash::calculate_state_diff_hash; -use super::transaction_commitment::{calculate_transaction_commitment, TransactionLeafElement}; +use super::transaction_commitment::{TransactionLeafElement, calculate_transaction_commitment}; use crate::block::{BlockHash, BlockHeaderWithoutHash, GasPricePerToken, StarknetVersion}; use crate::core::{ - ascii_as_felt, EventCommitment, ReceiptCommitment, StateDiffCommitment, TransactionCommitment, + EventCommitment, ReceiptCommitment, StateDiffCommitment, TransactionCommitment, ascii_as_felt, }; use crate::crypto::utils::HashChain; use crate::data_availability::L1DataAvailabilityMode; @@ -122,7 +122,7 @@ pub fn calculate_block_hash( .chain(&header.sequencer.0) .chain(&header.timestamp.0.into()) .chain(&block_commitments.concatenated_counts) - .chain(&block_commitments.state_diff_commitment.0 .0) + .chain(&block_commitments.state_diff_commitment.0.0) .chain(&block_commitments.transaction_commitment.0) .chain(&block_commitments.event_commitment.0) .chain(&block_commitments.receipt_commitment.0) @@ -240,15 +240,17 @@ fn gas_prices_to_hash( block_hash_version: &BlockHashVersion, ) -> Vec { if block_hash_version >= &BlockHashVersion::V0_13_4 { - vec![HashChain::new() - .chain(&STARKNET_GAS_PRICES0) - .chain(&l1_gas_price.price_in_wei.0.into()) - .chain(&l1_gas_price.price_in_fri.0.into()) - .chain(&l1_data_gas_price.price_in_wei.0.into()) - .chain(&l1_data_gas_price.price_in_fri.0.into()) - .chain(&l2_gas_price.price_in_wei.0.into()) - .chain(&l2_gas_price.price_in_fri.0.into()) - .get_poseidon_hash()] + vec![ + HashChain::new() + .chain(&STARKNET_GAS_PRICES0) + .chain(&l1_gas_price.price_in_wei.0.into()) + .chain(&l1_gas_price.price_in_fri.0.into()) + .chain(&l1_data_gas_price.price_in_wei.0.into()) + .chain(&l1_data_gas_price.price_in_fri.0.into()) + .chain(&l2_gas_price.price_in_wei.0.into()) + .chain(&l2_gas_price.price_in_fri.0.into()) + .get_poseidon_hash(), + ] } else { vec![ l1_gas_price.price_in_wei.0.into(), diff --git a/crates/starknet_api/src/block_hash/block_hash_calculator_test.rs b/crates/starknet_api/src/block_hash/block_hash_calculator_test.rs index 0d15c3444c..f58f721d6e 100644 --- a/crates/starknet_api/src/block_hash/block_hash_calculator_test.rs +++ b/crates/starknet_api/src/block_hash/block_hash_calculator_test.rs @@ -6,8 +6,8 @@ use crate::block::{ BlockHash, BlockHeaderWithoutHash, BlockNumber, BlockTimestamp, GasPricePerToken, }; use crate::block_hash::block_hash_calculator::{ - calculate_block_commitments, calculate_block_hash, BlockHashVersion, BlockHeaderCommitments, - TransactionHashingData, + BlockHashVersion, BlockHeaderCommitments, TransactionHashingData, calculate_block_commitments, + calculate_block_hash, }; use crate::block_hash::test_utils::{get_state_diff, get_transaction_output}; use crate::core::{ diff --git a/crates/starknet_api/src/block_hash/event_commitment_test.rs b/crates/starknet_api/src/block_hash/event_commitment_test.rs index 7fc0752bfb..dd3a95709a 100644 --- a/crates/starknet_api/src/block_hash/event_commitment_test.rs +++ b/crates/starknet_api/src/block_hash/event_commitment_test.rs @@ -1,7 +1,7 @@ use starknet_types_core::felt::Felt; use starknet_types_core::hash::Poseidon; -use super::{calculate_event_commitment, calculate_event_hash, EventLeafElement}; +use super::{EventLeafElement, calculate_event_commitment, calculate_event_hash}; use crate::core::EventCommitment; use crate::transaction::{Event, EventContent, EventData, EventKey}; use crate::{contract_address, felt, tx_hash}; diff --git a/crates/starknet_api/src/block_hash/receipt_commitment_test.rs b/crates/starknet_api/src/block_hash/receipt_commitment_test.rs index 359dc1e919..6d42285459 100644 --- a/crates/starknet_api/src/block_hash/receipt_commitment_test.rs +++ b/crates/starknet_api/src/block_hash/receipt_commitment_test.rs @@ -3,7 +3,7 @@ use starknet_types_core::hash::Poseidon; use super::calculate_messages_sent_hash; use crate::block_hash::receipt_commitment::{ - calculate_receipt_commitment, calculate_receipt_hash, get_revert_reason_hash, ReceiptElement, + ReceiptElement, calculate_receipt_commitment, calculate_receipt_hash, get_revert_reason_hash, }; use crate::block_hash::test_utils::{generate_message_to_l1, get_transaction_output}; use crate::core::ReceiptCommitment; diff --git a/crates/starknet_api/src/block_hash/state_diff_hash.rs b/crates/starknet_api/src/block_hash/state_diff_hash.rs index 9fa4993a10..74d1316578 100644 --- a/crates/starknet_api/src/block_hash/state_diff_hash.rs +++ b/crates/starknet_api/src/block_hash/state_diff_hash.rs @@ -4,7 +4,7 @@ use indexmap::IndexMap; use starknet_types_core::felt::Felt; use crate::core::{ - ascii_as_felt, ClassHash, CompiledClassHash, ContractAddress, Nonce, StateDiffCommitment, + ClassHash, CompiledClassHash, ContractAddress, Nonce, StateDiffCommitment, ascii_as_felt, }; use crate::crypto::utils::HashChain; use crate::hash::PoseidonHash; diff --git a/crates/starknet_api/src/block_hash/transaction_commitment.rs b/crates/starknet_api/src/block_hash/transaction_commitment.rs index 9ddb4ad901..19cf9cae5e 100644 --- a/crates/starknet_api/src/block_hash/transaction_commitment.rs +++ b/crates/starknet_api/src/block_hash/transaction_commitment.rs @@ -5,8 +5,8 @@ use super::block_hash_calculator::TransactionHashingData; use crate::core::TransactionCommitment; use crate::crypto::patricia_hash::calculate_root; use crate::crypto::utils::HashChain; -use crate::transaction::fields::TransactionSignature; use crate::transaction::TransactionHash; +use crate::transaction::fields::TransactionSignature; #[cfg(test)] #[path = "transaction_commitment_test.rs"] diff --git a/crates/starknet_api/src/block_test.rs b/crates/starknet_api/src/block_test.rs index fa7b6f526c..3b12398292 100644 --- a/crates/starknet_api/src/block_test.rs +++ b/crates/starknet_api/src/block_test.rs @@ -1,7 +1,7 @@ use serde_json::json; use strum::IntoEnumIterator; -use super::{verify_block_signature, StarknetVersion}; +use super::{StarknetVersion, verify_block_signature}; use crate::block::{BlockHash, BlockNumber, BlockSignature}; use crate::core::{GlobalRoot, SequencerPublicKey}; use crate::crypto::utils::{PublicKey, Signature}; @@ -43,8 +43,10 @@ fn block_signature_verification() { "0x48253ff2c3bed7af18bde0b611b083b39445959102d4947c51c4db6aa4f4e58" ))); - assert!(verify_block_signature(&sequencer_pub_key, &signature, &state_commitment, &block_hash) - .unwrap()); + assert!( + verify_block_signature(&sequencer_pub_key, &signature, &state_commitment, &block_hash) + .unwrap() + ); } #[test] diff --git a/crates/starknet_api/src/contract_class.rs b/crates/starknet_api/src/contract_class.rs index c8a295d57a..475fce7963 100644 --- a/crates/starknet_api/src/contract_class.rs +++ b/crates/starknet_api/src/contract_class.rs @@ -6,9 +6,9 @@ use derive_more::Deref; use semver::Version; use serde::{Deserialize, Serialize}; +use crate::StarknetApiError; use crate::core::CompiledClassHash; use crate::deprecated_contract_class::ContractClass as DeprecatedContractClass; -use crate::StarknetApiError; /// One Felt fits into 32 bytes. pub const FELT_WIDTH: usize = 32; diff --git a/crates/starknet_api/src/core.rs b/crates/starknet_api/src/core.rs index d8298d6583..f4efbd9524 100644 --- a/crates/starknet_api/src/core.rs +++ b/crates/starknet_api/src/core.rs @@ -14,7 +14,7 @@ use crate::crypto::utils::PublicKey; use crate::hash::{PoseidonHash, StarkHash}; use crate::serde_utils::{BytesAsHex, PrefixedBytesAsHex}; use crate::transaction::fields::{Calldata, ContractAddressSalt}; -use crate::{impl_from_through_intermediate, StarknetApiError}; +use crate::{StarknetApiError, impl_from_through_intermediate}; /// Felt. pub fn ascii_as_felt(ascii_str: &str) -> Result { @@ -113,9 +113,9 @@ impl ContractAddress { /// The lower bound is above the special saved addresses and the upper bound is congruent with /// the storage var address upper bound. pub fn validate(&self) -> Result<(), StarknetApiError> { - let value = self.0 .0; + let value = self.0.0; let l2_address_upper_bound = Felt::from(*L2_ADDRESS_UPPER_BOUND); - if (value > BLOCK_HASH_TABLE_ADDRESS.0 .0) && (value < l2_address_upper_bound) { + if (value > BLOCK_HASH_TABLE_ADDRESS.0.0) && (value < l2_address_upper_bound) { return Ok(()); } diff --git a/crates/starknet_api/src/core_test.rs b/crates/starknet_api/src/core_test.rs index 705ce707ee..21d78e7ec0 100644 --- a/crates/starknet_api/src/core_test.rs +++ b/crates/starknet_api/src/core_test.rs @@ -3,8 +3,8 @@ use starknet_types_core::felt::Felt; use starknet_types_core::hash::{Pedersen, StarkHash as CoreStarkHash}; use crate::core::{ - ascii_as_felt, calculate_contract_address, ChainId, ContractAddress, EthAddress, Nonce, - PatriciaKey, StarknetApiError, CONTRACT_ADDRESS_PREFIX, L2_ADDRESS_UPPER_BOUND, + CONTRACT_ADDRESS_PREFIX, ChainId, ContractAddress, EthAddress, L2_ADDRESS_UPPER_BOUND, Nonce, + PatriciaKey, StarknetApiError, ascii_as_felt, calculate_contract_address, }; use crate::hash::StarkHash; use crate::transaction::fields::{Calldata, ContractAddressSalt}; diff --git a/crates/starknet_api/src/crypto/crypto_test.rs b/crates/starknet_api/src/crypto/crypto_test.rs index 7d78fc35ba..b0ea14e632 100644 --- a/crates/starknet_api/src/crypto/crypto_test.rs +++ b/crates/starknet_api/src/crypto/crypto_test.rs @@ -2,7 +2,7 @@ use starknet_types_core::hash::{Poseidon, StarkHash}; -use crate::crypto::utils::{verify_message_hash_signature, PublicKey, Signature}; +use crate::crypto::utils::{PublicKey, Signature, verify_message_hash_signature}; use crate::felt; #[test] diff --git a/crates/starknet_api/src/deprecated_contract_class.rs b/crates/starknet_api/src/deprecated_contract_class.rs index 233ceb64ea..e5f0660a8f 100644 --- a/crates/starknet_api/src/deprecated_contract_class.rs +++ b/crates/starknet_api/src/deprecated_contract_class.rs @@ -7,11 +7,11 @@ use serde::de::Error as DeserializationError; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::Value; +use crate::StarknetApiError; use crate::contract_class::EntryPointType; use crate::core::EntryPointSelector; use crate::hash::StarkHash; use crate::serde_utils::deserialize_optional_contract_class_abi_entry_vector; -use crate::StarknetApiError; /// A deprecated contract class. #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] diff --git a/crates/starknet_api/src/executable_transaction.rs b/crates/starknet_api/src/executable_transaction.rs index 9bc79ada44..581f610900 100644 --- a/crates/starknet_api/src/executable_transaction.rs +++ b/crates/starknet_api/src/executable_transaction.rs @@ -1,7 +1,8 @@ use serde::{Deserialize, Serialize}; +use crate::StarknetApiError; use crate::contract_class::{ClassInfo, ContractClass}; -use crate::core::{calculate_contract_address, ChainId, ClassHash, ContractAddress, Nonce}; +use crate::core::{ChainId, ClassHash, ContractAddress, Nonce, calculate_contract_address}; use crate::data_availability::DataAvailabilityMode; use crate::rpc_transaction::{ RpcDeployAccountTransaction, RpcDeployAccountTransactionV3, RpcInvokeTransaction, @@ -12,7 +13,6 @@ use crate::transaction::fields::{ Tip, TransactionSignature, ValidResourceBounds, }; use crate::transaction::{TransactionHash, TransactionHasher, TransactionVersion}; -use crate::StarknetApiError; macro_rules! implement_inner_tx_getter_calls { ($(($field:ident, $field_type:ty)),*) => { diff --git a/crates/starknet_api/src/execution_utils.rs b/crates/starknet_api/src/execution_utils.rs index 087187c23d..70552e1588 100644 --- a/crates/starknet_api/src/execution_utils.rs +++ b/crates/starknet_api/src/execution_utils.rs @@ -7,9 +7,5 @@ pub fn format_panic_data(felts: &[Felt]) -> String { while let Some(item) = format_next_item(&mut felts) { items.push(item.quote_if_string()); } - if let [item] = &items[..] { - item.clone() - } else { - format!("({})", items.join(", ")) - } + if let [item] = &items[..] { item.clone() } else { format!("({})", items.join(", ")) } } diff --git a/crates/starknet_api/src/rpc_transaction.rs b/crates/starknet_api/src/rpc_transaction.rs index 5cbf80fc85..c0f8ce4544 100644 --- a/crates/starknet_api/src/rpc_transaction.rs +++ b/crates/starknet_api/src/rpc_transaction.rs @@ -7,9 +7,10 @@ use std::collections::HashMap; use cairo_lang_starknet_classes::contract_class::ContractEntryPoints as CairoLangContractEntryPoints; use serde::{Deserialize, Serialize}; +use crate::StarknetApiError; use crate::contract_class::EntryPointType; use crate::core::{ - calculate_contract_address, ClassHash, CompiledClassHash, ContractAddress, Nonce, + ClassHash, CompiledClassHash, ContractAddress, Nonce, calculate_contract_address, }; use crate::data_availability::DataAvailabilityMode; use crate::state::{EntryPoint, SierraContractClass}; @@ -21,7 +22,6 @@ use crate::transaction::{ DeclareTransaction, DeclareTransactionV3, DeployAccountTransaction, DeployAccountTransactionV3, InvokeTransaction, InvokeTransactionV3, Transaction, }; -use crate::StarknetApiError; /// Transactions that are ready to be broadcasted to the network through RPC and are not included in /// a block. diff --git a/crates/starknet_api/src/rpc_transaction_test.rs b/crates/starknet_api/src/rpc_transaction_test.rs index 5a7695f493..9f4866777f 100644 --- a/crates/starknet_api/src/rpc_transaction_test.rs +++ b/crates/starknet_api/src/rpc_transaction_test.rs @@ -11,7 +11,7 @@ use crate::rpc_transaction::{ RpcDeployAccountTransaction, RpcDeployAccountTransactionV3, RpcTransaction, }; use crate::state::SierraContractClass; -use crate::test_utils::invoke::{rpc_invoke_tx, InvokeTxArgs}; +use crate::test_utils::invoke::{InvokeTxArgs, rpc_invoke_tx}; use crate::transaction::fields::{ AccountDeploymentData, AllResourceBounds, Calldata, ContractAddressSalt, PaymasterData, ResourceBounds, Tip, TransactionSignature, ValidResourceBounds, diff --git a/crates/starknet_api/src/serde_utils.rs b/crates/starknet_api/src/serde_utils.rs index d82ea6233e..8a70d5e3b3 100644 --- a/crates/starknet_api/src/serde_utils.rs +++ b/crates/starknet_api/src/serde_utils.rs @@ -3,9 +3,9 @@ #[path = "serde_utils_test.rs"] mod serde_utils_test; +use serde::Deserializer; use serde::de::{Deserialize, Visitor}; use serde::ser::{Serialize, SerializeTuple}; -use serde::Deserializer; use crate::deprecated_contract_class::ContractClassAbiEntry; @@ -131,11 +131,7 @@ pub fn hex_str_from_bytes(bytes: [u8; N]) let hex_str = hex::encode(bytes); let mut hex_str = hex_str.trim_start_matches('0'); hex_str = if hex_str.is_empty() { "0" } else { hex_str }; - if PREFIXED { - format!("0x{hex_str}") - } else { - hex_str.to_string() - } + if PREFIXED { format!("0x{hex_str}") } else { hex_str.to_string() } } pub fn deserialize_optional_contract_class_abi_entry_vector<'de, D>( diff --git a/crates/starknet_api/src/serde_utils_test.rs b/crates/starknet_api/src/serde_utils_test.rs index 711de14621..be0ac38ff4 100644 --- a/crates/starknet_api/src/serde_utils_test.rs +++ b/crates/starknet_api/src/serde_utils_test.rs @@ -5,8 +5,8 @@ use crate::deprecated_contract_class::{ ConstructorType, ContractClassAbiEntry, FunctionAbiEntry, TypedParameter, }; use crate::serde_utils::{ - bytes_from_hex_str, deserialize_optional_contract_class_abi_entry_vector, hex_str_from_bytes, - BytesAsHex, InnerDeserializationError, + BytesAsHex, InnerDeserializationError, bytes_from_hex_str, + deserialize_optional_contract_class_abi_entry_vector, hex_str_from_bytes, }; #[test] @@ -141,23 +141,18 @@ fn deserialize_valid_optional_contract_class_abi_entry_vector() { } "#; let res: DummyContractClass = serde_json::from_str(json).unwrap(); - assert_eq!( - res, - DummyContractClass { - abi: Some(vec![ContractClassAbiEntry::Constructor(FunctionAbiEntry::< - ConstructorType, - > { - name: "constructor".to_string(), - inputs: vec![TypedParameter { - name: "implementation".to_string(), - r#type: "felt".to_string(), - }], - outputs: vec![], - state_mutability: None, - r#type: ConstructorType::Constructor, - })]) - } - ); + assert_eq!(res, DummyContractClass { + abi: Some(vec![ContractClassAbiEntry::Constructor(FunctionAbiEntry:: { + name: "constructor".to_string(), + inputs: vec![TypedParameter { + name: "implementation".to_string(), + r#type: "felt".to_string(), + }], + outputs: vec![], + state_mutability: None, + r#type: ConstructorType::Constructor, + })]) + }); } #[test] diff --git a/crates/starknet_api/src/state.rs b/crates/starknet_api/src/state.rs index d213c9d8cd..6c10aa85f7 100644 --- a/crates/starknet_api/src/state.rs +++ b/crates/starknet_api/src/state.rs @@ -17,7 +17,7 @@ use crate::core::{ use crate::deprecated_contract_class::ContractClass as DeprecatedContractClass; use crate::hash::StarkHash; use crate::rpc_transaction::EntryPointByType; -use crate::{impl_from_through_intermediate, StarknetApiError}; +use crate::{StarknetApiError, impl_from_through_intermediate}; pub type DeclaredClasses = IndexMap; pub type DeprecatedDeclaredClasses = IndexMap; diff --git a/crates/starknet_api/src/state_test.rs b/crates/starknet_api/src/state_test.rs index 09cc54f056..9d6f47515a 100644 --- a/crates/starknet_api/src/state_test.rs +++ b/crates/starknet_api/src/state_test.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use indexmap::{indexmap, IndexMap}; +use indexmap::{IndexMap, indexmap}; use serde_json::json; use super::ThinStateDiff; @@ -65,17 +65,21 @@ fn thin_state_diff_len() { #[test] fn thin_state_diff_is_empty() { assert!(ThinStateDiff::default().is_empty()); - assert!(ThinStateDiff { - storage_diffs: indexmap! { Default::default() => IndexMap::new() }, - ..Default::default() - } - .is_empty()); + assert!( + ThinStateDiff { + storage_diffs: indexmap! { Default::default() => IndexMap::new() }, + ..Default::default() + } + .is_empty() + ); - assert!(!ThinStateDiff { - deployed_contracts: indexmap! { Default::default() => Default::default() }, - ..Default::default() - } - .is_empty()); + assert!( + !ThinStateDiff { + deployed_contracts: indexmap! { Default::default() => Default::default() }, + ..Default::default() + } + .is_empty() + ); assert!( !ThinStateDiff { storage_diffs: indexmap! { Default::default() => indexmap! { Default::default() => Default::default() } }, @@ -83,24 +87,32 @@ fn thin_state_diff_is_empty() { } .is_empty() ); - assert!(!ThinStateDiff { - declared_classes: indexmap! { Default::default() => Default::default() }, - ..Default::default() - } - .is_empty()); - assert!(!ThinStateDiff { - deprecated_declared_classes: vec![Default::default()], - ..Default::default() - } - .is_empty()); - assert!(!ThinStateDiff { - nonces: indexmap! { Default::default() => Default::default() }, - ..Default::default() - } - .is_empty()); - assert!(!ThinStateDiff { - replaced_classes: indexmap! { Default::default() => Default::default() }, - ..Default::default() - } - .is_empty()); + assert!( + !ThinStateDiff { + declared_classes: indexmap! { Default::default() => Default::default() }, + ..Default::default() + } + .is_empty() + ); + assert!( + !ThinStateDiff { + deprecated_declared_classes: vec![Default::default()], + ..Default::default() + } + .is_empty() + ); + assert!( + !ThinStateDiff { + nonces: indexmap! { Default::default() => Default::default() }, + ..Default::default() + } + .is_empty() + ); + assert!( + !ThinStateDiff { + replaced_classes: indexmap! { Default::default() => Default::default() }, + ..Default::default() + } + .is_empty() + ); } diff --git a/crates/starknet_api/src/test_utils/deploy_account.rs b/crates/starknet_api/src/test_utils/deploy_account.rs index 30dad3dafe..bb7891a186 100644 --- a/crates/starknet_api/src/test_utils/deploy_account.rs +++ b/crates/starknet_api/src/test_utils/deploy_account.rs @@ -1,5 +1,5 @@ use super::NonceManager; -use crate::core::{calculate_contract_address, ClassHash, ContractAddress, Nonce}; +use crate::core::{ClassHash, ContractAddress, Nonce, calculate_contract_address}; use crate::data_availability::DataAvailabilityMode; use crate::executable_transaction::{ AccountTransaction, DeployAccountTransaction as ExecutableDeployAccountTransaction, diff --git a/crates/starknet_api/src/transaction.rs b/crates/starknet_api/src/transaction.rs index e92bfae590..57ff5f42ae 100644 --- a/crates/starknet_api/src/transaction.rs +++ b/crates/starknet_api/src/transaction.rs @@ -22,7 +22,7 @@ use crate::transaction_hash::{ get_deploy_transaction_hash, get_invoke_transaction_v0_hash, get_invoke_transaction_v1_hash, get_invoke_transaction_v3_hash, get_l1_handler_transaction_hash, }; -use crate::{executable_transaction, StarknetApiError}; +use crate::{StarknetApiError, executable_transaction}; #[cfg(test)] #[path = "transaction_test.rs"] diff --git a/crates/starknet_api/src/transaction/fields.rs b/crates/starknet_api/src/transaction/fields.rs index 5e1df8e112..b0c5533df5 100644 --- a/crates/starknet_api/src/transaction/fields.rs +++ b/crates/starknet_api/src/transaction/fields.rs @@ -5,11 +5,11 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use starknet_types_core::felt::Felt; use strum_macros::EnumIter; +use crate::StarknetApiError; use crate::block::{GasPrice, NonzeroGasPrice}; use crate::execution_resources::GasAmount; use crate::hash::StarkHash; use crate::serde_utils::PrefixedBytesAsHex; -use crate::StarknetApiError; /// A fee. #[cfg_attr(any(test, feature = "testing"), derive(derive_more::Add, derive_more::Deref))] diff --git a/crates/starknet_api/src/transaction_hash.rs b/crates/starknet_api/src/transaction_hash.rs index 09307a8323..d172580511 100644 --- a/crates/starknet_api/src/transaction_hash.rs +++ b/crates/starknet_api/src/transaction_hash.rs @@ -2,19 +2,19 @@ use std::sync::LazyLock; use starknet_types_core::felt::Felt; +use crate::StarknetApiError; use crate::block::BlockNumber; -use crate::core::{ascii_as_felt, calculate_contract_address, ChainId, ContractAddress}; +use crate::core::{ChainId, ContractAddress, ascii_as_felt, calculate_contract_address}; use crate::crypto::utils::HashChain; use crate::data_availability::DataAvailabilityMode; use crate::transaction::fields::{ResourceBounds, Tip, ValidResourceBounds}; use crate::transaction::{ - signed_tx_version_from_tx, DeclareTransaction, DeclareTransactionV0V1, DeclareTransactionV2, - DeclareTransactionV3, DeployAccountTransaction, DeployAccountTransactionV1, - DeployAccountTransactionV3, DeployTransaction, InvokeTransaction, InvokeTransactionV0, - InvokeTransactionV1, InvokeTransactionV3, L1HandlerTransaction, Transaction, TransactionHash, - TransactionOptions, TransactionVersion, + DeclareTransaction, DeclareTransactionV0V1, DeclareTransactionV2, DeclareTransactionV3, + DeployAccountTransaction, DeployAccountTransactionV1, DeployAccountTransactionV3, + DeployTransaction, InvokeTransaction, InvokeTransactionV0, InvokeTransactionV1, + InvokeTransactionV3, L1HandlerTransaction, Transaction, TransactionHash, TransactionOptions, + TransactionVersion, signed_tx_version_from_tx, }; -use crate::StarknetApiError; #[cfg(test)] #[path = "transaction_hash_test.rs"] diff --git a/crates/starknet_api/src/transaction_hash_test.rs b/crates/starknet_api/src/transaction_hash_test.rs index 32877f5be3..199f403852 100644 --- a/crates/starknet_api/src/transaction_hash_test.rs +++ b/crates/starknet_api/src/transaction_hash_test.rs @@ -2,8 +2,8 @@ use pretty_assertions::assert_eq; use sha3::{Digest, Keccak256}; use starknet_types_core::felt::Felt; -use super::{get_transaction_hash, validate_transaction_hash, CONSTRUCTOR_ENTRY_POINT_SELECTOR}; -use crate::test_utils::{read_json_file, TransactionTestData}; +use super::{CONSTRUCTOR_ENTRY_POINT_SELECTOR, get_transaction_hash, validate_transaction_hash}; +use crate::test_utils::{TransactionTestData, read_json_file}; use crate::transaction::{Transaction, TransactionOptions}; #[test] diff --git a/crates/starknet_api/src/transaction_test.rs b/crates/starknet_api/src/transaction_test.rs index 5eb6e04ed2..1ee7e0d141 100644 --- a/crates/starknet_api/src/transaction_test.rs +++ b/crates/starknet_api/src/transaction_test.rs @@ -5,7 +5,7 @@ use super::{Transaction, TransactionHash}; use crate::block::NonzeroGasPrice; use crate::executable_transaction::Transaction as ExecutableTransaction; use crate::execution_resources::GasAmount; -use crate::test_utils::{read_json_file, TransactionTestData}; +use crate::test_utils::{TransactionTestData, read_json_file}; use crate::transaction::Fee; #[fixture] diff --git a/crates/starknet_batcher/src/batcher_test.rs b/crates/starknet_batcher/src/batcher_test.rs index af88d40efa..4df6ad4dd8 100644 --- a/crates/starknet_batcher/src/batcher_test.rs +++ b/crates/starknet_batcher/src/batcher_test.rs @@ -6,8 +6,8 @@ use async_trait::async_trait; use blockifier::abi::constants; use blockifier::test_utils::struct_impls::BlockInfoExt; use chrono::Utc; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use mockall::automock; use mockall::predicate::{always, eq}; use rstest::rstest; @@ -257,19 +257,17 @@ async fn validate_block_full_flow() { content: SendProposalContent::Txs(test_txs(0..1)), }; let send_txs_result = batcher.send_proposal_content(send_proposal_input_txs).await.unwrap(); - assert_eq!( - send_txs_result, - SendProposalContentResponse { response: ProposalStatus::Processing } - ); + assert_eq!(send_txs_result, SendProposalContentResponse { + response: ProposalStatus::Processing + }); let send_proposal_input_finish = SendProposalContentInput { proposal_id: PROPOSAL_ID, content: SendProposalContent::Finish }; let send_finish_result = batcher.send_proposal_content(send_proposal_input_finish).await.unwrap(); - assert_eq!( - send_finish_result, - SendProposalContentResponse { response: ProposalStatus::Finished(proposal_commitment()) } - ); + assert_eq!(send_finish_result, SendProposalContentResponse { + response: ProposalStatus::Finished(proposal_commitment()) + }); } #[rstest] @@ -417,10 +415,9 @@ async fn propose_block_full_flow() { .get_proposal_content(GetProposalContentInput { proposal_id: PROPOSAL_ID }) .await .unwrap(); - assert_eq!( - commitment, - GetProposalContentResponse { content: GetProposalContent::Finished(proposal_commitment()) } - ); + assert_eq!(commitment, GetProposalContentResponse { + content: GetProposalContent::Finished(proposal_commitment()) + }); let exhausted = batcher.get_proposal_content(GetProposalContentInput { proposal_id: PROPOSAL_ID }).await; diff --git a/crates/starknet_batcher/src/block_builder.rs b/crates/starknet_batcher/src/block_builder.rs index a11c7f127c..88d13140a5 100644 --- a/crates/starknet_batcher/src/block_builder.rs +++ b/crates/starknet_batcher/src/block_builder.rs @@ -19,7 +19,7 @@ use blockifier::versioned_constants::{VersionedConstants, VersionedConstantsOver use indexmap::IndexMap; #[cfg(test)] use mockall::automock; -use papyrus_config::dumping::{append_sub_config_name, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use papyrus_state_reader::papyrus_state::PapyrusReader; use papyrus_storage::StorageReader; diff --git a/crates/starknet_batcher/src/block_builder_test.rs b/crates/starknet_batcher/src/block_builder_test.rs index 1bb5583928..cfa017478c 100644 --- a/crates/starknet_batcher/src/block_builder_test.rs +++ b/crates/starknet_batcher/src/block_builder_test.rs @@ -5,13 +5,13 @@ use blockifier::fee::fee_checks::FeeCheckError; use blockifier::state::errors::StateError; use blockifier::transaction::objects::{RevertError, TransactionExecutionInfo}; use blockifier::transaction::transaction_execution::Transaction as BlockifierTransaction; -use indexmap::{indexmap, IndexMap}; -use mockall::predicate::eq; +use indexmap::{IndexMap, indexmap}; use mockall::Sequence; +use mockall::predicate::eq; use rstest::rstest; use starknet_api::executable_transaction::Transaction; -use starknet_api::transaction::fields::Fee; use starknet_api::transaction::TransactionHash; +use starknet_api::transaction::fields::Fee; use starknet_api::tx_hash; use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender}; diff --git a/crates/starknet_batcher/src/config.rs b/crates/starknet_batcher/src/config.rs index b25c2d7ea1..e0c4a06188 100644 --- a/crates/starknet_batcher/src/config.rs +++ b/crates/starknet_batcher/src/config.rs @@ -1,6 +1,6 @@ use std::collections::BTreeMap; -use papyrus_config::dumping::{append_sub_config_name, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use serde::{Deserialize, Serialize}; use validator::{Validate, ValidationError}; diff --git a/crates/starknet_batcher/src/fee_market.rs b/crates/starknet_batcher/src/fee_market.rs index 3f55adb174..71cba26a49 100644 --- a/crates/starknet_batcher/src/fee_market.rs +++ b/crates/starknet_batcher/src/fee_market.rs @@ -9,7 +9,7 @@ pub mod fee_market_test; // between consecutive blocks. const GAS_PRICE_MAX_CHANGE_DENOMINATOR: u128 = 48; const MIN_GAS_PRICE: u64 = 100000; // In fri. - // TODO(Mohammad): Check the exact value for maximum block size in StarkNet. +// TODO(Mohammad): Check the exact value for maximum block size in StarkNet. const MAX_BLOCK_SIZE: u64 = 4000000000; // In gas units. It's equivalent to 40M gas steps, with 100 gas units per step. /// Calculate the base gas price for the next block according to EIP-1559. diff --git a/crates/starknet_batcher/src/fee_market_test.rs b/crates/starknet_batcher/src/fee_market_test.rs index c478184000..81bca49866 100644 --- a/crates/starknet_batcher/src/fee_market_test.rs +++ b/crates/starknet_batcher/src/fee_market_test.rs @@ -1,5 +1,5 @@ use crate::fee_market::{ - calculate_next_base_gas_price, GAS_PRICE_MAX_CHANGE_DENOMINATOR, MAX_BLOCK_SIZE, MIN_GAS_PRICE, + GAS_PRICE_MAX_CHANGE_DENOMINATOR, MAX_BLOCK_SIZE, MIN_GAS_PRICE, calculate_next_base_gas_price, }; #[test] diff --git a/crates/starknet_batcher/src/proposal_manager.rs b/crates/starknet_batcher/src/proposal_manager.rs index 038879facd..fb744f5a79 100644 --- a/crates/starknet_batcher/src/proposal_manager.rs +++ b/crates/starknet_batcher/src/proposal_manager.rs @@ -10,7 +10,7 @@ use starknet_api::transaction::TransactionHash; use starknet_batcher_types::batcher_types::{ProposalCommitment, ProposalId}; use thiserror::Error; use tokio::sync::Mutex; -use tracing::{debug, error, info, instrument, Instrument}; +use tracing::{Instrument, debug, error, info, instrument}; use crate::block_builder::{BlockBuilderError, BlockBuilderTrait, BlockExecutionArtifacts}; diff --git a/crates/starknet_batcher/src/test_utils.rs b/crates/starknet_batcher/src/test_utils.rs index 73f251de03..dddf39d75f 100644 --- a/crates/starknet_batcher/src/test_utils.rs +++ b/crates/starknet_batcher/src/test_utils.rs @@ -5,7 +5,7 @@ use blockifier::bouncer::BouncerWeights; use blockifier::state::cached_state::CommitmentStateDiff; use indexmap::IndexMap; use starknet_api::executable_transaction::Transaction; -use starknet_api::test_utils::invoke::{executable_invoke_tx, InvokeTxArgs}; +use starknet_api::test_utils::invoke::{InvokeTxArgs, executable_invoke_tx}; use starknet_api::tx_hash; use crate::block_builder::BlockExecutionArtifacts; diff --git a/crates/starknet_batcher/src/transaction_provider_test.rs b/crates/starknet_batcher/src/transaction_provider_test.rs index 2c56376639..afc457571d 100644 --- a/crates/starknet_batcher/src/transaction_provider_test.rs +++ b/crates/starknet_batcher/src/transaction_provider_test.rs @@ -4,7 +4,7 @@ use assert_matches::assert_matches; use mockall::predicate::eq; use rstest::{fixture, rstest}; use starknet_api::executable_transaction::{L1HandlerTransaction, Transaction}; -use starknet_api::test_utils::invoke::{executable_invoke_tx, InvokeTxArgs}; +use starknet_api::test_utils::invoke::{InvokeTxArgs, executable_invoke_tx}; use starknet_api::tx_hash; use starknet_mempool_types::communication::MockMempoolClient; @@ -139,12 +139,16 @@ async fn no_more_l1_handler(mut mock_dependencies: MockDependencies) { let txs = tx_provider.get_txs(MAX_TXS_PER_FETCH).await.unwrap(); let data = assert_matches!(txs, NextTxs::Txs(txs) if txs.len() == MAX_TXS_PER_FETCH => txs); - assert!(data[..NUM_L1_HANDLER_TXS_IN_PROVIDER] - .iter() - .all(|tx| matches!(tx, Transaction::L1Handler(_)))); - assert!(data[NUM_L1_HANDLER_TXS_IN_PROVIDER..] - .iter() - .all(|tx| { matches!(tx, Transaction::Account(_)) })); + assert!( + data[..NUM_L1_HANDLER_TXS_IN_PROVIDER] + .iter() + .all(|tx| matches!(tx, Transaction::L1Handler(_))) + ); + assert!( + data[NUM_L1_HANDLER_TXS_IN_PROVIDER..] + .iter() + .all(|tx| { matches!(tx, Transaction::Account(_)) }) + ); let txs = tx_provider.get_txs(MAX_TXS_PER_FETCH).await.unwrap(); let data = assert_matches!(txs, NextTxs::Txs(txs) if txs.len() == MAX_TXS_PER_FETCH => txs); diff --git a/crates/starknet_client/src/reader/mod.rs b/crates/starknet_client/src/reader/mod.rs index 33eff936de..00ea02358b 100644 --- a/crates/starknet_client/src/reader/mod.rs +++ b/crates/starknet_client/src/reader/mod.rs @@ -16,11 +16,11 @@ use cairo_lang_starknet_classes::casm_contract_class::{ use mockall::automock; use papyrus_common::pending_classes::ApiContractClass; use serde::{Deserialize, Serialize}; +use starknet_api::StarknetApiError; use starknet_api::block::BlockNumber; use starknet_api::core::{ClassHash, SequencerPublicKey}; use starknet_api::deprecated_contract_class::ContractClass as DeprecatedContractClass; use starknet_api::transaction::TransactionHash; -use starknet_api::StarknetApiError; use starknet_types_core::felt::Felt; use tracing::{debug, error, instrument}; use url::Url; diff --git a/crates/starknet_client/src/reader/objects/block_test.rs b/crates/starknet_client/src/reader/objects/block_test.rs index 4015cc6d51..712f99cc6e 100644 --- a/crates/starknet_client/src/reader/objects/block_test.rs +++ b/crates/starknet_client/src/reader/objects/block_test.rs @@ -8,12 +8,12 @@ use starknet_api::transaction::TransactionOffsetInBlock; use starknet_api::{class_hash, contract_address, felt, storage_key, tx_hash}; use super::{Block, GlobalRoot, TransactionReceiptsError}; +use crate::reader::ReaderClientError; use crate::reader::objects::block::BlockPostV0_13_1; use crate::reader::objects::state::{ DeclaredClassHashEntry, DeployedContract, ReplacedClass, StateDiff, StateUpdate, StorageEntry, }; use crate::reader::objects::transaction::TransactionReceipt; -use crate::reader::ReaderClientError; use crate::test_utils::read_resource::read_resource_file; #[test] diff --git a/crates/starknet_client/src/reader/objects/test_utils.rs b/crates/starknet_client/src/reader/objects/test_utils.rs index d30cd9427c..12e21be98d 100644 --- a/crates/starknet_client/src/reader/objects/test_utils.rs +++ b/crates/starknet_client/src/reader/objects/test_utils.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use papyrus_test_utils::{auto_impl_get_test_instance, get_number_of_variants, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, auto_impl_get_test_instance, get_number_of_variants}; use starknet_api::contract_class::EntryPointType; use starknet_api::core::{ ClassHash, CompiledClassHash, ContractAddress, EntryPointSelector, EthAddress, Nonce, diff --git a/crates/starknet_client/src/reader/starknet_feeder_gateway_client_test.rs b/crates/starknet_client/src/reader/starknet_feeder_gateway_client_test.rs index c27f927591..69d976f96c 100644 --- a/crates/starknet_client/src/reader/starknet_feeder_gateway_client_test.rs +++ b/crates/starknet_client/src/reader/starknet_feeder_gateway_client_test.rs @@ -24,12 +24,12 @@ use starknet_api::{class_hash, contract_address, felt, nonce}; use super::objects::state::StateUpdate; use super::objects::transaction::IntermediateDeclareTransaction; use super::{ - ContractClass, GenericContractClass, PendingData, ReaderClientError, ReaderClientResult, - StarknetFeederGatewayClient, StarknetReader, BLOCK_NUMBER_QUERY, CLASS_HASH_QUERY, - GET_BLOCK_URL, GET_STATE_UPDATE_URL, + BLOCK_NUMBER_QUERY, CLASS_HASH_QUERY, ContractClass, GET_BLOCK_URL, GET_STATE_UPDATE_URL, + GenericContractClass, PendingData, ReaderClientError, ReaderClientResult, + StarknetFeederGatewayClient, StarknetReader, }; -use crate::reader::objects::block::{BlockSignatureData, BlockSignatureMessage}; use crate::reader::Block; +use crate::reader::objects::block::{BlockSignatureData, BlockSignatureMessage}; use crate::test_utils::read_resource::read_resource_file; use crate::test_utils::retry::get_test_config; @@ -157,25 +157,21 @@ async fn contract_class() { ) .unwrap(); let expected_contract_class = ContractClass { - sierra_program: vec![ - felt!("0x302e312e30"), - felt!("0x1c"), - felt!("0x52616e6765436865636b"), - ], - entry_points_by_type: HashMap::from([( - EntryPointType::External, - vec! [EntryPoint { + sierra_program: vec![felt!("0x302e312e30"), felt!("0x1c"), felt!("0x52616e6765436865636b")], + entry_points_by_type: HashMap::from([ + (EntryPointType::External, vec![EntryPoint { function_idx: FunctionIndex(0), selector: EntryPointSelector(felt!( "0x22ff5f21f0b81b113e63f7db6da94fedef11b2119b4088b89664fb9a3cb658" )), - }], - ), - (EntryPointType::Constructor, vec![]), - (EntryPointType::L1Handler, vec![]), + }]), + (EntryPointType::Constructor, vec![]), + (EntryPointType::L1Handler, vec![]), ]), contract_class_version: String::from("0.1.0"), - abi: String::from("[\n {\n \"type\": \"function\",\n \"name\": \"test\",\n \"inputs\": [\n {\n \"name\": \"arg\",\n \"ty\": \"core::felt\"\n },\n {\n \"name\": \"arg1\",\n \"ty\": \"core::felt\"\n },\n {\n \"name\": \"arg2\",\n \"ty\": \"core::felt\"\n }\n ],\n \"output_ty\": \"core::felt\",\n \"state_mutability\": \"external\"\n },\n {\n \"type\": \"function\",\n \"name\": \"empty\",\n \"inputs\": [],\n \"output_ty\": \"()\",\n \"state_mutability\": \"external\"\n },\n {\n \"type\": \"function\",\n \"name\": \"call_foo\",\n \"inputs\": [\n {\n \"name\": \"a\",\n \"ty\": \"core::integer::u128\"\n }\n ],\n \"output_ty\": \"core::integer::u128\",\n \"state_mutability\": \"external\"\n }\n]"), + abi: String::from( + "[\n {\n \"type\": \"function\",\n \"name\": \"test\",\n \"inputs\": [\n {\n \"name\": \"arg\",\n \"ty\": \"core::felt\"\n },\n {\n \"name\": \"arg1\",\n \"ty\": \"core::felt\"\n },\n {\n \"name\": \"arg2\",\n \"ty\": \"core::felt\"\n }\n ],\n \"output_ty\": \"core::felt\",\n \"state_mutability\": \"external\"\n },\n {\n \"type\": \"function\",\n \"name\": \"empty\",\n \"inputs\": [],\n \"output_ty\": \"()\",\n \"state_mutability\": \"external\"\n },\n {\n \"type\": \"function\",\n \"name\": \"call_foo\",\n \"inputs\": [\n {\n \"name\": \"a\",\n \"ty\": \"core::integer::u128\"\n }\n ],\n \"output_ty\": \"core::integer::u128\",\n \"state_mutability\": \"external\"\n }\n]", + ), }; let mock_by_hash = mock( @@ -244,24 +240,18 @@ async fn deprecated_contract_class() { }, entry_points_by_type: HashMap::from([ (EntryPointType::L1Handler, vec![]), - ( - EntryPointType::Constructor, - vec![DeprecatedEntryPoint { - selector: EntryPointSelector(felt!( - "0x028ffe4ff0f226a9107253e17a904099aa4f63a02a5621de0576e5aa71bc5194" - )), - offset: EntryPointOffset(62), - }], - ), - ( - EntryPointType::External, - vec![DeprecatedEntryPoint { - selector: EntryPointSelector(felt!( - "0x0000000000000000000000000000000000000000000000000000000000000000" - )), - offset: EntryPointOffset(86), - }], - ), + (EntryPointType::Constructor, vec![DeprecatedEntryPoint { + selector: EntryPointSelector(felt!( + "0x028ffe4ff0f226a9107253e17a904099aa4f63a02a5621de0576e5aa71bc5194" + )), + offset: EntryPointOffset(62), + }]), + (EntryPointType::External, vec![DeprecatedEntryPoint { + selector: EntryPointSelector(felt!( + "0x0000000000000000000000000000000000000000000000000000000000000000" + )), + offset: EntryPointOffset(86), + }]), ]), }; let mock_by_hash = mock( diff --git a/crates/starknet_client/src/retry.rs b/crates/starknet_client/src/retry.rs index bbebc9bd39..ba4e949ef7 100644 --- a/crates/starknet_client/src/retry.rs +++ b/crates/starknet_client/src/retry.rs @@ -7,7 +7,7 @@ use std::fmt::Debug; use std::iter::Take; use std::time::Duration; -use papyrus_config::dumping::{ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use serde::{Deserialize, Serialize}; use tokio_retry::strategy::ExponentialBackoff; diff --git a/crates/starknet_client/src/retry_test.rs b/crates/starknet_client/src/retry_test.rs index 6da469004d..7686bd32f6 100644 --- a/crates/starknet_client/src/retry_test.rs +++ b/crates/starknet_client/src/retry_test.rs @@ -28,11 +28,7 @@ impl Worker { let mut number_of_calls = self.number_of_calls.lock().unwrap(); *number_of_calls += 1; - if *number_of_calls <= *self.number_of_errors { - Err("Some error.") - } else { - Ok(()) - } + if *number_of_calls <= *self.number_of_errors { Err("Some error.") } else { Ok(()) } } } diff --git a/crates/starknet_client/src/starknet_client_test.rs b/crates/starknet_client/src/starknet_client_test.rs index 1c7fad3d90..767cdb9e6f 100644 --- a/crates/starknet_client/src/starknet_client_test.rs +++ b/crates/starknet_client/src/starknet_client_test.rs @@ -3,7 +3,7 @@ use mockito::mock; use reqwest::StatusCode; use crate::starknet_error::{KnownStarknetErrorCode, StarknetError, StarknetErrorCode}; -use crate::test_utils::retry::{get_test_config, MAX_RETRIES}; +use crate::test_utils::retry::{MAX_RETRIES, get_test_config}; use crate::{ClientError, RetryErrorCode, StarknetClient}; const NODE_VERSION: &str = "NODE VERSION"; diff --git a/crates/starknet_client/src/writer/objects/test_utils.rs b/crates/starknet_client/src/writer/objects/test_utils.rs index a75a012e37..b4b24e8e52 100644 --- a/crates/starknet_client/src/writer/objects/test_utils.rs +++ b/crates/starknet_client/src/writer/objects/test_utils.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use papyrus_test_utils::{auto_impl_get_test_instance, get_number_of_variants, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, auto_impl_get_test_instance, get_number_of_variants}; use starknet_api::contract_class::EntryPointType; use starknet_api::core::{ClassHash, ContractAddress}; use starknet_api::deprecated_contract_class::{ diff --git a/crates/starknet_client/src/writer/objects/transaction.rs b/crates/starknet_client/src/writer/objects/transaction.rs index 689ce41fd6..2458998d0e 100644 --- a/crates/starknet_client/src/writer/objects/transaction.rs +++ b/crates/starknet_client/src/writer/objects/transaction.rs @@ -22,11 +22,11 @@ use starknet_api::deprecated_contract_class::{ ContractClassAbiEntry as DeprecatedContractClassAbiEntry, EntryPointV0 as DeprecatedEntryPoint, }; use starknet_api::state::EntryPoint; +use starknet_api::transaction::TransactionVersion; use starknet_api::transaction::fields::{ AccountDeploymentData, Calldata, ContractAddressSalt, DeprecatedResourceBoundsMapping, Fee, PaymasterData, Tip, TransactionSignature, }; -use starknet_api::transaction::TransactionVersion; // Each transaction type has a field called `type`. This field needs to be of a type that // serializes to/deserializes from a constant string. diff --git a/crates/starknet_client/src/writer/starknet_gateway_client_test.rs b/crates/starknet_client/src/writer/starknet_gateway_client_test.rs index 399634b9f6..518ac68a56 100644 --- a/crates/starknet_client/src/writer/starknet_gateway_client_test.rs +++ b/crates/starknet_client/src/writer/starknet_gateway_client_test.rs @@ -1,7 +1,7 @@ use std::fmt::Debug; use std::future::Future; -use mockito::{mock, Matcher}; +use mockito::{Matcher, mock}; use serde::{Deserialize, Serialize}; use starknet_api::test_utils::read_json_file; diff --git a/crates/starknet_committer/src/forest/filled_forest.rs b/crates/starknet_committer/src/forest/filled_forest.rs index 404209f8e4..d4597a01aa 100644 --- a/crates/starknet_committer/src/forest/filled_forest.rs +++ b/crates/starknet_committer/src/forest/filled_forest.rs @@ -131,22 +131,19 @@ impl FilledForest { let original_contract_state = original_contracts_trie_leaves .get(&node_index) .ok_or(ForestError::MissingContractCurrentState(contract_address))?; - leaf_index_to_leaf_input.insert( - node_index, - ContractStateInput { - leaf_index: node_index, - nonce: *(address_to_nonce - .get(&contract_address) - .unwrap_or(&original_contract_state.nonce)), - class_hash: *(address_to_class_hash - .get(&contract_address) - .unwrap_or(&original_contract_state.class_hash)), - updated_skeleton: contract_address_to_storage_skeleton - .remove(&contract_address) - .ok_or(ForestError::MissingUpdatedSkeleton(contract_address))?, - storage_updates, - }, - ); + leaf_index_to_leaf_input.insert(node_index, ContractStateInput { + leaf_index: node_index, + nonce: *(address_to_nonce + .get(&contract_address) + .unwrap_or(&original_contract_state.nonce)), + class_hash: *(address_to_class_hash + .get(&contract_address) + .unwrap_or(&original_contract_state.class_hash)), + updated_skeleton: contract_address_to_storage_skeleton + .remove(&contract_address) + .ok_or(ForestError::MissingUpdatedSkeleton(contract_address))?, + storage_updates, + }); } Ok(leaf_index_to_leaf_input) } diff --git a/crates/starknet_consensus_manager/src/config.rs b/crates/starknet_consensus_manager/src/config.rs index 84ca95dfd2..eb85bee098 100644 --- a/crates/starknet_consensus_manager/src/config.rs +++ b/crates/starknet_consensus_manager/src/config.rs @@ -1,6 +1,6 @@ use std::collections::BTreeMap; -use papyrus_config::dumping::{append_sub_config_name, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name}; use papyrus_config::{ParamPath, SerializedParam}; use papyrus_consensus::config::ConsensusConfig; use serde::{Deserialize, Serialize}; diff --git a/crates/starknet_gateway/src/compilation.rs b/crates/starknet_gateway/src/compilation.rs index b446aa7fb0..caa068313b 100644 --- a/crates/starknet_gateway/src/compilation.rs +++ b/crates/starknet_gateway/src/compilation.rs @@ -5,10 +5,10 @@ use cairo_lang_starknet_classes::contract_class::ContractClass as CairoLangContr use starknet_api::contract_class::{ClassInfo, ContractClass, SierraVersion}; use starknet_api::rpc_transaction::RpcDeclareTransaction; use starknet_gateway_types::errors::GatewaySpecError; +use starknet_sierra_compile::SierraToCasmCompiler; use starknet_sierra_compile::command_line_compiler::CommandLineCompiler; use starknet_sierra_compile::config::SierraToCasmCompilationConfig; use starknet_sierra_compile::utils::into_contract_class_for_compilation; -use starknet_sierra_compile::SierraToCasmCompiler; use tracing::{debug, error}; use crate::errors::GatewayResult; diff --git a/crates/starknet_gateway/src/compilation_test.rs b/crates/starknet_gateway/src/compilation_test.rs index 41bff119e2..3d5d4de860 100644 --- a/crates/starknet_gateway/src/compilation_test.rs +++ b/crates/starknet_gateway/src/compilation_test.rs @@ -1,6 +1,6 @@ use assert_matches::assert_matches; use mempool_test_utils::starknet_api_test_utils::{ - declare_tx as rpc_declare_tx, COMPILED_CLASS_HASH, + COMPILED_CLASS_HASH, declare_tx as rpc_declare_tx, }; use rstest::{fixture, rstest}; use starknet_api::rpc_transaction::{ diff --git a/crates/starknet_gateway/src/compiler_version.rs b/crates/starknet_gateway/src/compiler_version.rs index ce6fa55c23..1fa7ba75e2 100644 --- a/crates/starknet_gateway/src/compiler_version.rs +++ b/crates/starknet_gateway/src/compiler_version.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; use cairo_lang_starknet_classes::compiler_version::VersionId as CairoLangVersionId; use cairo_lang_starknet_classes::contract_class::version_id_from_serialized_sierra_program; -use papyrus_config::dumping::{ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use serde::{Deserialize, Serialize}; use starknet_sierra_compile::utils::sierra_program_as_felts_to_big_uint_as_hex; diff --git a/crates/starknet_gateway/src/config.rs b/crates/starknet_gateway/src/config.rs index f0e02aee90..97dd39a45f 100644 --- a/crates/starknet_gateway/src/config.rs +++ b/crates/starknet_gateway/src/config.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; use blockifier::context::ChainInfo; use blockifier::versioned_constants::VersionedConstantsOverrides; -use papyrus_config::dumping::{append_sub_config_name, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use serde::{Deserialize, Serialize}; use starknet_api::core::Nonce; diff --git a/crates/starknet_gateway/src/errors.rs b/crates/starknet_gateway/src/errors.rs index fec0a49de4..819cc09980 100644 --- a/crates/starknet_gateway/src/errors.rs +++ b/crates/starknet_gateway/src/errors.rs @@ -1,9 +1,9 @@ use axum::http::StatusCode; use blockifier::state::errors::StateError; use serde_json::{Error as SerdeError, Value}; +use starknet_api::StarknetApiError; use starknet_api::block::GasPrice; use starknet_api::transaction::fields::{Resource, ResourceBounds}; -use starknet_api::StarknetApiError; use starknet_gateway_types::errors::GatewaySpecError; use thiserror::Error; diff --git a/crates/starknet_gateway/src/gateway.rs b/crates/starknet_gateway/src/gateway.rs index 5c720b7247..8056847f41 100644 --- a/crates/starknet_gateway/src/gateway.rs +++ b/crates/starknet_gateway/src/gateway.rs @@ -11,7 +11,7 @@ use starknet_mempool_types::communication::{AddTransactionArgsWrapper, SharedMem use starknet_mempool_types::mempool_types::{AccountState, AddTransactionArgs}; use starknet_sequencer_infra::component_definitions::ComponentStarter; use starknet_sierra_compile::config::SierraToCasmCompilationConfig; -use tracing::{error, instrument, Span}; +use tracing::{Span, error, instrument}; use crate::compilation::GatewayCompiler; use crate::config::{GatewayConfig, RpcStateReaderConfig}; diff --git a/crates/starknet_gateway/src/gateway_test.rs b/crates/starknet_gateway/src/gateway_test.rs index 7460738e0d..8acb4b0302 100644 --- a/crates/starknet_gateway/src/gateway_test.rs +++ b/crates/starknet_gateway/src/gateway_test.rs @@ -6,7 +6,7 @@ use blockifier::test_utils::{CairoVersion, RunnableCairo1}; use mempool_test_utils::starknet_api_test_utils::{declare_tx, invoke_tx}; use mockall::predicate::eq; use papyrus_network_types::network_types::BroadcastedMessageMetadata; -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use rstest::{fixture, rstest}; use starknet_api::core::{ChainId, CompiledClassHash, ContractAddress}; use starknet_api::executable_transaction::{AccountTransaction, InvokeTransaction}; @@ -21,7 +21,7 @@ use crate::config::{ GatewayConfig, StatefulTransactionValidatorConfig, StatelessTransactionValidatorConfig, }; use crate::gateway::Gateway; -use crate::state_reader_test_utils::{local_test_state_reader_factory, TestStateReaderFactory}; +use crate::state_reader_test_utils::{TestStateReaderFactory, local_test_state_reader_factory}; #[fixture] fn config() -> GatewayConfig { diff --git a/crates/starknet_gateway/src/rpc_state_reader.rs b/crates/starknet_gateway/src/rpc_state_reader.rs index 7a2c7292e6..b1449794ff 100644 --- a/crates/starknet_gateway/src/rpc_state_reader.rs +++ b/crates/starknet_gateway/src/rpc_state_reader.rs @@ -6,18 +6,18 @@ use blockifier::state::state_api::{StateReader as BlockifierStateReader, StateRe use papyrus_rpc::CompiledContractClass; use reqwest::blocking::Client as BlockingClient; use serde::Serialize; -use serde_json::{json, Value}; +use serde_json::{Value, json}; use starknet_api::block::{BlockInfo, BlockNumber}; use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce}; use starknet_api::state::StorageKey; use starknet_types_core::felt::Felt; use crate::config::RpcStateReaderConfig; -use crate::errors::{serde_err_to_state_err, RPCStateReaderError, RPCStateReaderResult}; +use crate::errors::{RPCStateReaderError, RPCStateReaderResult, serde_err_to_state_err}; use crate::rpc_objects::{ BlockHeader, BlockId, GetBlockWithTxHashesParams, GetClassHashAtParams, GetCompiledClassParams, - GetNonceParams, GetStorageAtParams, RpcResponse, RPC_CLASS_HASH_NOT_FOUND, - RPC_ERROR_BLOCK_NOT_FOUND, RPC_ERROR_CONTRACT_ADDRESS_NOT_FOUND, RPC_ERROR_INVALID_PARAMS, + GetNonceParams, GetStorageAtParams, RPC_CLASS_HASH_NOT_FOUND, RPC_ERROR_BLOCK_NOT_FOUND, + RPC_ERROR_CONTRACT_ADDRESS_NOT_FOUND, RPC_ERROR_INVALID_PARAMS, RpcResponse, }; use crate::state_reader::{MempoolStateReader, StateReaderFactory}; diff --git a/crates/starknet_gateway/src/state_reader_test_utils.rs b/crates/starknet_gateway/src/state_reader_test_utils.rs index 80c8fc8b51..0640313d19 100644 --- a/crates/starknet_gateway/src/state_reader_test_utils.rs +++ b/crates/starknet_gateway/src/state_reader_test_utils.rs @@ -5,7 +5,7 @@ use blockifier::state::state_api::{StateReader as BlockifierStateReader, StateRe use blockifier::test_utils::contracts::FeatureContract; use blockifier::test_utils::dict_state_reader::DictStateReader; use blockifier::test_utils::initial_test_state::test_state; -use blockifier::test_utils::{CairoVersion, BALANCE}; +use blockifier::test_utils::{BALANCE, CairoVersion}; use starknet_api::block::{BlockInfo, BlockNumber}; use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce}; use starknet_api::state::StorageKey; @@ -75,11 +75,10 @@ pub fn local_test_state_reader_factory( let account_contract = FeatureContract::AccountWithoutValidations(cairo_version); let test_contract = FeatureContract::TestContract(cairo_version); - let state_reader = test_state( - block_context.chain_info(), - account_balance, - &[(account_contract, 1), (test_contract, 1)], - ); + let state_reader = test_state(block_context.chain_info(), account_balance, &[ + (account_contract, 1), + (test_contract, 1), + ]); TestStateReaderFactory { state_reader: TestStateReader { diff --git a/crates/starknet_gateway/src/stateful_transaction_validator_test.rs b/crates/starknet_gateway/src/stateful_transaction_validator_test.rs index 71594af5e7..c5462f212f 100644 --- a/crates/starknet_gateway/src/stateful_transaction_validator_test.rs +++ b/crates/starknet_gateway/src/stateful_transaction_validator_test.rs @@ -6,8 +6,8 @@ use blockifier::context::ChainInfo; use blockifier::test_utils::{CairoVersion, RunnableCairo1}; use blockifier::transaction::errors::{TransactionFeeError, TransactionPreValidationError}; use mempool_test_utils::starknet_api_test_utils::{ - executable_invoke_tx as create_executable_invoke_tx, VALID_L1_GAS_MAX_AMOUNT, - VALID_L1_GAS_MAX_PRICE_PER_UNIT, + VALID_L1_GAS_MAX_AMOUNT, VALID_L1_GAS_MAX_PRICE_PER_UNIT, + executable_invoke_tx as create_executable_invoke_tx, }; use mockall::predicate::eq; use num_bigint::BigUint; @@ -17,10 +17,10 @@ use starknet_api::block::GasPrice; use starknet_api::core::Nonce; use starknet_api::executable_transaction::AccountTransaction; use starknet_api::execution_resources::GasAmount; +use starknet_api::test_utils::NonceManager; use starknet_api::test_utils::declare::TEST_SENDER_ADDRESS; use starknet_api::test_utils::deploy_account::executable_deploy_account_tx; use starknet_api::test_utils::invoke::executable_invoke_tx; -use starknet_api::test_utils::NonceManager; use starknet_api::transaction::fields::Resource; use starknet_api::{deploy_account_tx_args, invoke_tx_args, nonce}; use starknet_gateway_types::errors::GatewaySpecError; diff --git a/crates/starknet_gateway/src/stateless_transaction_validator.rs b/crates/starknet_gateway/src/stateless_transaction_validator.rs index 019cb70713..499fb42e19 100644 --- a/crates/starknet_gateway/src/stateless_transaction_validator.rs +++ b/crates/starknet_gateway/src/stateless_transaction_validator.rs @@ -7,7 +7,7 @@ use starknet_api::rpc_transaction::{ use starknet_api::state::EntryPoint; use starknet_api::transaction::fields::{AllResourceBounds, Resource}; use starknet_types_core::felt::Felt; -use tracing::{instrument, Level}; +use tracing::{Level, instrument}; use crate::compiler_version::VersionId; use crate::config::StatelessTransactionValidatorConfig; diff --git a/crates/starknet_gateway/src/stateless_transaction_validator_test.rs b/crates/starknet_gateway/src/stateless_transaction_validator_test.rs index a927c17ee5..2087dfd352 100644 --- a/crates/starknet_gateway/src/stateless_transaction_validator_test.rs +++ b/crates/starknet_gateway/src/stateless_transaction_validator_test.rs @@ -12,7 +12,7 @@ use starknet_api::transaction::fields::{ AccountDeploymentData, AllResourceBounds, PaymasterData, Resource, ResourceBounds, TransactionSignature, }; -use starknet_api::{calldata, contract_address, declare_tx_args, felt, StarknetApiError}; +use starknet_api::{StarknetApiError, calldata, contract_address, declare_tx_args, felt}; use starknet_types_core::felt::Felt; use crate::compiler_version::{VersionId, VersionIdError}; @@ -22,8 +22,8 @@ use crate::stateless_transaction_validator::{ StatelessTransactionValidator, StatelessTransactionValidatorError, }; use crate::test_utils::{ - create_sierra_program, rpc_tx_for_testing, RpcTransactionArgs, TransactionType, - NON_EMPTY_RESOURCE_BOUNDS, + NON_EMPTY_RESOURCE_BOUNDS, RpcTransactionArgs, TransactionType, create_sierra_program, + rpc_tx_for_testing, }; static MIN_SIERRA_VERSION: LazyLock = LazyLock::new(|| VersionId::new(1, 1, 0)); diff --git a/crates/starknet_gateway/src/test_utils.rs b/crates/starknet_gateway/src/test_utils.rs index f15a242067..b80f7adb04 100644 --- a/crates/starknet_gateway/src/test_utils.rs +++ b/crates/starknet_gateway/src/test_utils.rs @@ -4,7 +4,7 @@ use starknet_api::data_availability::DataAvailabilityMode; use starknet_api::execution_resources::GasAmount; use starknet_api::rpc_transaction::RpcTransaction; use starknet_api::state::SierraContractClass; -use starknet_api::test_utils::declare::{rpc_declare_tx, TEST_SENDER_ADDRESS}; +use starknet_api::test_utils::declare::{TEST_SENDER_ADDRESS, rpc_declare_tx}; use starknet_api::test_utils::deploy_account::rpc_deploy_account_tx; use starknet_api::test_utils::invoke::rpc_invoke_tx; use starknet_api::transaction::fields::{ diff --git a/crates/starknet_gateway_types/src/errors.rs b/crates/starknet_gateway_types/src/errors.rs index cc75a76a27..c8f3cc32f8 100644 --- a/crates/starknet_gateway_types/src/errors.rs +++ b/crates/starknet_gateway_types/src/errors.rs @@ -3,11 +3,11 @@ use axum::response::{IntoResponse, Response}; use enum_assoc::Assoc; use papyrus_network_types::network_types::BroadcastedMessageMetadata; use papyrus_rpc::error::{ - unexpected_error, validation_failure, JsonRpcError, CLASS_ALREADY_DECLARED, - CLASS_HASH_NOT_FOUND, COMPILATION_FAILED, COMPILED_CLASS_HASH_MISMATCH, + CLASS_ALREADY_DECLARED, CLASS_HASH_NOT_FOUND, COMPILATION_FAILED, COMPILED_CLASS_HASH_MISMATCH, CONTRACT_CLASS_SIZE_IS_TOO_LARGE, DUPLICATE_TX, INSUFFICIENT_ACCOUNT_BALANCE, - INSUFFICIENT_MAX_FEE, INVALID_TRANSACTION_NONCE, NON_ACCOUNT, - UNSUPPORTED_CONTRACT_CLASS_VERSION, UNSUPPORTED_TX_VERSION, + INSUFFICIENT_MAX_FEE, INVALID_TRANSACTION_NONCE, JsonRpcError, NON_ACCOUNT, + UNSUPPORTED_CONTRACT_CLASS_VERSION, UNSUPPORTED_TX_VERSION, unexpected_error, + validation_failure, }; use serde::{Deserialize, Serialize}; use thiserror::Error; diff --git a/crates/starknet_http_server/src/config.rs b/crates/starknet_http_server/src/config.rs index 905281f7a0..206507b5ff 100644 --- a/crates/starknet_http_server/src/config.rs +++ b/crates/starknet_http_server/src/config.rs @@ -1,7 +1,7 @@ use std::collections::BTreeMap; use std::net::IpAddr; -use papyrus_config::dumping::{ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use serde::{Deserialize, Serialize}; use validator::Validate; diff --git a/crates/starknet_http_server/src/http_server.rs b/crates/starknet_http_server/src/http_server.rs index 5ebd88c26b..c1677a1873 100644 --- a/crates/starknet_http_server/src/http_server.rs +++ b/crates/starknet_http_server/src/http_server.rs @@ -4,7 +4,7 @@ use std::net::SocketAddr; use axum::extract::State; use axum::routing::post; -use axum::{async_trait, Json, Router}; +use axum::{Json, Router, async_trait}; use starknet_api::rpc_transaction::RpcTransaction; use starknet_api::transaction::TransactionHash; use starknet_gateway_types::communication::SharedGatewayClient; diff --git a/crates/starknet_integration_tests/src/config_utils.rs b/crates/starknet_integration_tests/src/config_utils.rs index d9882eba8f..32e4468084 100644 --- a/crates/starknet_integration_tests/src/config_utils.rs +++ b/crates/starknet_integration_tests/src/config_utils.rs @@ -3,7 +3,7 @@ use std::io::Write; use std::net::SocketAddr; use std::path::PathBuf; -use serde_json::{json, Value}; +use serde_json::{Value, json}; use starknet_sequencer_infra::component_definitions::{ LocalServerConfig, RemoteClientConfig, RemoteServerConfig, }; diff --git a/crates/starknet_integration_tests/src/flow_test_setup.rs b/crates/starknet_integration_tests/src/flow_test_setup.rs index 3515aacb05..92f26a186e 100644 --- a/crates/starknet_integration_tests/src/flow_test_setup.rs +++ b/crates/starknet_integration_tests/src/flow_test_setup.rs @@ -19,7 +19,7 @@ use tokio::runtime::Handle; use tokio::task::JoinHandle; use tracing::{debug, instrument}; -use crate::state_reader::{spawn_test_rpc_state_reader, StorageTestSetup}; +use crate::state_reader::{StorageTestSetup, spawn_test_rpc_state_reader}; use crate::utils::{ create_chain_info, create_config, create_consensus_manager_configs_and_channels, }; diff --git a/crates/starknet_integration_tests/src/integration_test_setup.rs b/crates/starknet_integration_tests/src/integration_test_setup.rs index 5483a0f3f5..ac43378591 100644 --- a/crates/starknet_integration_tests/src/integration_test_setup.rs +++ b/crates/starknet_integration_tests/src/integration_test_setup.rs @@ -7,10 +7,10 @@ use starknet_http_server::config::HttpServerConfig; use starknet_http_server::test_utils::HttpTestClient; use starknet_monitoring_endpoint::config::MonitoringEndpointConfig; use starknet_monitoring_endpoint::test_utils::IsAliveClient; -use tempfile::{tempdir, TempDir}; +use tempfile::{TempDir, tempdir}; use crate::config_utils::dump_config_file_changes; -use crate::state_reader::{spawn_test_rpc_state_reader, StorageTestSetup}; +use crate::state_reader::{StorageTestSetup, spawn_test_rpc_state_reader}; use crate::utils::{ create_chain_info, create_config, create_consensus_manager_configs_and_channels, }; diff --git a/crates/starknet_integration_tests/src/state_reader.rs b/crates/starknet_integration_tests/src/state_reader.rs index 17dda98019..e440fb98ab 100644 --- a/crates/starknet_integration_tests/src/state_reader.rs +++ b/crates/starknet_integration_tests/src/state_reader.rs @@ -5,15 +5,15 @@ use assert_matches::assert_matches; use blockifier::context::ChainInfo; use blockifier::test_utils::contracts::FeatureContract; use blockifier::test_utils::{ - CairoVersion, RunnableCairo1, BALANCE, CURRENT_BLOCK_TIMESTAMP, DEFAULT_ETH_L1_GAS_PRICE, - DEFAULT_STRK_L1_GAS_PRICE, TEST_SEQUENCER_ADDRESS, + BALANCE, CURRENT_BLOCK_TIMESTAMP, CairoVersion, DEFAULT_ETH_L1_GAS_PRICE, + DEFAULT_STRK_L1_GAS_PRICE, RunnableCairo1, TEST_SEQUENCER_ADDRESS, }; use blockifier::versioned_constants::VersionedConstants; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; use indexmap::IndexMap; use mempool_test_utils::starknet_api_test_utils::Contract; use papyrus_common::pending_classes::PendingClasses; -use papyrus_rpc::{run_server, RpcConfig}; +use papyrus_rpc::{RpcConfig, run_server}; use papyrus_storage::body::BodyStorageWriter; use papyrus_storage::class::ClassStorageWriter; use papyrus_storage::compiled_class::CasmStorageWriter; diff --git a/crates/starknet_integration_tests/src/utils.rs b/crates/starknet_integration_tests/src/utils.rs index b99dacd489..e266636389 100644 --- a/crates/starknet_integration_tests/src/utils.rs +++ b/crates/starknet_integration_tests/src/utils.rs @@ -7,9 +7,9 @@ use blockifier::test_utils::contracts::FeatureContract; use blockifier::test_utils::{CairoVersion, RunnableCairo1}; use mempool_test_utils::starknet_api_test_utils::{AccountId, MultiAccountTransactionGenerator}; use papyrus_consensus::config::ConsensusConfig; -use papyrus_consensus::types::{ValidatorId, DEFAULT_VALIDATOR_ID}; -use papyrus_network::network_manager::test_utils::create_network_configs_connected_to_broadcast_channels; +use papyrus_consensus::types::{DEFAULT_VALIDATOR_ID, ValidatorId}; use papyrus_network::network_manager::BroadcastTopicChannels; +use papyrus_network::network_manager::test_utils::create_network_configs_connected_to_broadcast_channels; use papyrus_protobuf::consensus::{ProposalPart, StreamMessage}; use papyrus_storage::StorageConfig; use starknet_api::block::BlockNumber; diff --git a/crates/starknet_integration_tests/tests/end_to_end_integration_test.rs b/crates/starknet_integration_tests/tests/end_to_end_integration_test.rs index b3cb29b844..37482710da 100644 --- a/crates/starknet_integration_tests/tests/end_to_end_integration_test.rs +++ b/crates/starknet_integration_tests/tests/end_to_end_integration_test.rs @@ -1,8 +1,8 @@ use infra_utils::run_until::run_until; use mempool_test_utils::starknet_api_test_utils::{AccountId, MultiAccountTransactionGenerator}; use papyrus_execution::execution_utils::get_nonce_at; -use papyrus_storage::state::StateStorageReader; use papyrus_storage::StorageReader; +use papyrus_storage::state::StateStorageReader; use rstest::{fixture, rstest}; use starknet_api::block::BlockNumber; use starknet_api::core::{ContractAddress, Nonce}; diff --git a/crates/starknet_integration_tests/tests/mempool_p2p_flow_test.rs b/crates/starknet_integration_tests/tests/mempool_p2p_flow_test.rs index 6eda11b729..1c68fdb735 100644 --- a/crates/starknet_integration_tests/tests/mempool_p2p_flow_test.rs +++ b/crates/starknet_integration_tests/tests/mempool_p2p_flow_test.rs @@ -16,14 +16,14 @@ use starknet_api::rpc_transaction::{ use starknet_api::transaction::TransactionHash; use starknet_http_server::config::HttpServerConfig; use starknet_http_server::test_utils::HttpTestClient; -use starknet_integration_tests::state_reader::{spawn_test_rpc_state_reader, StorageTestSetup}; +use starknet_integration_tests::state_reader::{StorageTestSetup, spawn_test_rpc_state_reader}; use starknet_integration_tests::utils::{ create_batcher_config, create_chain_info, create_gateway_config, create_http_server_config, create_integration_test_tx_generator, run_integration_test_scenario, test_rpc_state_reader_config, }; -use starknet_mempool_p2p::config::MempoolP2pConfig; use starknet_mempool_p2p::MEMPOOL_TOPIC; +use starknet_mempool_p2p::config::MempoolP2pConfig; use starknet_sequencer_node::config::component_config::ComponentConfig; use starknet_sequencer_node::config::component_execution_config::{ ActiveComponentExecutionConfig, ReactiveComponentExecutionConfig, diff --git a/crates/starknet_l1_provider/src/l1_provider_tests.rs b/crates/starknet_l1_provider/src/l1_provider_tests.rs index 6af7ff8cdf..62eea0ffd2 100644 --- a/crates/starknet_l1_provider/src/l1_provider_tests.rs +++ b/crates/starknet_l1_provider/src/l1_provider_tests.rs @@ -3,12 +3,12 @@ use pretty_assertions::assert_eq; use starknet_api::test_utils::l1_handler::executable_l1_handler_tx; use starknet_api::transaction::TransactionHash; use starknet_api::{l1_handler_tx_args, tx_hash}; -use starknet_l1_provider_types::errors::L1ProviderError; use starknet_l1_provider_types::ValidationStatus; +use starknet_l1_provider_types::errors::L1ProviderError; -use crate::test_utils::L1ProviderContentBuilder; use crate::L1Provider; use crate::ProviderState::{Pending, Propose, Uninitialized, Validate}; +use crate::test_utils::L1ProviderContentBuilder; macro_rules! tx { (tx_hash: $tx_hash:expr) => {{ diff --git a/crates/starknet_mempool/src/mempool.rs b/crates/starknet_mempool/src/mempool.rs index ab1f063cbb..c30e563f65 100644 --- a/crates/starknet_mempool/src/mempool.rs +++ b/crates/starknet_mempool/src/mempool.rs @@ -3,8 +3,8 @@ use std::collections::HashMap; use starknet_api::block::GasPrice; use starknet_api::core::{ContractAddress, Nonce}; use starknet_api::executable_transaction::AccountTransaction; -use starknet_api::transaction::fields::Tip; use starknet_api::transaction::TransactionHash; +use starknet_api::transaction::fields::Tip; use starknet_mempool_types::errors::MempoolError; use starknet_mempool_types::mempool_types::{ AccountState, AddTransactionArgs, CommitBlockArgs, MempoolResult, diff --git a/crates/starknet_mempool/src/mempool_test.rs b/crates/starknet_mempool/src/mempool_test.rs index deb65c0ebd..6867441589 100644 --- a/crates/starknet_mempool/src/mempool_test.rs +++ b/crates/starknet_mempool/src/mempool_test.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use mockall::predicate; use papyrus_network_types::network_types::BroadcastedMessageMetadata; -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use pretty_assertions::assert_eq; use rstest::{fixture, rstest}; use starknet_api::block::GasPrice; @@ -186,14 +186,10 @@ fn add_txs_and_verify_no_replacement( invalid_replacement_inputs: impl IntoIterator, ) { for input in invalid_replacement_inputs { - add_tx_expect_error( - &mut mempool, - &input, - MempoolError::DuplicateNonce { - address: input.tx.contract_address(), - nonce: input.tx.nonce(), - }, - ); + add_tx_expect_error(&mut mempool, &input, MempoolError::DuplicateNonce { + address: input.tx.contract_address(), + nonce: input.tx.nonce(), + }); } // Verify transaction was not replaced. @@ -296,11 +292,11 @@ fn test_get_txs_replenishes_queue_only_between_chunks() { // Test and assert: all transactions returned. // Replenishment done in chunks: account 1 transaction is returned before the one of account 0, // although its priority is higher. - get_txs_and_assert_expected( - &mut mempool, - 3, - &[tx_address_0_nonce_0, tx_address_1_nonce_0, tx_address_0_nonce_1], - ); + get_txs_and_assert_expected(&mut mempool, 3, &[ + tx_address_0_nonce_0, + tx_address_1_nonce_0, + tx_address_0_nonce_1, + ]); let expected_mempool_content = MempoolContentBuilder::new().with_priority_queue([]).build(); expected_mempool_content.assert_eq(&mempool); } @@ -391,11 +387,9 @@ fn test_add_tx_failure_on_duplicate_tx_hash(mut mempool: Mempool) { // Test. add_tx(&mut mempool, &input); - add_tx_expect_error( - &mut mempool, - &duplicate_input, - MempoolError::DuplicateTransaction { tx_hash: input.tx.tx_hash() }, - ); + add_tx_expect_error(&mut mempool, &duplicate_input, MempoolError::DuplicateTransaction { + tx_hash: input.tx.tx_hash(), + }); // Assert: the original transaction remains. let expected_mempool_content = MempoolContentBuilder::new().with_pool([input.tx]).build(); @@ -410,18 +404,16 @@ fn test_add_tx_lower_than_queued_nonce(mut mempool: Mempool) { // Test and assert: original transaction remains. let invalid_input = add_tx_input!(tx_hash: 2, address: "0x0", tx_nonce: 0, account_nonce: 1); - add_tx_expect_error( - &mut mempool, - &invalid_input, - MempoolError::NonceTooOld { address: contract_address!("0x0"), nonce: nonce!(0) }, - ); + add_tx_expect_error(&mut mempool, &invalid_input, MempoolError::NonceTooOld { + address: contract_address!("0x0"), + nonce: nonce!(0), + }); let invalid_input = add_tx_input!(tx_hash: 2, address: "0x0", tx_nonce: 1, account_nonce: 1); - add_tx_expect_error( - &mut mempool, - &invalid_input, - MempoolError::DuplicateNonce { address: contract_address!("0x0"), nonce: nonce!(1) }, - ); + add_tx_expect_error(&mut mempool, &invalid_input, MempoolError::DuplicateNonce { + address: contract_address!("0x0"), + nonce: nonce!(1), + }); } #[rstest] diff --git a/crates/starknet_mempool/src/transaction_pool.rs b/crates/starknet_mempool/src/transaction_pool.rs index 7da94658dd..2d0f830de2 100644 --- a/crates/starknet_mempool/src/transaction_pool.rs +++ b/crates/starknet_mempool/src/transaction_pool.rs @@ -1,4 +1,4 @@ -use std::collections::{hash_map, BTreeMap, HashMap}; +use std::collections::{BTreeMap, HashMap, hash_map}; use starknet_api::core::{ContractAddress, Nonce}; use starknet_api::executable_transaction::AccountTransaction; diff --git a/crates/starknet_mempool/src/transaction_queue.rs b/crates/starknet_mempool/src/transaction_queue.rs index e0335dac69..c46699c66a 100644 --- a/crates/starknet_mempool/src/transaction_queue.rs +++ b/crates/starknet_mempool/src/transaction_queue.rs @@ -3,8 +3,8 @@ use std::collections::{BTreeSet, HashMap}; use starknet_api::block::GasPrice; use starknet_api::core::{ContractAddress, Nonce}; -use starknet_api::transaction::fields::Tip; use starknet_api::transaction::TransactionHash; +use starknet_api::transaction::fields::Tip; use crate::mempool::TransactionReference; diff --git a/crates/starknet_mempool/tests/flow_test.rs b/crates/starknet_mempool/tests/flow_test.rs index 5c9e0d0e2a..eb1a162088 100644 --- a/crates/starknet_mempool/tests/flow_test.rs +++ b/crates/starknet_mempool/tests/flow_test.rs @@ -37,11 +37,10 @@ fn test_add_tx_fills_nonce_gap(mut mempool: Mempool) { add_tx(&mut mempool, &input_address_0_nonce_0); // Test and assert: all remaining transactions are returned. - get_txs_and_assert_expected( - &mut mempool, - 2, - &[input_address_0_nonce_0.tx, input_address_0_nonce_1.tx], - ); + get_txs_and_assert_expected(&mut mempool, 2, &[ + input_address_0_nonce_0.tx, + input_address_0_nonce_1.tx, + ]); } #[rstest] @@ -54,11 +53,10 @@ fn test_add_tx_rejection_for_txs_passed_to_batcher(mut mempool: Mempool) { get_txs_and_assert_expected(&mut mempool, 1, &[input_tx.tx]); let input_tx_duplicate_nonce = add_tx_input!(tx_hash: 1, tx_nonce: 0); - add_tx_expect_error( - &mut mempool, - &input_tx_duplicate_nonce, - MempoolError::NonceTooOld { address: contract_address!("0x0"), nonce: nonce!(0) }, - ); + add_tx_expect_error(&mut mempool, &input_tx_duplicate_nonce, MempoolError::NonceTooOld { + address: contract_address!("0x0"), + nonce: nonce!(0), + }); } #[rstest] @@ -78,11 +76,10 @@ fn test_add_same_nonce_tx_after_previous_not_included_in_block(mut mempool: Memp } // Test. - get_txs_and_assert_expected( - &mut mempool, - 2, - &[tx_nonce_3_account_nonce_3.tx, tx_nonce_4_account_nonce_3.tx.clone()], - ); + get_txs_and_assert_expected(&mut mempool, 2, &[ + tx_nonce_3_account_nonce_3.tx, + tx_nonce_4_account_nonce_3.tx.clone(), + ]); let nonces = [("0x0", 4)]; // Transaction with nonce 3 was included, 4 was not. let tx_hashes = [1]; @@ -90,17 +87,15 @@ fn test_add_same_nonce_tx_after_previous_not_included_in_block(mut mempool: Memp let tx_nonce_4_account_nonce_4 = add_tx_input!(tx_hash: 4, address: "0x0", tx_nonce: 4, account_nonce: 4); - add_tx_expect_error( - &mut mempool, - &tx_nonce_4_account_nonce_4, - MempoolError::DuplicateNonce { address: contract_address!("0x0"), nonce: nonce!(4) }, - ); - - get_txs_and_assert_expected( - &mut mempool, - 2, - &[tx_nonce_4_account_nonce_3.tx, tx_nonce_5_account_nonce_3.tx], - ); + add_tx_expect_error(&mut mempool, &tx_nonce_4_account_nonce_4, MempoolError::DuplicateNonce { + address: contract_address!("0x0"), + nonce: nonce!(4), + }); + + get_txs_and_assert_expected(&mut mempool, 2, &[ + tx_nonce_4_account_nonce_3.tx, + tx_nonce_5_account_nonce_3.tx, + ]); } #[rstest] @@ -157,32 +152,26 @@ fn test_commit_block_includes_proposed_txs_subset(mut mempool: Mempool) { } // Test. - get_txs_and_assert_expected( - &mut mempool, - 2, - &[tx_address_2_nonce_1.tx.clone(), tx_address_1_nonce_2.tx], - ); - get_txs_and_assert_expected( - &mut mempool, - 4, - &[ - tx_address_2_nonce_2.tx, - tx_address_1_nonce_3.tx.clone(), - tx_address_0_nonce_1.tx, - tx_address_1_nonce_4.tx.clone(), - ], - ); + get_txs_and_assert_expected(&mut mempool, 2, &[ + tx_address_2_nonce_1.tx.clone(), + tx_address_1_nonce_2.tx, + ]); + get_txs_and_assert_expected(&mut mempool, 4, &[ + tx_address_2_nonce_2.tx, + tx_address_1_nonce_3.tx.clone(), + tx_address_0_nonce_1.tx, + tx_address_1_nonce_4.tx.clone(), + ]); // Address 0x0 stays as proposed, address 0x1 rewinds nonce 4, address 0x2 rewinds completely. let nonces = [("0x0", 2), ("0x1", 4)]; let tx_hashes = [1, 4]; commit_block(&mut mempool, nonces, tx_hashes); - get_txs_and_assert_expected( - &mut mempool, - 2, - &[tx_address_2_nonce_1.tx, tx_address_1_nonce_4.tx], - ); + get_txs_and_assert_expected(&mut mempool, 2, &[ + tx_address_2_nonce_1.tx, + tx_address_1_nonce_4.tx, + ]); } #[rstest] @@ -207,11 +196,10 @@ fn test_commit_block_fills_nonce_gap(mut mempool: Mempool) { // Assert: hole was indeed closed. let tx_nonce_4_account_nonce_4 = add_tx_input!(tx_hash: 3, address: "0x0", tx_nonce: 4, account_nonce: 4); - add_tx_expect_error( - &mut mempool, - &tx_nonce_4_account_nonce_4, - MempoolError::NonceTooOld { address: contract_address!("0x0"), nonce: nonce!(4) }, - ); + add_tx_expect_error(&mut mempool, &tx_nonce_4_account_nonce_4, MempoolError::NonceTooOld { + address: contract_address!("0x0"), + nonce: nonce!(4), + }); get_txs_and_assert_expected(&mut mempool, 2, &[tx_nonce_5_account_nonce_3.tx]); } @@ -234,16 +222,12 @@ fn test_commit_block_rewinds_queued_nonce(mut mempool: Mempool) { add_tx(&mut mempool, input); } - get_txs_and_assert_expected( - &mut mempool, - 4, - &[ - tx_address_1_nonce_2.tx.clone(), - tx_address_0_nonce_2.tx, - tx_address_1_nonce_3.tx, - tx_address_0_nonce_3.tx.clone(), - ], - ); + get_txs_and_assert_expected(&mut mempool, 4, &[ + tx_address_1_nonce_2.tx.clone(), + tx_address_0_nonce_2.tx, + tx_address_1_nonce_3.tx, + tx_address_0_nonce_3.tx.clone(), + ]); // Test. let nonces = [("0x0", 3)]; @@ -253,11 +237,10 @@ fn test_commit_block_rewinds_queued_nonce(mut mempool: Mempool) { commit_block(&mut mempool, nonces, tx_hashes); // Nonces 3 and 4 were re-enqueued correctly. - get_txs_and_assert_expected( - &mut mempool, - 2, - &[tx_address_1_nonce_2.tx, tx_address_0_nonce_3.tx], - ); + get_txs_and_assert_expected(&mut mempool, 2, &[ + tx_address_1_nonce_2.tx, + tx_address_0_nonce_3.tx, + ]); } #[rstest] diff --git a/crates/starknet_mempool_p2p/src/config.rs b/crates/starknet_mempool_p2p/src/config.rs index ff32d0f354..5cec4be1b8 100644 --- a/crates/starknet_mempool_p2p/src/config.rs +++ b/crates/starknet_mempool_p2p/src/config.rs @@ -1,6 +1,6 @@ use std::collections::BTreeMap; -use papyrus_config::dumping::{append_sub_config_name, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use papyrus_network::NetworkConfig; use serde::{Deserialize, Serialize}; diff --git a/crates/starknet_mempool_p2p/src/propagator/test.rs b/crates/starknet_mempool_p2p/src/propagator/test.rs index 0779800e0f..5cbf8ae778 100644 --- a/crates/starknet_mempool_p2p/src/propagator/test.rs +++ b/crates/starknet_mempool_p2p/src/propagator/test.rs @@ -1,11 +1,11 @@ use futures::stream::StreamExt; +use papyrus_network::network_manager::BroadcastTopicChannels; use papyrus_network::network_manager::test_utils::{ - mock_register_broadcast_topic, BroadcastNetworkMock, TestSubscriberChannels, + BroadcastNetworkMock, TestSubscriberChannels, mock_register_broadcast_topic, }; -use papyrus_network::network_manager::BroadcastTopicChannels; use papyrus_network_types::network_types::BroadcastedMessageMetadata; use papyrus_protobuf::mempool::RpcTransactionWrapper; -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use starknet_api::rpc_transaction::RpcTransaction; use starknet_mempool_p2p_types::communication::MempoolP2pPropagatorRequest; use starknet_sequencer_infra::component_definitions::ComponentRequestHandler; diff --git a/crates/starknet_mempool_p2p/src/runner/mod.rs b/crates/starknet_mempool_p2p/src/runner/mod.rs index 2cb08dcc31..7e73791356 100644 --- a/crates/starknet_mempool_p2p/src/runner/mod.rs +++ b/crates/starknet_mempool_p2p/src/runner/mod.rs @@ -3,7 +3,7 @@ mod test; use async_trait::async_trait; use futures::stream::FuturesUnordered; -use futures::{pin_mut, StreamExt, TryFutureExt}; +use futures::{StreamExt, TryFutureExt, pin_mut}; use papyrus_network::network_manager::{ BroadcastTopicClient, BroadcastTopicClientTrait, BroadcastTopicServer, NetworkManager, }; diff --git a/crates/starknet_mempool_p2p/src/runner/test.rs b/crates/starknet_mempool_p2p/src/runner/test.rs index a9a4e820b7..45a0ab6120 100644 --- a/crates/starknet_mempool_p2p/src/runner/test.rs +++ b/crates/starknet_mempool_p2p/src/runner/test.rs @@ -2,17 +2,17 @@ use std::sync::Arc; use std::time::Duration; use async_trait::async_trait; +use futures::SinkExt; use futures::channel::mpsc::Sender; use futures::stream::StreamExt; -use futures::SinkExt; +use papyrus_network::NetworkConfig; use papyrus_network::network_manager::test_utils::{ - mock_register_broadcast_topic, BroadcastNetworkMock, TestSubscriberChannels, + BroadcastNetworkMock, TestSubscriberChannels, mock_register_broadcast_topic, }; use papyrus_network::network_manager::{BroadcastTopicChannels, NetworkManager}; -use papyrus_network::NetworkConfig; use papyrus_network_types::network_types::BroadcastedMessageMetadata; use papyrus_protobuf::mempool::RpcTransactionWrapper; -use papyrus_test_utils::{get_rng, GetTestInstance}; +use papyrus_test_utils::{GetTestInstance, get_rng}; use starknet_api::rpc_transaction::RpcTransaction; use starknet_api::transaction::TransactionHash; use starknet_gateway_types::communication::{GatewayClient, GatewayClientResult}; diff --git a/crates/starknet_monitoring_endpoint/src/config.rs b/crates/starknet_monitoring_endpoint/src/config.rs index 4eddcf2929..1186712726 100644 --- a/crates/starknet_monitoring_endpoint/src/config.rs +++ b/crates/starknet_monitoring_endpoint/src/config.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; use std::fmt::{Display, Formatter, Result}; use std::net::IpAddr; -use papyrus_config::dumping::{ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use serde::{Deserialize, Serialize}; use validator::Validate; diff --git a/crates/starknet_monitoring_endpoint/src/monitoring_endpoint.rs b/crates/starknet_monitoring_endpoint/src/monitoring_endpoint.rs index ff92ca0a54..13532d899c 100644 --- a/crates/starknet_monitoring_endpoint/src/monitoring_endpoint.rs +++ b/crates/starknet_monitoring_endpoint/src/monitoring_endpoint.rs @@ -4,7 +4,7 @@ use std::net::SocketAddr; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use axum::routing::get; -use axum::{async_trait, Router, Server}; +use axum::{Router, Server, async_trait}; use hyper::Error; use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle}; use starknet_sequencer_infra::component_definitions::ComponentStarter; diff --git a/crates/starknet_monitoring_endpoint/src/monitoring_endpoint_test.rs b/crates/starknet_monitoring_endpoint/src/monitoring_endpoint_test.rs index dd9017e7ea..49304598bd 100644 --- a/crates/starknet_monitoring_endpoint/src/monitoring_endpoint_test.rs +++ b/crates/starknet_monitoring_endpoint/src/monitoring_endpoint_test.rs @@ -1,10 +1,10 @@ use std::net::IpAddr; +use axum::Router; use axum::http::StatusCode; use axum::response::Response; -use axum::Router; -use hyper::body::to_bytes; use hyper::Client; +use hyper::body::to_bytes; use metrics::{absolute_counter, describe_counter, register_counter}; use pretty_assertions::assert_eq; use tokio::spawn; @@ -13,7 +13,7 @@ use tower::ServiceExt; use super::MonitoringEndpointConfig; use crate::monitoring_endpoint::{ - create_monitoring_endpoint, MonitoringEndpoint, ALIVE, METRICS, READY, VERSION, + ALIVE, METRICS, MonitoringEndpoint, READY, VERSION, create_monitoring_endpoint, }; use crate::test_utils::build_request; diff --git a/crates/starknet_monitoring_endpoint/src/test_utils.rs b/crates/starknet_monitoring_endpoint/src/test_utils.rs index 8d284fc5aa..17eee47a64 100644 --- a/crates/starknet_monitoring_endpoint/src/test_utils.rs +++ b/crates/starknet_monitoring_endpoint/src/test_utils.rs @@ -2,8 +2,8 @@ use std::net::{IpAddr, SocketAddr}; use axum::body::Body; use axum::http::Request; -use hyper::client::HttpConnector; use hyper::Client; +use hyper::client::HttpConnector; use infra_utils::run_until::run_until; use infra_utils::tracing::{CustomLogger, TraceLevel}; use tracing::info; diff --git a/crates/starknet_patricia/src/patricia_merkle_tree/external_test_utils.rs b/crates/starknet_patricia/src/patricia_merkle_tree/external_test_utils.rs index 5958d330ef..075b156409 100644 --- a/crates/starknet_patricia/src/patricia_merkle_tree/external_test_utils.rs +++ b/crates/starknet_patricia/src/patricia_merkle_tree/external_test_utils.rs @@ -17,7 +17,7 @@ use crate::felt::Felt; use crate::hash::hash_trait::HashOutput; use crate::patricia_merkle_tree::errors::TypesError; use crate::storage::map_storage::MapStorage; -use crate::storage::storage_trait::{create_db_key, StarknetPrefix, StorageKey, StorageValue}; +use crate::storage::storage_trait::{StarknetPrefix, StorageKey, StorageValue, create_db_key}; impl TryFrom<&U256> for Felt { type Error = TypesError; @@ -90,13 +90,10 @@ where &leaf_modifications .iter() .map(|(index, data)| { - ( - *index, - match data.is_empty() { - true => SkeletonLeaf::Zero, - false => SkeletonLeaf::NonZero, - }, - ) + (*index, match data.is_empty() { + true => SkeletonLeaf::Zero, + false => SkeletonLeaf::NonZero, + }) }) .collect(), ) diff --git a/crates/starknet_patricia/src/patricia_merkle_tree/filled_tree/tree.rs b/crates/starknet_patricia/src/patricia_merkle_tree/filled_tree/tree.rs index db98b66a1b..a662e12c0f 100644 --- a/crates/starknet_patricia/src/patricia_merkle_tree/filled_tree/tree.rs +++ b/crates/starknet_patricia/src/patricia_merkle_tree/filled_tree/tree.rs @@ -216,11 +216,10 @@ impl FilledTreeImpl { }); let hash = TH::compute_node_hash(&data); - Self::write_to_output_map( - filled_tree_output_map, - index, - FilledNode { hash, data }, - )?; + Self::write_to_output_map(filled_tree_output_map, index, FilledNode { + hash, + data, + })?; Ok(hash) } UpdatedSkeletonNode::Edge(path_to_bottom) => { @@ -237,11 +236,10 @@ impl FilledTreeImpl { let data = NodeData::Edge(EdgeData { path_to_bottom: *path_to_bottom, bottom_hash }); let hash = TH::compute_node_hash(&data); - Self::write_to_output_map( - filled_tree_output_map, - index, - FilledNode { hash, data }, - )?; + Self::write_to_output_map(filled_tree_output_map, index, FilledNode { + hash, + data, + })?; Ok(hash) } UpdatedSkeletonNode::UnmodifiedSubTree(hash_result) => Ok(*hash_result), @@ -254,11 +252,10 @@ impl FilledTreeImpl { } let data = NodeData::Leaf(leaf_data); let hash = TH::compute_node_hash(&data); - Self::write_to_output_map( - filled_tree_output_map, - index, - FilledNode { hash, data }, - )?; + Self::write_to_output_map(filled_tree_output_map, index, FilledNode { + hash, + data, + })?; if let Some(output) = leaf_output { Self::write_to_output_map(leaf_index_to_leaf_output, index, output)? }; diff --git a/crates/starknet_patricia/src/patricia_merkle_tree/filled_tree/tree_test.rs b/crates/starknet_patricia/src/patricia_merkle_tree/filled_tree/tree_test.rs index 1299d00d3c..9f15c2ab68 100644 --- a/crates/starknet_patricia/src/patricia_merkle_tree/filled_tree/tree_test.rs +++ b/crates/starknet_patricia/src/patricia_merkle_tree/filled_tree/tree_test.rs @@ -288,8 +288,8 @@ async fn test_delete_leaf_from_empty_tree() { assert!(root_hash == HashOutput::ROOT_OF_EMPTY_TREE); } -fn get_small_tree_updated_skeleton_and_leaf_modifications( -) -> (UpdatedSkeletonTreeImpl, LeafModifications) { +fn get_small_tree_updated_skeleton_and_leaf_modifications() +-> (UpdatedSkeletonTreeImpl, LeafModifications) { // Set up the updated skeleton tree. let new_leaves = [(35, "0x1"), (36, "0x2"), (63, "0x3")]; let nodes_in_skeleton_tree: Vec<(NodeIndex, UpdatedSkeletonNode)> = [ @@ -315,8 +315,8 @@ fn get_small_tree_updated_skeleton_and_leaf_modifications( (updated_skeleton_tree, modifications) } -fn get_small_tree_expected_filled_tree_map_and_root_hash( -) -> (HashMap>, HashOutput) { +fn get_small_tree_expected_filled_tree_map_and_root_hash() +-> (HashMap>, HashOutput) { let expected_root_hash = HashOutput(Felt::from_hex("0x21").unwrap()); let expected_filled_tree_map = HashMap::from([ create_mock_binary_entry_for_testing(1, "0x21", "0xb", "0x16"), @@ -371,16 +371,13 @@ fn create_mock_binary_entry_for_testing( left_hash: &str, right_hash: &str, ) -> (NodeIndex, FilledNode) { - ( - NodeIndex::from(index), - FilledNode { - hash: HashOutput(Felt::from_hex(hash).unwrap()), - data: NodeData::Binary(BinaryData { - left_hash: HashOutput(Felt::from_hex(left_hash).unwrap()), - right_hash: HashOutput(Felt::from_hex(right_hash).unwrap()), - }), - }, - ) + (NodeIndex::from(index), FilledNode { + hash: HashOutput(Felt::from_hex(hash).unwrap()), + data: NodeData::Binary(BinaryData { + left_hash: HashOutput(Felt::from_hex(left_hash).unwrap()), + right_hash: HashOutput(Felt::from_hex(right_hash).unwrap()), + }), + }) } fn create_mock_edge_entry_for_testing( @@ -390,31 +387,22 @@ fn create_mock_edge_entry_for_testing( length: u8, bottom_hash: &str, ) -> (NodeIndex, FilledNode) { - ( - NodeIndex::from(index), - FilledNode { - hash: HashOutput(Felt::from_hex(hash).unwrap()), - data: NodeData::Edge(EdgeData { - bottom_hash: HashOutput(Felt::from_hex(bottom_hash).unwrap()), - path_to_bottom: PathToBottom::new( - path.into(), - EdgePathLength::new(length).unwrap(), - ) + (NodeIndex::from(index), FilledNode { + hash: HashOutput(Felt::from_hex(hash).unwrap()), + data: NodeData::Edge(EdgeData { + bottom_hash: HashOutput(Felt::from_hex(bottom_hash).unwrap()), + path_to_bottom: PathToBottom::new(path.into(), EdgePathLength::new(length).unwrap()) .unwrap(), - }), - }, - ) + }), + }) } fn create_mock_leaf_entry_for_testing( index: u128, hash: &str, ) -> (NodeIndex, FilledNode) { - ( - NodeIndex::from(index), - FilledNode { - hash: HashOutput(Felt::from_hex(hash).unwrap()), - data: NodeData::Leaf(MockLeaf(Felt::from_hex(hash).unwrap())), - }, - ) + (NodeIndex::from(index), FilledNode { + hash: HashOutput(Felt::from_hex(hash).unwrap()), + data: NodeData::Leaf(MockLeaf(Felt::from_hex(hash).unwrap())), + }) } diff --git a/crates/starknet_patricia/src/patricia_merkle_tree/node_data/leaf.rs b/crates/starknet_patricia/src/patricia_merkle_tree/node_data/leaf.rs index 0a711e5eca..e779a10d82 100644 --- a/crates/starknet_patricia/src/patricia_merkle_tree/node_data/leaf.rs +++ b/crates/starknet_patricia/src/patricia_merkle_tree/node_data/leaf.rs @@ -65,11 +65,7 @@ impl SkeletonLeaf { impl From for SkeletonLeaf { fn from(value: Felt) -> Self { - if value == Felt::ZERO { - Self::Zero - } else { - Self::NonZero - } + if value == Felt::ZERO { Self::Zero } else { Self::NonZero } } } diff --git a/crates/starknet_patricia/src/patricia_merkle_tree/original_skeleton_tree/create_tree.rs b/crates/starknet_patricia/src/patricia_merkle_tree/original_skeleton_tree/create_tree.rs index 7e535fc29d..bcf641abe0 100644 --- a/crates/starknet_patricia/src/patricia_merkle_tree/original_skeleton_tree/create_tree.rs +++ b/crates/starknet_patricia/src/patricia_merkle_tree/original_skeleton_tree/create_tree.rs @@ -18,7 +18,7 @@ use crate::patricia_merkle_tree::original_skeleton_tree::tree::{ use crate::patricia_merkle_tree::original_skeleton_tree::utils::split_leaves; use crate::patricia_merkle_tree::types::{NodeIndex, SortedLeafIndices, SubTreeHeight}; use crate::storage::errors::StorageError; -use crate::storage::storage_trait::{create_db_key, StarknetPrefix, Storage, StorageKey}; +use crate::storage::storage_trait::{StarknetPrefix, Storage, StorageKey, create_db_key}; #[cfg(test)] #[path = "create_tree_test.rs"] diff --git a/crates/starknet_patricia/src/patricia_merkle_tree/original_skeleton_tree/create_tree_test.rs b/crates/starknet_patricia/src/patricia_merkle_tree/original_skeleton_tree/create_tree_test.rs index 64a8389e3b..23d5cae4be 100644 --- a/crates/starknet_patricia/src/patricia_merkle_tree/original_skeleton_tree/create_tree_test.rs +++ b/crates/starknet_patricia/src/patricia_merkle_tree/original_skeleton_tree/create_tree_test.rs @@ -13,7 +13,7 @@ use crate::patricia_merkle_tree::external_test_utils::{ create_unmodified_subtree_skeleton_node, }; use crate::patricia_merkle_tree::internal_test_utils::{ - small_tree_index_to_full, MockLeaf, OriginalSkeletonMockTrieConfig, + MockLeaf, OriginalSkeletonMockTrieConfig, small_tree_index_to_full, }; use crate::patricia_merkle_tree::node_data::inner_node::{EdgePath, EdgePathLength, PathToBottom}; use crate::patricia_merkle_tree::node_data::leaf::LeafModifications; diff --git a/crates/starknet_patricia/src/patricia_merkle_tree/original_skeleton_tree/utils_test.rs b/crates/starknet_patricia/src/patricia_merkle_tree/original_skeleton_tree/utils_test.rs index 8d9b4416cd..8a622d97dd 100644 --- a/crates/starknet_patricia/src/patricia_merkle_tree/original_skeleton_tree/utils_test.rs +++ b/crates/starknet_patricia/src/patricia_merkle_tree/original_skeleton_tree/utils_test.rs @@ -1,6 +1,6 @@ -use ethnum::{uint, U256}; -use rand::rngs::ThreadRng; +use ethnum::{U256, uint}; use rand::Rng; +use rand::rngs::ThreadRng; use rstest::rstest; use super::split_leaves; diff --git a/crates/starknet_patricia/src/patricia_merkle_tree/types_test.rs b/crates/starknet_patricia/src/patricia_merkle_tree/types_test.rs index 08447d3b6f..6e688b0d47 100644 --- a/crates/starknet_patricia/src/patricia_merkle_tree/types_test.rs +++ b/crates/starknet_patricia/src/patricia_merkle_tree/types_test.rs @@ -1,6 +1,6 @@ -use ethnum::{uint, U256}; -use rand::rngs::ThreadRng; +use ethnum::{U256, uint}; use rand::Rng; +use rand::rngs::ThreadRng; use rstest::rstest; use crate::felt::Felt; diff --git a/crates/starknet_patricia/src/patricia_merkle_tree/updated_skeleton_tree/create_tree_helper_test.rs b/crates/starknet_patricia/src/patricia_merkle_tree/updated_skeleton_tree/create_tree_helper_test.rs index 17c933492e..645858dc7a 100644 --- a/crates/starknet_patricia/src/patricia_merkle_tree/updated_skeleton_tree/create_tree_helper_test.rs +++ b/crates/starknet_patricia/src/patricia_merkle_tree/updated_skeleton_tree/create_tree_helper_test.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use ethnum::{uint, U256}; +use ethnum::{U256, uint}; use pretty_assertions::assert_eq; use rstest::{fixture, rstest}; @@ -8,8 +8,8 @@ use crate::felt::Felt; use crate::hash::hash_trait::HashOutput; use crate::patricia_merkle_tree::filled_tree::tree::FilledTree; use crate::patricia_merkle_tree::internal_test_utils::{ - as_fully_indexed, get_initial_updated_skeleton, small_tree_index_to_full, MockLeaf, MockTrie, - OriginalSkeletonMockTrieConfig, TestTreeHashFunction, + MockLeaf, MockTrie, OriginalSkeletonMockTrieConfig, TestTreeHashFunction, as_fully_indexed, + get_initial_updated_skeleton, small_tree_index_to_full, }; use crate::patricia_merkle_tree::node_data::inner_node::{EdgePathLength, PathToBottom}; use crate::patricia_merkle_tree::original_skeleton_tree::node::OriginalSkeletonNode; @@ -18,7 +18,7 @@ use crate::patricia_merkle_tree::original_skeleton_tree::tree::{ }; use crate::patricia_merkle_tree::types::{NodeIndex, SortedLeafIndices, SubTreeHeight}; use crate::patricia_merkle_tree::updated_skeleton_tree::create_tree_helper::{ - get_path_to_lca, has_leaves_on_both_sides, TempSkeletonNode, + TempSkeletonNode, get_path_to_lca, has_leaves_on_both_sides, }; use crate::patricia_merkle_tree::updated_skeleton_tree::node::UpdatedSkeletonNode; use crate::patricia_merkle_tree::updated_skeleton_tree::tree::{ diff --git a/crates/starknet_patricia/src/patricia_merkle_tree/updated_skeleton_tree/tree_test.rs b/crates/starknet_patricia/src/patricia_merkle_tree/updated_skeleton_tree/tree_test.rs index 327d9377fd..147fcf46f6 100644 --- a/crates/starknet_patricia/src/patricia_merkle_tree/updated_skeleton_tree/tree_test.rs +++ b/crates/starknet_patricia/src/patricia_merkle_tree/updated_skeleton_tree/tree_test.rs @@ -5,7 +5,7 @@ use rstest::{fixture, rstest}; use crate::felt::Felt; use crate::hash::hash_trait::HashOutput; use crate::patricia_merkle_tree::internal_test_utils::{ - get_initial_updated_skeleton, MockLeaf, OriginalSkeletonMockTrieConfig, + MockLeaf, OriginalSkeletonMockTrieConfig, get_initial_updated_skeleton, }; use crate::patricia_merkle_tree::node_data::inner_node::PathToBottom; use crate::patricia_merkle_tree::node_data::leaf::{LeafModifications, SkeletonLeaf}; diff --git a/crates/starknet_sequencer_infra/src/component_client/definitions.rs b/crates/starknet_sequencer_infra/src/component_client/definitions.rs index 5bb1e06199..23a6900060 100644 --- a/crates/starknet_sequencer_infra/src/component_client/definitions.rs +++ b/crates/starknet_sequencer_infra/src/component_client/definitions.rs @@ -1,8 +1,8 @@ use std::sync::Arc; use hyper::StatusCode; -use serde::de::DeserializeOwned; use serde::Serialize; +use serde::de::DeserializeOwned; use thiserror::Error; use super::{LocalComponentClient, RemoteComponentClient}; diff --git a/crates/starknet_sequencer_infra/src/component_client/local_component_client.rs b/crates/starknet_sequencer_infra/src/component_client/local_component_client.rs index 4724f85b05..96a2e87afe 100644 --- a/crates/starknet_sequencer_infra/src/component_client/local_component_client.rs +++ b/crates/starknet_sequencer_infra/src/component_client/local_component_client.rs @@ -1,9 +1,9 @@ use std::any::type_name; use async_trait::async_trait; -use serde::de::DeserializeOwned; use serde::Serialize; -use tokio::sync::mpsc::{channel, Sender}; +use serde::de::DeserializeOwned; +use tokio::sync::mpsc::{Sender, channel}; use tracing::info; use crate::component_client::ClientResult; diff --git a/crates/starknet_sequencer_infra/src/component_client/remote_component_client.rs b/crates/starknet_sequencer_infra/src/component_client/remote_component_client.rs index bc08d14ae4..d1ab74a507 100644 --- a/crates/starknet_sequencer_infra/src/component_client/remote_component_client.rs +++ b/crates/starknet_sequencer_infra/src/component_client/remote_component_client.rs @@ -8,12 +8,12 @@ use async_trait::async_trait; use hyper::body::to_bytes; use hyper::header::CONTENT_TYPE; use hyper::{Body, Client, Request as HyperRequest, Response as HyperResponse, StatusCode, Uri}; -use serde::de::DeserializeOwned; use serde::Serialize; +use serde::de::DeserializeOwned; use super::definitions::{ClientError, ClientResult}; use crate::component_definitions::{ - ComponentClient, RemoteClientConfig, ServerError, APPLICATION_OCTET_STREAM, + APPLICATION_OCTET_STREAM, ComponentClient, RemoteClientConfig, ServerError, }; use crate::serde_utils::SerdeWrapper; diff --git a/crates/starknet_sequencer_infra/src/component_definitions.rs b/crates/starknet_sequencer_infra/src/component_definitions.rs index 6fd199b08c..64e9d9f239 100644 --- a/crates/starknet_sequencer_infra/src/component_definitions.rs +++ b/crates/starknet_sequencer_infra/src/component_definitions.rs @@ -4,7 +4,7 @@ use std::fmt::Debug; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use async_trait::async_trait; -use papyrus_config::dumping::{ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; diff --git a/crates/starknet_sequencer_infra/src/component_server/remote_component_server.rs b/crates/starknet_sequencer_infra/src/component_server/remote_component_server.rs index a50f226cd7..3c3b6da34b 100644 --- a/crates/starknet_sequencer_infra/src/component_server/remote_component_server.rs +++ b/crates/starknet_sequencer_infra/src/component_server/remote_component_server.rs @@ -7,12 +7,12 @@ use hyper::body::to_bytes; use hyper::header::CONTENT_TYPE; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request as HyperRequest, Response as HyperResponse, Server, StatusCode}; -use serde::de::DeserializeOwned; use serde::Serialize; +use serde::de::DeserializeOwned; use crate::component_client::{ClientError, LocalComponentClient}; use crate::component_definitions::{ - ComponentClient, RemoteServerConfig, ServerError, APPLICATION_OCTET_STREAM, + APPLICATION_OCTET_STREAM, ComponentClient, RemoteServerConfig, ServerError, }; use crate::component_server::ComponentServerStarter; use crate::errors::ComponentServerError; diff --git a/crates/starknet_sequencer_infra/src/tests/local_component_client_server_test.rs b/crates/starknet_sequencer_infra/src/tests/local_component_client_server_test.rs index 08660d7ebc..c6cadb5dd3 100644 --- a/crates/starknet_sequencer_infra/src/tests/local_component_client_server_test.rs +++ b/crates/starknet_sequencer_infra/src/tests/local_component_client_server_test.rs @@ -7,9 +7,9 @@ use crate::component_client::{ClientError, ClientResult, LocalComponentClient}; use crate::component_definitions::{ComponentClient, ComponentRequestAndResponseSender}; use crate::component_server::{ComponentServerStarter, LocalComponentServer}; use crate::tests::{ - test_a_b_functionality, ComponentA, ComponentAClientTrait, ComponentARequest, - ComponentAResponse, ComponentB, ComponentBClientTrait, ComponentBRequest, ComponentBResponse, - ResultA, ResultB, ValueA, ValueB, + ComponentA, ComponentAClientTrait, ComponentARequest, ComponentAResponse, ComponentB, + ComponentBClientTrait, ComponentBRequest, ComponentBResponse, ResultA, ResultB, ValueA, ValueB, + test_a_b_functionality, }; type ComponentAClient = LocalComponentClient; diff --git a/crates/starknet_sequencer_infra/src/tests/remote_component_client_server_test.rs b/crates/starknet_sequencer_infra/src/tests/remote_component_client_server_test.rs index 7ac784d5c8..2f86eb6489 100644 --- a/crates/starknet_sequencer_infra/src/tests/remote_component_client_server_test.rs +++ b/crates/starknet_sequencer_infra/src/tests/remote_component_client_server_test.rs @@ -8,19 +8,19 @@ use hyper::header::CONTENT_TYPE; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Client, Request, Response, Server, StatusCode, Uri}; use rstest::rstest; -use serde::de::DeserializeOwned; use serde::Serialize; +use serde::de::DeserializeOwned; use starknet_types_core::felt::Felt; -use tokio::sync::mpsc::channel; use tokio::sync::Mutex; +use tokio::sync::mpsc::channel; use tokio::task; use crate::component_client::{ ClientError, ClientResult, LocalComponentClient, RemoteComponentClient, }; use crate::component_definitions::{ - ComponentClient, ComponentRequestAndResponseSender, RemoteClientConfig, RemoteServerConfig, - ServerError, APPLICATION_OCTET_STREAM, + APPLICATION_OCTET_STREAM, ComponentClient, ComponentRequestAndResponseSender, + RemoteClientConfig, RemoteServerConfig, ServerError, }; use crate::component_server::{ ComponentServerStarter, LocalComponentServer, RemoteComponentServer, @@ -28,9 +28,9 @@ use crate::component_server::{ use crate::serde_utils::SerdeWrapper; use crate::test_utils::get_available_socket; use crate::tests::{ - test_a_b_functionality, ComponentA, ComponentAClientTrait, ComponentARequest, - ComponentAResponse, ComponentB, ComponentBClientTrait, ComponentBRequest, ComponentBResponse, - ResultA, ResultB, ValueA, ValueB, + ComponentA, ComponentAClientTrait, ComponentARequest, ComponentAResponse, ComponentB, + ComponentBClientTrait, ComponentBRequest, ComponentBResponse, ResultA, ResultB, ValueA, ValueB, + test_a_b_functionality, }; type ComponentAClient = RemoteComponentClient; diff --git a/crates/starknet_sequencer_infra/src/trace_util.rs b/crates/starknet_sequencer_infra/src/trace_util.rs index 6d01e5fb86..50adc4aedf 100644 --- a/crates/starknet_sequencer_infra/src/trace_util.rs +++ b/crates/starknet_sequencer_infra/src/trace_util.rs @@ -1,7 +1,7 @@ use tokio::sync::OnceCell; use tracing::metadata::LevelFilter; use tracing_subscriber::prelude::*; -use tracing_subscriber::{fmt, EnvFilter}; +use tracing_subscriber::{EnvFilter, fmt}; const DEFAULT_LEVEL: LevelFilter = LevelFilter::INFO; // Define a OnceCell to ensure the configuration is initialized only once diff --git a/crates/starknet_sequencer_node/src/bin/sequencer_dump_config.rs b/crates/starknet_sequencer_node/src/bin/sequencer_dump_config.rs index 3b38df5c60..c5ca1553ef 100644 --- a/crates/starknet_sequencer_node/src/bin/sequencer_dump_config.rs +++ b/crates/starknet_sequencer_node/src/bin/sequencer_dump_config.rs @@ -1,6 +1,6 @@ use papyrus_config::dumping::SerializeConfig; use starknet_sequencer_node::config::node_config::{ - SequencerNodeConfig, CONFIG_NON_POINTERS_WHITELIST, CONFIG_POINTERS, DEFAULT_CONFIG_PATH, + CONFIG_NON_POINTERS_WHITELIST, CONFIG_POINTERS, DEFAULT_CONFIG_PATH, SequencerNodeConfig, }; /// Updates the default config file by: diff --git a/crates/starknet_sequencer_node/src/communication.rs b/crates/starknet_sequencer_node/src/communication.rs index 812b72ab99..a5b3a6b1f7 100644 --- a/crates/starknet_sequencer_node/src/communication.rs +++ b/crates/starknet_sequencer_node/src/communication.rs @@ -4,7 +4,7 @@ use starknet_mempool_p2p_types::communication::MempoolP2pPropagatorRequestAndRes use starknet_mempool_types::communication::MempoolRequestAndResponseSender; use starknet_sequencer_infra::component_definitions::ComponentCommunication; use starknet_state_sync_types::communication::StateSyncRequestAndResponseSender; -use tokio::sync::mpsc::{channel, Receiver, Sender}; +use tokio::sync::mpsc::{Receiver, Sender, channel}; pub struct SequencerNodeCommunication { batcher_channel: ComponentCommunication, diff --git a/crates/starknet_sequencer_node/src/components.rs b/crates/starknet_sequencer_node/src/components.rs index 342945a0bc..9cb5d5da5f 100644 --- a/crates/starknet_sequencer_node/src/components.rs +++ b/crates/starknet_sequencer_node/src/components.rs @@ -1,15 +1,15 @@ use std::sync::Arc; -use starknet_batcher::batcher::{create_batcher, Batcher}; +use starknet_batcher::batcher::{Batcher, create_batcher}; use starknet_consensus_manager::consensus_manager::ConsensusManager; -use starknet_gateway::gateway::{create_gateway, Gateway}; -use starknet_http_server::http_server::{create_http_server, HttpServer}; -use starknet_mempool::communication::{create_mempool, MempoolCommunicationWrapper}; +use starknet_gateway::gateway::{Gateway, create_gateway}; +use starknet_http_server::http_server::{HttpServer, create_http_server}; +use starknet_mempool::communication::{MempoolCommunicationWrapper, create_mempool}; use starknet_mempool_p2p::create_p2p_propagator_and_runner; use starknet_mempool_p2p::propagator::MempoolP2pPropagator; use starknet_mempool_p2p::runner::MempoolP2pRunner; use starknet_monitoring_endpoint::monitoring_endpoint::{ - create_monitoring_endpoint, MonitoringEndpoint, + MonitoringEndpoint, create_monitoring_endpoint, }; use starknet_state_sync_types::communication::EmptyStateSyncClient; diff --git a/crates/starknet_sequencer_node/src/config/component_config.rs b/crates/starknet_sequencer_node/src/config/component_config.rs index 15e62ae209..baa818d00f 100644 --- a/crates/starknet_sequencer_node/src/config/component_config.rs +++ b/crates/starknet_sequencer_node/src/config/component_config.rs @@ -1,6 +1,6 @@ use std::collections::BTreeMap; -use papyrus_config::dumping::{append_sub_config_name, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name}; use papyrus_config::{ParamPath, SerializedParam}; use serde::{Deserialize, Serialize}; use validator::Validate; diff --git a/crates/starknet_sequencer_node/src/config/component_execution_config.rs b/crates/starknet_sequencer_node/src/config/component_execution_config.rs index fc8829fd31..d9b8b68961 100644 --- a/crates/starknet_sequencer_node/src/config/component_execution_config.rs +++ b/crates/starknet_sequencer_node/src/config/component_execution_config.rs @@ -1,6 +1,6 @@ use std::collections::BTreeMap; -use papyrus_config::dumping::{ser_optional_sub_config, ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_optional_sub_config, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use serde::{Deserialize, Serialize}; use starknet_sequencer_infra::component_definitions::{ diff --git a/crates/starknet_sequencer_node/src/config/config_test.rs b/crates/starknet_sequencer_node/src/config/config_test.rs index 8043e9119a..b84fe21dd4 100644 --- a/crates/starknet_sequencer_node/src/config/config_test.rs +++ b/crates/starknet_sequencer_node/src/config/config_test.rs @@ -6,9 +6,9 @@ use assert_json_diff::assert_json_eq; use assert_matches::assert_matches; use colored::Colorize; use infra_utils::path::resolve_project_relative_path; +use papyrus_config::SerializedParam; use papyrus_config::dumping::SerializeConfig; use papyrus_config::validators::config_validate; -use papyrus_config::SerializedParam; use rstest::rstest; use starknet_batcher::block_builder::BlockBuilderConfig; use starknet_batcher::config::BatcherConfig; @@ -21,9 +21,9 @@ use crate::config::component_execution_config::{ ReactiveComponentExecutionConfig, ReactiveComponentExecutionMode, }; use crate::config::node_config::{ - SequencerNodeConfig, CONFIG_NON_POINTERS_WHITELIST, CONFIG_POINTERS, DEFAULT_CONFIG_PATH, + CONFIG_NON_POINTERS_WHITELIST, CONFIG_POINTERS, DEFAULT_CONFIG_PATH, SequencerNodeConfig, }; -use crate::config::test_utils::{create_test_config_load_args, RequiredParams}; +use crate::config::test_utils::{RequiredParams, create_test_config_load_args}; const LOCAL_EXECUTION_MODE: ReactiveComponentExecutionMode = ReactiveComponentExecutionMode::LocalExecutionWithRemoteDisabled; @@ -153,7 +153,9 @@ fn test_validate_batcher_config_failure() { }; let error = config.validate().unwrap_err(); - assert!(error - .to_string() - .contains("input_stream_content_buffer_size must be at least tx_chunk_size")); + assert!( + error + .to_string() + .contains("input_stream_content_buffer_size must be at least tx_chunk_size") + ); } diff --git a/crates/starknet_sequencer_node/src/config/node_config.rs b/crates/starknet_sequencer_node/src/config/node_config.rs index 8e5367a332..34c2afaf41 100644 --- a/crates/starknet_sequencer_node/src/config/node_config.rs +++ b/crates/starknet_sequencer_node/src/config/node_config.rs @@ -7,14 +7,14 @@ use std::vec::Vec; use clap::Command; use infra_utils::path::resolve_project_relative_path; use papyrus_config::dumping::{ - append_sub_config_name, generate_struct_pointer, ser_pointer_target_required_param, - set_pointing_param_paths, ConfigPointers, Pointers, SerializeConfig, + ConfigPointers, Pointers, SerializeConfig, append_sub_config_name, generate_struct_pointer, + ser_pointer_target_required_param, set_pointing_param_paths, }; use papyrus_config::loading::load_and_process_config; use papyrus_config::{ConfigError, ParamPath, SerializationType, SerializedParam}; use serde::{Deserialize, Serialize}; -use starknet_batcher::config::BatcherConfig; use starknet_batcher::VersionedConstantsOverrides; +use starknet_batcher::config::BatcherConfig; use starknet_consensus_manager::config::ConsensusManagerConfig; use starknet_gateway::config::{GatewayConfig, RpcStateReaderConfig}; use starknet_http_server::config::HttpServerConfig; diff --git a/crates/starknet_sequencer_node/src/main.rs b/crates/starknet_sequencer_node/src/main.rs index 3f01e87c83..443cd65120 100644 --- a/crates/starknet_sequencer_node/src/main.rs +++ b/crates/starknet_sequencer_node/src/main.rs @@ -1,8 +1,8 @@ use std::env::args; use std::process::exit; -use papyrus_config::validators::config_validate; use papyrus_config::ConfigError; +use papyrus_config::validators::config_validate; use starknet_sequencer_infra::trace_util::configure_tracing; use starknet_sequencer_node::config::node_config::SequencerNodeConfig; use starknet_sequencer_node::servers::run_component_servers; diff --git a/crates/starknet_sequencer_node/src/utils.rs b/crates/starknet_sequencer_node/src/utils.rs index 990ca27d90..9f2bbbf6da 100644 --- a/crates/starknet_sequencer_node/src/utils.rs +++ b/crates/starknet_sequencer_node/src/utils.rs @@ -1,8 +1,8 @@ -use crate::clients::{create_node_clients, SequencerNodeClients}; +use crate::clients::{SequencerNodeClients, create_node_clients}; use crate::communication::create_node_channels; use crate::components::create_node_components; use crate::config::node_config::SequencerNodeConfig; -use crate::servers::{create_node_servers, SequencerNodeServers}; +use crate::servers::{SequencerNodeServers, create_node_servers}; pub fn create_node_modules( config: &SequencerNodeConfig, diff --git a/crates/starknet_sierra_compile/src/command_line_compiler.rs b/crates/starknet_sierra_compile/src/command_line_compiler.rs index aebf9b3510..51143b929e 100644 --- a/crates/starknet_sierra_compile/src/command_line_compiler.rs +++ b/crates/starknet_sierra_compile/src/command_line_compiler.rs @@ -8,6 +8,9 @@ use cairo_lang_starknet_classes::contract_class::ContractClass; use cairo_native::executor::AotContractExecutor; use tempfile::NamedTempFile; +use crate::SierraToCasmCompiler; +#[cfg(feature = "cairo_native")] +use crate::SierraToNativeCompiler; use crate::config::SierraToCasmCompilationConfig; use crate::constants::CAIRO_LANG_BINARY_NAME; #[cfg(feature = "cairo_native")] @@ -16,9 +19,6 @@ use crate::errors::CompilationUtilError; use crate::paths::binary_path; #[cfg(feature = "cairo_native")] use crate::paths::output_file_path; -use crate::SierraToCasmCompiler; -#[cfg(feature = "cairo_native")] -use crate::SierraToNativeCompiler; #[derive(Clone)] pub struct CommandLineCompiler { diff --git a/crates/starknet_sierra_compile/src/compile_test.rs b/crates/starknet_sierra_compile/src/compile_test.rs index 642cd4e4b9..b579592530 100644 --- a/crates/starknet_sierra_compile/src/compile_test.rs +++ b/crates/starknet_sierra_compile/src/compile_test.rs @@ -7,13 +7,13 @@ use infra_utils::path::resolve_project_relative_path; use mempool_test_utils::{FAULTY_ACCOUNT_CLASS_FILE, TEST_FILES_FOLDER}; use rstest::rstest; +use crate::SierraToCasmCompiler; +#[cfg(feature = "cairo_native")] +use crate::SierraToNativeCompiler; use crate::command_line_compiler::CommandLineCompiler; use crate::config::SierraToCasmCompilationConfig; use crate::errors::CompilationUtilError; use crate::test_utils::contract_class_from_file; -use crate::SierraToCasmCompiler; -#[cfg(feature = "cairo_native")] -use crate::SierraToNativeCompiler; const SIERRA_TO_CASM_COMPILATION_CONFIG: SierraToCasmCompilationConfig = SierraToCasmCompilationConfig { max_bytecode_size: 81920 }; diff --git a/crates/starknet_sierra_compile/src/config.rs b/crates/starknet_sierra_compile/src/config.rs index e3601b6f8e..a90dd789a7 100644 --- a/crates/starknet_sierra_compile/src/config.rs +++ b/crates/starknet_sierra_compile/src/config.rs @@ -1,6 +1,6 @@ use std::collections::BTreeMap; -use papyrus_config::dumping::{ser_param, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, ser_param}; use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam}; use serde::{Deserialize, Serialize}; use validator::Validate; diff --git a/crates/starknet_state_sync/src/config.rs b/crates/starknet_state_sync/src/config.rs index 7a7061fb25..d434541ac2 100644 --- a/crates/starknet_state_sync/src/config.rs +++ b/crates/starknet_state_sync/src/config.rs @@ -1,6 +1,6 @@ use std::collections::BTreeMap; -use papyrus_config::dumping::{append_sub_config_name, SerializeConfig}; +use papyrus_config::dumping::{SerializeConfig, append_sub_config_name}; use papyrus_config::{ParamPath, SerializedParam}; use papyrus_network::NetworkConfig; use papyrus_p2p_sync::client::P2PSyncClientConfig; diff --git a/crates/starknet_state_sync/src/lib.rs b/crates/starknet_state_sync/src/lib.rs index 92be38b563..b9a213d1ac 100644 --- a/crates/starknet_state_sync/src/lib.rs +++ b/crates/starknet_state_sync/src/lib.rs @@ -2,9 +2,9 @@ pub mod config; pub mod runner; use async_trait::async_trait; +use papyrus_storage::StorageReader; use papyrus_storage::body::BodyStorageReader; use papyrus_storage::state::StateStorageReader; -use papyrus_storage::StorageReader; use starknet_api::block::BlockNumber; use starknet_sequencer_infra::component_definitions::ComponentRequestHandler; use starknet_state_sync_types::communication::{ diff --git a/crates/starknet_state_sync/src/runner/mod.rs b/crates/starknet_state_sync/src/runner/mod.rs index defced11d3..d53001fe4f 100644 --- a/crates/starknet_state_sync/src/runner/mod.rs +++ b/crates/starknet_state_sync/src/runner/mod.rs @@ -2,13 +2,13 @@ mod test; use async_trait::async_trait; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use papyrus_network::network_manager::{self, NetworkError}; use papyrus_p2p_sync::client::{P2PSyncClient, P2PSyncClientChannels, P2PSyncClientError}; use papyrus_p2p_sync::server::{P2PSyncServer, P2PSyncServerChannels}; -use papyrus_p2p_sync::{Protocol, BUFFER_SIZE}; -use papyrus_storage::{open_storage, StorageReader}; +use papyrus_p2p_sync::{BUFFER_SIZE, Protocol}; +use papyrus_storage::{StorageReader, open_storage}; use starknet_sequencer_infra::component_definitions::ComponentStarter; use starknet_sequencer_infra::errors::ComponentError;