Fuzzing e test degli invariant
Impari come il fuzzing basato sulle proprietà e i test degli invariant individuino nei smart contract bug nei casi limite che i test unitari fissi non rilevano, usando Foundry come framework di riferimento.
Fuzzing e test degli invariant è una lezione Blockchain Smart Contracts with Solidity gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Blockchain Smart Contracts with Solidity, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Blockchain Smart Contracts with Solidity include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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.
Domande Frequenti
La lezione «Fuzzing e test degli invariant» è gratuita?
Sì — il testo completo di «Fuzzing e test degli invariant» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Blockchain Smart Contracts with Solidity, passa a CoddyKit PRO. Il corso Blockchain Smart Contracts with Solidity include 4 lezioni in totale.
Cosa imparerò in «Fuzzing e test degli invariant»?
Impari come il fuzzing basato sulle proprietà e i test degli invariant individuino nei smart contract bug nei casi limite che i test unitari fissi non rilevano, usando Foundry come framework di rifer… Eserciti Blockchain Smart Contracts with Solidity con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Blockchain Smart Contracts with Solidity?
Non è richiesta alcuna esperienza precedente. Blockchain Smart Contracts with Solidity su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Fuzzing e test degli invariant»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Blockchain Smart Contracts with Solidity?
Sì. Ogni lezione Blockchain Smart Contracts with Solidity include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Test avanzati con Foundry/Hardhat
- Fondamenti della verifica formale
- Deployment e monitoraggio sulla mainnet
- Fuzzing e test degli invariant