Fuzzing und Invariant-Testing
Lernen Sie, wie eigenschaftsbasiertes Fuzzing und Invariant-Testing Randfehler in Smart Contracts aufdecken, die feste Unit-Tests übersehen, am Beispiel von Foundry
Fuzzing und Invariant-Testing ist eine kostenlose Blockchain Smart Contracts with Solidity-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Blockchain Smart Contracts with Solidity-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Blockchain Smart Contracts with Solidity-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
Limits of Example Tests
You have written unit tests with specific inputs. But attackers find the one input you did not try. Fixed examples cannot cover the huge space of possible values. This is where fuzzing helps.
What Is Fuzzing?
Fuzz testing runs a test many times with randomly generated inputs. Instead of asserting on one value, you assert a property that should hold for all inputs.
A Fuzz Test in Foundry
In Foundry, any test function parameter is automatically fuzzed. The framework feeds in many random values.
function testFuzz_DepositIncreasesBalance(uint256 amount) public {
vm.assume(amount > 0 && amount < 1e30);
vault.deposit(amount);
assertEq(vault.balanceOf(address(this)), amount);
}Bounding Inputs
Random values can be absurd (like the max uint256). Use vm.assume to discard bad inputs or bound to map a value into a valid range so tests stay meaningful.
function testFuzz_Transfer(uint256 amount) public {
amount = bound(amount, 1, token.balanceOf(address(this)));
token.transfer(bob, amount);
assertEq(token.balanceOf(bob), amount);
}Thinking in Properties
The shift is from 'with input X expect Y' to 'no matter the input, this rule holds'. Common properties:
- Total supply never changes on a transfer
- A user can never withdraw more than they deposited
- Balances never underflow
What Are Invariants?
An invariant is a property that must hold after any sequence of operations, not just one call. Invariant testing fires many random function calls in random order, then checks the invariant after each step.
Declaring an Invariant
In Foundry, functions prefixed with invariant_ are checked after each randomized call sequence.
function invariant_TotalSupplyEqualsSumOfBalances() public {
assertEq(token.totalSupply(), handler.sumOfBalances());
}The Handler Pattern
Raw random calls often revert or wander into useless states. A handler contract wraps the target with guided, valid actions and tracks expected totals (ghost variables) for the invariant to check.
contract Handler {
Token token;
uint256 public sumOfBalances;
function transfer(uint256 toSeed, uint256 amount) external {
// bounded, valid transfer logic that updates ghost totals
}
}Shrinking Failures
When a fuzzer finds a failing input, it shrinks it to the simplest counterexample. This makes the bug far easier to understand and reproduce than a random gigantic number.
Tuning Test Runs
More runs find deeper bugs but take longer. Configure run counts in foundry.toml for CI versus quick local checks.
[fuzz]
runs = 1000
[invariant]
runs = 256
depth = 50When to Use Each
Use fuzzing to harden individual functions against unexpected single inputs. Use invariant testing to verify system-wide rules survive any sequence of actions. Together they catch classes of bugs fixed tests never reach.
Quick Check
Test your understanding of property-based testing.
Recap
You learned fuzzing and invariant testing:
- Fuzzing runs functions with many random inputs against properties
vm.assumeandboundkeep inputs valid- Invariants check system rules across random call sequences
- Handlers guide actions; shrinking simplifies failures
These techniques uncover edge cases that example-based tests miss.
Häufig gestellte Fragen
Ist die Lektion „Fuzzing und Invariant-Testing“ kostenlos?
Ja — der vollständige Text von „Fuzzing und Invariant-Testing“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Blockchain Smart Contracts with Solidity-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Blockchain Smart Contracts with Solidity-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Fuzzing und Invariant-Testing“?
Lernen Sie, wie eigenschaftsbasiertes Fuzzing und Invariant-Testing Randfehler in Smart Contracts aufdecken, die feste Unit-Tests übersehen, am Beispiel von Foundry Du übst Blockchain Smart Contracts with Solidity mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Blockchain Smart Contracts with Solidity zu starten?
Keine Vorkenntnisse erforderlich. Blockchain Smart Contracts with Solidity auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Fuzzing und Invariant-Testing“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Blockchain Smart Contracts with Solidity-Lektion Code schreiben und ausführen?
Ja. Jede Blockchain Smart Contracts with Solidity-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Fortgeschrittenes Testing mit Foundry/Hardhat
- Grundlagen der formalen Verifikation
- Mainnet-Deployment und Monitoring
- Fuzzing und Invariant-Testing