Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable all testing modes by default, update property mode testing, improve UX, allow for contracts to have starting balances, and fix coverage panic #216

Merged
merged 18 commits into from
Feb 20, 2024

Conversation

anishnaik
Copy link
Collaborator

@anishnaik anishnaik commented Aug 30, 2023

Here are the following changes:

  1. All testing modes are enabled by default. You can only disable them through the config file. The --assertion-mode and --optimization-mode flags were removed to simplify the CLI. First time users should not have to worry about disabling/enabling different testing modes. This PR closes Merge property and assertion mode #191.
  2. The requirements for a property test have now changed. A property test no longer has to return a boolean. It only has to start with a user-defined test prefix and must take no arguments. However, the testing provider will still check to see if the function returns true/false. Thus, we maintain backwards compatibility while pushing towards a new testing paradigm. The default test prefix has been changed from fuzz_ to property_. This PR closes Rename fuzz_ default #182.
  3. deploymentOrder has been renamed to targetContracts. This is purely a UX change to make it easier for people to understand what it means. The --target flag has been changed to --compilation-target to make the differentiation between --target-contracts and --compilation-target a bit easier.
  4. Target contracts can now have a starting balance through the targetContractsBalances config option. Each index in the targetContracts array is associated with the same index in the targetContractsBalances array. Thus, if you have [A, B, C] as your targetContracts and targetContractsBalances is [0, 1e18, 2e18] then A will have 0 wei, B will have 1 ether, and C will have 2 ether. This PR closes Debugging "contract deployment tx returned a failed status: execution reverted module=fuzzer" #212. This PR closes Feature Request: Starting balance for fuzzing contract #213.
  5. Fixed the coverage tracer bug. This PR closes Medusa crash when deploying contract inside target contract constructor #211. This PR closes Crash on "coverageEnabled": true #299.
  6. We now encode byte arrays and fixed byte arrays as hex strings.

Closes #145

Summary by CodeRabbit

  • New Features
    • Introduced utility functions to identify optimization and property tests.
    • Added the ability to send ether to payable constructors during deployment in test contracts.
  • Enhancements
    • Improved flag naming and descriptions for clarity in command usage.
    • Enhanced JSON marshaling and unmarshaling for fuzzing configurations with additional fields and validation checks.
    • Refined coverage calculation logic to accurately display 0% coverage when applicable.
    • Adjusted display logic for return data in execution traces for better clarity.
  • Refactor
    • Renamed numerous functions across test contracts to align with property testing terminology.
    • Updated logic to handle renamed flags and configurations throughout the codebase.
    • Modified ABI value encoding for byte types to use hexadecimal strings.
  • Bug Fixes
    • Fixed an issue in coverage maps handling where exceeding the program counter size now returns false without an error.
  • Chores
    • Updated global logger initialization to improve logging behavior.

- created testing provider utils file to evaluate whether an abi.method is an optimization / property test
- updated fuzzer tests
- made default property test prefix "invariant_"
@anishnaik anishnaik requested a review from Xenomega as a code owner August 30, 2023 13:59
@anishnaik anishnaik changed the title Merge testing modes Enable all testing modes by default, update property mode testing, improve UX, and allow for contracts to have starting balances Aug 31, 2023
@anishnaik anishnaik changed the title Enable all testing modes by default, update property mode testing, improve UX, and allow for contracts to have starting balances Enable all testing modes by default, update property mode testing, improve UX, allow for contracts to have starting balances, and fix coverage panic Sep 1, 2023
@anishnaik
Copy link
Collaborator Author

Need to fix bug with target balances such that it accepts scientific notation instead of hex values.

# Conflicts:
#	fuzzing/config/config.go
#	fuzzing/fuzzer.go
#	fuzzing/fuzzer_test.go
#	go.mod
Copy link

coderabbitai bot commented Feb 9, 2024

Walkthrough

The overarching update focuses on refining and enhancing a fuzzing framework. Key modifications include renaming flags and functions for clarity, improving JSON marshaling for configuration, and adjusting logic across various components to better handle contract deployment, testing modes, and value generation. These changes streamline the framework's usability and functionality, making it more intuitive and effective for users aiming to identify vulnerabilities in smart contracts.

Changes

Files Changes Summary
cmd/fuzz_flags.go, cmd/init_flags.go Renamed flags for clarity (target to compilation-target, deployment-order to target-contracts), removed some flags, and updated flag descriptions.
fuzzing/config/..., fuzzing/config_defaults.go, gen_fuzzing_config.go Enhanced FuzzingConfig struct and related configurations, including renaming fields, adding new imports, and improving JSON marshaling.
fuzzing/coverage/... Adjusted coverage calculation logic and simplified code handling in coverage maps.
fuzzing/executiontracer/execution_trace.go, fuzzing/fuzzer.go, fuzzing/fuzzer_test.go Updated logic for return data display, global logger configuration, and fuzzer settings related to testing modes and contract deployment.
fuzzing/test_case_... Refactored logic for test case providers, including updates for optimization, property, and assertion testing.
fuzzing/testdata/contracts/... Renamed functions across various test contracts to align with the updated testing approach (fuzz_ prefix changed to property_). Also introduced new test contracts.
fuzzing/valuegeneration/abi_values.go, logging/logger.go, utils/testing_provider_utils.go Modified value generation for ABI types, updated logger initialization, and introduced utility functions for test identification.

"In a codebase vast and wide, 🌌
Changes bloom like spring outside. 🌸
Renames, refactors, all in stride,
With every commit, our codebase thrived. 🚀"

  • 🐰💻

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 22

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between e471c52 and 931cce6.
Files ignored due to path filters (1)
  • go.sum is excluded by: !**/*.sum
Files selected for processing (39)
  • cmd/fuzz_flags.go (6 hunks)
  • cmd/init_flags.go (1 hunks)
  • fuzzing/config/config.go (7 hunks)
  • fuzzing/config/config_defaults.go (3 hunks)
  • fuzzing/config/gen_fuzzing_config.go (1 hunks)
  • fuzzing/coverage/coverage_maps.go (2 hunks)
  • fuzzing/coverage/report_generation.go (1 hunks)
  • fuzzing/executiontracer/execution_trace.go (1 hunks)
  • fuzzing/fuzzer.go (7 hunks)
  • fuzzing/fuzzer_test.go (26 hunks)
  • fuzzing/test_case_assertion_provider.go (5 hunks)
  • fuzzing/test_case_optimization_provider.go (4 hunks)
  • fuzzing/test_case_property_provider.go (4 hunks)
  • fuzzing/testdata/contracts/assertions/assert_and_property_test.sol (1 hunks)
  • fuzzing/testdata/contracts/chain/tx_out_of_gas.sol (1 hunks)
  • fuzzing/testdata/contracts/corpus_mutation/specific_call_sequence.sol (1 hunks)
  • fuzzing/testdata/contracts/deployments/deploy_payable_constructors.sol (1 hunks)
  • fuzzing/testdata/contracts/deployments/deployment_order.sol (2 hunks)
  • fuzzing/testdata/contracts/deployments/deployment_with_args.sol (2 hunks)
  • fuzzing/testdata/contracts/deployments/inner_deployment.sol (1 hunks)
  • fuzzing/testdata/contracts/deployments/inner_deployment_on_construction.sol (1 hunks)
  • fuzzing/testdata/contracts/deployments/inner_inner_deployment.sol (1 hunks)
  • fuzzing/testdata/contracts/deployments/internal_library.sol (1 hunks)
  • fuzzing/testdata/contracts/deployments/testing_scope.sol (2 hunks)
  • fuzzing/testdata/contracts/value_generation/generate_all_types.sol (1 hunks)
  • fuzzing/testdata/contracts/value_generation/match_addr_contract.sol (1 hunks)
  • fuzzing/testdata/contracts/value_generation/match_addr_exact.sol (1 hunks)
  • fuzzing/testdata/contracts/value_generation/match_addr_sender.sol (1 hunks)
  • fuzzing/testdata/contracts/value_generation/match_ints_xy.sol (1 hunks)
  • fuzzing/testdata/contracts/value_generation/match_payable_xy.sol (1 hunks)
  • fuzzing/testdata/contracts/value_generation/match_string_exact.sol (1 hunks)
  • fuzzing/testdata/contracts/value_generation/match_structs_xy.sol (1 hunks)
  • fuzzing/testdata/contracts/value_generation/match_uints_xy.sol (1 hunks)
  • fuzzing/testdata/contracts/vm_tests/block_hash_store_check.sol (1 hunks)
  • fuzzing/testdata/contracts/vm_tests/block_number_increasing.sol (1 hunks)
  • fuzzing/testdata/contracts/vm_tests/block_timestamp_increasing.sol (1 hunks)
  • fuzzing/valuegeneration/abi_values.go (1 hunks)
  • logging/logger.go (3 hunks)
  • utils/testing_provider_utils.go (1 hunks)
Files skipped from review due to trivial changes (2)
  • fuzzing/testdata/contracts/value_generation/match_addr_contract.sol
  • fuzzing/testdata/contracts/vm_tests/block_timestamp_increasing.sol
Additional comments: 31
fuzzing/testdata/contracts/assertions/assert_and_property_test.sol (1)
  • 8-8: Renaming fuzz_failing_property to property_failing_property aligns with the updated property testing requirements and the new default test prefix. This change is consistent and clear.
fuzzing/testdata/contracts/value_generation/match_addr_sender.sol (1)
  • 11-11: Renaming fuzz_never_specific_values to property_never_specific_values aligns with the updated property testing requirements and the new default test prefix. This change is consistent and clear.
fuzzing/testdata/contracts/value_generation/match_string_exact.sol (1)
  • 9-9: Renaming fuzz_never_specific_values to property_never_specific_values aligns with the updated property testing requirements and the new default test prefix. This change is consistent and clear.
fuzzing/testdata/contracts/deployments/inner_deployment.sol (1)
  • 4-4: Renaming fuzz_inner_deployment to property_inner_deployment aligns with the updated property testing requirements and the new default test prefix. This change is consistent and clear.
cmd/init_flags.go (1)
  • 13-24: Renaming the flag from "target" to "compilation-target" improves clarity and aligns with the PR objectives. The implementation correctly updates the project configuration based on this flag.
fuzzing/test_case_assertion_provider.go (4)
  • 8-8: Import of utils added.
  • 48-57: Modified logic in isTestableMethod to exclude optimization and property tests based on configurations.
  • 87-87: Updated usage of AssertionModesConfig to PanicCodeConfig in encounteredAssertionFailure.
  • 101-102: Changed verification of contracts to use TargetContracts instead of DeploymentOrder.
fuzzing/coverage/coverage_maps.go (1)
  • 375-378: Adjusted the setCoveredAt function to handle cases where the program counter exceeds the code size by returning false without an error message.
fuzzing/config/config.go (6)
  • 8-13: Added imports for hexutil, big, and os.
  • 59-64: Modified FuzzingConfig struct fields: Renamed DeploymentOrder to TargetContracts and added TargetContractsBalances.
  • 99-104: Added fuzzingConfigMarshaling struct for custom JSON marshaling.
  • 132-132: Renamed PropertyTestConfig to PropertyTestingConfig.
  • 146-147: Renamed AssertionModesConfig to PanicCodeConfig.
  • 275-279: Added validation checks and logging in ProjectConfig's Validate method.
fuzzing/test_case_property_provider.go (2)
  • 49-53: Refactored the logic to check for testing prefixes before attaching a test case provider.
  • 143-143: Updated the check for property test methods using a utility function from utils.
fuzzing/executiontracer/execution_trace.go (1)
  • 198-210: The added condition to handle outputArgumentsDisplayText being nil and callFrame.ReturnData length greater than 0 is correctly implemented. It ensures that return data is displayed appropriately when available, enhancing the method's functionality.
fuzzing/test_case_optimization_provider.go (4)
  • 8-10: Replacing the abi import with utils and introducing a new import for slices aligns with the changes in logic and functionality. Ensure that the utils package provides the necessary functionality previously covered by abi.
  • 49-52: The condition to return nil if no testing prefixes are provided simplifies the initialization process by avoiding unnecessary attachment of a test case provider. This is a logical optimization.
  • 134-138: The use of slices.Contains to check if the current contract is specified in the target contracts improves readability and maintainability of the code by utilizing standard library functions.
  • 141-141: The integration of utils.IsOptimizationTest for verifying optimization test methods aligns with the changes in import and ensures that the method identification logic is encapsulated within a utility function, promoting modularity.
logging/logger.go (1)
  • 59-63: Initializing structured and unstructured loggers with zerolog.New(nil) changes the default behavior of where log output is directed. Confirm that this change is intentional and that log output is correctly managed elsewhere in the code.
Verification successful

The grep results indicate that the loggers (structuredLogger and unstructuredLogger) are initially created with zerolog.New(nil) but are later configured with zerolog.MultiLevelWriter to manage log output destinations dynamically. This setup allows for flexible configuration of log output destinations, suggesting that the initial concern about log output management is addressed by the subsequent logger configuration. Therefore, the change to initialize loggers with nil appears to be intentional and part of a design to configure log output destinations dynamically.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that log output is correctly managed after initializing loggers with nil.
grep -r "structuredLogger" .
grep -r "unstructuredLogger" .

Length of output: 4134

fuzzing/fuzzer.go (3)
  • 6-9: Added imports for coverage, logging, colors, and zerolog are necessary for the new functionality and logging enhancements.
  • 111-129: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [95-126]

The global logger initialization and configuration have been updated. Ensure that the logger's level is correctly set based on the project configuration and that error handling is properly implemented when creating the log file.

Verification successful

The verification process has confirmed that the logger's level is correctly set based on the project configuration as shown in the provided code snippet. Additionally, the error handling when creating the log file is properly implemented, with the code checking for errors and logging them if any occur during the file creation process. This aligns with the review comment's concerns, verifying that both aspects are correctly addressed in the code.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that the logger's level is set correctly in all scenarios.
ast-grep --lang go --pattern $'logging.GlobalLogger.SetLevel($_)'
# Verify proper error handling when creating the log file.
ast-grep --lang go --pattern $'if $_, $_ := utils.CreateFile($_, $_); $_ != nil {'

Length of output: 572

* 334-353: > 📝 **NOTE** > This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [337-425]

Adjustments in handling target contracts and their balances during deployment need to ensure that the configuration is validated correctly, and that the deployment process accounts for specified balances. Verify that the deployment logic correctly handles the case where TargetContractsBalances is specified for each target contract.

Verification successful

The provided code snippet explicitly handles TargetContractsBalances by checking its length and setting the contractBalance for each target contract accordingly. This indicates that the deployment logic correctly accounts for specified balances for target contracts as described in the review comment. Therefore, the review comment is consistent with the codebase.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that the deployment logic correctly handles specified balances for target contracts.
ast-grep --lang go --pattern $'if len($_.config.Fuzzing.TargetContractsBalances) > $_ {'

Length of output: 434

fuzzing/valuegeneration/abi_values.go (1)
  • 450-451: The conversion of dynamic-sized bytes to a hex string using hex.EncodeToString is correct and aligns with the PR objectives of standardizing their representation.
fuzzing/fuzzer_test.go (3)
  • 239-239: The configuration update here aligns with the PR objectives by enabling AssertionTesting.Enabled and specifying EnableFFI for cheat code testing. This change is approved as it demonstrates an understanding of the testing framework's capabilities and the PR's goals.
  • 733-733: This test function appears to be a duplicate of the one starting at line 712, both testing block number increasing. Verify if this duplication is intentional or if it's a mistake. If it's a mistake, consider removing or modifying this test to cover a different aspect.
  • 752-752: The configuration updates here are appropriate for the test scenario. However, ensure that the explicit disabling of testing modes aligns with the PR objectives of enabling all testing modes by default.

fuzzing/valuegeneration/abi_values.go Show resolved Hide resolved
fuzzing/fuzzer_test.go Show resolved Hide resolved
fuzzing/fuzzer_test.go Show resolved Hide resolved
fuzzing/fuzzer_test.go Show resolved Hide resolved
fuzzing/fuzzer_test.go Show resolved Hide resolved
fuzzing/fuzzer_test.go Show resolved Hide resolved
fuzzing/fuzzer_test.go Show resolved Hide resolved
fuzzing/fuzzer_test.go Show resolved Hide resolved
fuzzing/fuzzer_test.go Show resolved Hide resolved
fuzzing/fuzzer_test.go Show resolved Hide resolved
fuzzing/config/config.go Outdated Show resolved Hide resolved
@Xenomega
Copy link
Member

Left some comments here! All looks good besides a few smaller nitpicks. Once you resolve them all, we can merge!

@anishnaik
Copy link
Collaborator Author

Need to fix bug with target balances such that it accepts scientific notation instead of hex values.

Will not be fixing this

@anishnaik anishnaik merged commit 04df3f1 into master Feb 20, 2024
9 checks passed
@anishnaik anishnaik deleted the dev/merge-assertion-and-property-mode branch February 20, 2024 17:28
Leeyah-123 pushed a commit to Leeyah-123/medusa that referenced this pull request Jun 4, 2024
…prove UX, allow for contracts to have starting balances, and fix coverage panic (crytic#216)

* - merged all three testing modes
- created testing provider utils file to evaluate whether an abi.method is an optimization / property test
- updated fuzzer tests
- made default property test prefix "invariant_"

* enable all testing modes, update fuzzer tests

* add verification for config

* improve config-related errors

* update deploymentOrder to targetContracts

* update edge case where coverage is 0/0 lines

* add support for payable constructors

* linting

* fix bug

* fix panic and improve return data printing in execution trace

* encode bytes and byteX as hex strings

* fix console

* updates from PR review

* change config language
s4nsec pushed a commit that referenced this pull request Jul 9, 2024
…prove UX, allow for contracts to have starting balances, and fix coverage panic (#216)

* - merged all three testing modes
- created testing provider utils file to evaluate whether an abi.method is an optimization / property test
- updated fuzzer tests
- made default property test prefix "invariant_"

* enable all testing modes, update fuzzer tests

* add verification for config

* improve config-related errors

* update deploymentOrder to targetContracts

* update edge case where coverage is 0/0 lines

* add support for payable constructors

* linting

* fix bug

* fix panic and improve return data printing in execution trace

* encode bytes and byteX as hex strings

* fix console

* updates from PR review

* change config language
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment