6 - Security I.
Today you look at contracts the way an attacker does, and prove what you find with tests. Unit tests in Wake with full coverage are 5 points of semestral Task 1: everything you need for them is on this page.
Tutorial objectives
We will see what an audit is, the ways software is tested, and the classic exploits in smart contracts, each with a short piece of code. Then we install Wake 5, test and break one example together, and you find and prove the bugs in one contract yourself.
Tutorial pre-requisites
- Python 3.10 or newer (https://www.python.org/downloads/)
- Wake 5, installed below
- VS Code with the Solidity (Wake) extension (https://marketplace.visualstudio.com/items?itemName=AckeeBlockchain.tools-for-solidity), for coverage
- Solidity from tutorials 4 and 5, and a little Python
Auditing
An audit is a review of a contract before it holds money: finding code that does something it shouldn’t, in a way someone can use. The auditor understands what the contract should do, runs the automatic tools, reads every line, proves each problem with a test, and reports it with a severity and a fix. Your semestral Task II is exactly this. For every function, ask:
| Question | What goes wrong |
|---|---|
| Who can call it? | a missing onlyOwner: anyone can withdraw or change settings |
| Is the condition right? | < instead of <=, a check on the wrong variable |
| What changes, and in what order? | ETH sent before the balance is lowered: reentrancy |
| What if the input is strange? | 0, the largest number, my own contract as the address |
| What does it trust? | a price from another contract, tx.origin, a balance someone can borrow |
Ways to test
| What you know | Testing | Fuzzing | |
|---|---|---|---|
| Black-box | only inputs and outputs, like a user | tests from the documentation | random inputs, no feedback |
| Grey-box | a little of the inside | you know the parts, not every line | random inputs, keeps the ones that reach new code (coverage) |
| White-box | all of the code | tests written to cover every branch | inputs computed from the code itself (symbolic execution) |
A unit test uses inputs you choose and checks one exact result. A fuzz test lets the computer call the contract with random inputs in random order, and checks an invariant: a rule that must always hold, for example "the bank always holds at least what it owes". Unit tests find the bugs you thought of; fuzz tests find the ones you didn’t. Advanced fuzzing is tutorial 9.
Static analysis doesn’t run the code: a program reads the source and checks it against rules called detectors (wake detect, Slither, Aderyn). It is fast, but it misses logic bugs and reports things that are fine.
Common exploits
A contract is harder to keep safe than a web app: its code is public, it can’t be patched after deployment, it holds the money itself, anyone can call it, and every transaction is visible before it runs. Here are the classic attacks.
Overflow and underflow
Numbers have a fixed size. Before Solidity 0.8 nothing checked the maths, so Bob, who has 0 tokens, could send 1 and end up with the largest possible number:
pragma solidity 0.7.6; // before 0.8: no overflow checks
contract OldToken {
mapping(address => uint256) public balances;
function transfer(address to, uint256 amount) external {
balances[msg.sender] -= amount; // Bob: 0 - 1 = 2^256 - 1, a huge balance
balances[to] += amount;
}
}Since 0.8 this reverts. It still wraps inside unchecked { }, in assembly, and when you cast to a smaller type: uint64(x) silently cuts off the top bits. Tokens have 18 decimals (1 token = 1018 units, like ether and wei), so a uint64 holds only about 18.4 tokens.
Reentrancy
The bank pays out before it writes the payout down:
function withdraw() external {
uint256 amount = balances[msg.sender];
(bool ok, ) = msg.sender.call{value: amount}(""); // 1. send: the receiver's code runs
require(ok);
balances[msg.sender] = 0; // 2. only now: update the balance
}Sending ETH to a contract runs its receive(). The attacker’s receive() calls withdraw() again, and the balance still says the old number, so the bank pays again, and again, until it is empty, all in one transaction. The fix is the rule from tutorial 5: record first, send last (set the balance to 0, then send), or a nonReentrant guard. In 2016 this drained The DAO of 3.6M ETH.
Rounding
A share is your slice of a pot: if there are 4 shares and you own 1, a quarter of the ETH is yours. Solidity has no decimals and every division rounds down: 1 / 3 * 3 is 0, but 1 * 3 / 3 is 1. In a vault, (myShares / totalShares) * balance pays 0 to everyone who doesn’t own the whole pool; myShares * balance / totalShares is right. Multiply first, divide last.
Front-running
A transaction doesn’t run when you send it. It waits in the mempool, a public waiting room where every node can see it with all its arguments. A validator then picks the order of the next block, putting the transactions that pay a higher tip first. So anyone who sees your transaction can pay to go before it.
The simplest case is a copied answer. This contract pays 10 ETH to whoever first sends the answer to a puzzle:
bytes32 public answerHash; // keccak256 of the answer, set when deployed
function solve(string calldata answer) external {
require(keccak256(bytes(answer)) == answerHash, "wrong answer");
answerHash = 0; // only the first one wins
(bool ok, ) = msg.sender.call{value: address(this).balance}("");
require(ok);
}Alice sends solve("festival"). A bot reads "festival" in the mempool, sends the same call with a higher tip, and runs first: the bot gets the 10 ETH and Alice gets "wrong answer". The fix is commit–reveal: first send only a hash of your answer and your address, which reveals nothing, and reveal the answer later. A copied reveal fails, because the hash contains Alice’s address, not the bot’s.
The second case happens on an exchange, so first: how do you swap tokens? A pool is a contract that holds two tokens, here 1,000 A and 1,000 B. You call swapAforB(100), and in that one call the pool takes your 100 A and sends B straight to your wallet; there is nothing to withdraw later. In a pool contract these are two lines:
tokenA.transferFrom(msg.sender, address(this), amountIn); // your A goes into the pool
tokenB.transfer(msg.sender, amountOut); // B goes to youHow much B? The pool keeps A × B the same: 1,000 × 1,000 = 1,000,000. With 1,100 A it may keep only 1,000,000 ÷ 1,100 = 909.09 B, so the other 90.91 B are yours. Now let three people swap 100 A each, one after another:
| You swap | Pool now holds | B it may keep: 1,000,000 ÷ A | You get | |
|---|---|---|---|---|
| start | 1,000 A | 1,000 B | ||
| 1st swap | 100 A | 1,100 A | 909.09 B | 90.91 B |
| 2nd swap | 100 A | 1,200 A | 833.33 B | 75.76 B |
| 3rd swap | 100 A | 1,300 A | 769.23 B | 64.10 B |
Same 100 A, less B every time. Real pools also keep a fee, often 0.3%: with it the first swap gets 90.66 B.
So whoever swaps just before you makes your price worse. Bots use this in a sandwich: when a victim swaps 100 A for B, the bot buys first and sells right after:
| Order | Who | Does | Result |
|---|---|---|---|
| 1 | attacker (higher tip) | swaps 50 A for B | B is now more expensive |
| 2 | victim | swaps 100 A for B | gets 82.60 B instead of 90.66 |
| 3 | attacker (lower tip) | swaps all its B back to A | ends 9.35 A richer |
The defence is on the victim’s side: say the least you accept, so the swap reverts if someone moved the price. That is the slippage setting in every DEX app:
require(amountOut >= minAmountOut, "slippage"); // the victim says the least they acceptDenial of service
Nothing is stolen; the function just can never succeed again:
address[] public winners;
function payEveryone() external {
for (uint256 i = 0; i < winners.length; i++) {
(bool ok, ) = winners[i].call{value: 1 ether}("");
require(ok, "payment failed"); // one winner that refuses ETH: nobody gets paid
}
}If one winner is a contract that refuses ETH, its payment fails and the whole loop reverts, every time. A list that anyone can make longer breaks the same way, once the loop needs more gas than a block has. The fix: each winner withdraws their own prize (pull, tutorial 5).
Flash loans
A flash loan lends any amount with no collateral, as long as it is paid back in the same transaction. The lender is safe because a transaction is all or nothing: if the loan isn’t repaid at the end, everything reverts as if it never happened. Why borrow for one transaction? To do something big without money of your own. The classic case is arbitrage: token B costs 1.00 A on one exchange and 1.02 A on another. In one transaction you borrow 1,000,000 A, swap it for B on the first exchange, swap the B back on the second for about 1,020,000 A, repay the loan and a small fee, and keep the rest. That is rough, because big swaps move the price, and if the trade fails, everything reverts and you lose only the gas. You need no capital, the lender earns a fee with no risk, and the two exchanges end up with the same price. Flash loans are also used to pay off a loan and free its collateral, or to move a loan to another protocol.
But they also mean that for one transaction anyone can hold millions of tokens. A contract that trusts how many tokens someone holds right now can be fooled, for example a vote with governance tokens, where 1 token is 1 vote:
function vote(uint256 proposal) external {
votes[proposal] += token.balanceOf(msg.sender); // held right now: can be borrowed
}
function execute(uint256 proposal) external {
require(votes[proposal] > token.totalSupply() / 2, "no majority");
proposals[proposal].action(); // e.g. "send the treasury to me"
}In one transaction the attacker borrows a million tokens, votes, executes "send the treasury to me" and repays the loan. Beanstalk lost about $180M exactly like this in 2022. The fix: count the votes someone had before the vote started (a snapshot), and wait before executing.
And many more
Missing access control is the most common finding of all. Others: tx.origin (tutorial 5), price manipulation, signature replay and compiler bugs. Collections of known issues: OWASP Smart Contract Top 10, the SWC Registry, and write-ups of real hacks on rekt.news.
Wake
Wake is a Python framework for Solidity by ack3, used in our audits. You write tests in Python and run them on a local chain; Wake generates a Python class for every contract (pytypes), and also has a fuzzer and detectors. Wake 5 runs the EVM itself, so you don’t need anything else. Your semestral tests must be written in Wake.
Install
Install Wake as a normal command on your computer, and name the version: plain pip install eth-wake installs the older Wake 4.
pip install eth-wake==5.0.0rc4
wake --versionIf Windows says wake is not found, Python was installed without being added to PATH: reinstall it and tick Add python.exe to PATH.
sudo apt install pipx # macOS: brew install pipx
pipx ensurepath # then open a new terminal
pipx install eth-wake==5.0.0rc4
wake --versionOn Linux and macOS the system Python refuses pip install for programs, so pipx installs Wake as a normal command instead.
Commands
| Command | What it does |
|---|---|
wake up pytypes | compile and generate the Python classes; run it again after every Solidity change (-w keeps watching) |
wake test | run every test in tests/ |
wake test tests/test_bank.py | run one file; wake test tests/test_bank.py::test_deposit runs one test |
wake test -s / wake test -d | show your print output / open a debugger where a test fails |
wake test --cov 1 | measure coverage: which lines your tests ran |
wake test -S <seed> | run a fuzz test again with the same random numbers |
wake detect all | run every detector; wake detect reentrancy runs one |
Your first test
The example in class is SimpleBank: users deposit ETH and withdraw it. This test is already in tests/test_bank.py:
from wake.testing import *
from pytypes.contracts.SimpleBank import SimpleBank # made by `wake up pytypes`
@chain.connect() # a fresh local chain for this test
def test_deposit():
alice, bob = chain.accounts[0:2] # name the first 2 of the 10 test accounts
bank = SimpleBank.deploy(from_=alice) # deploy, sent by Alice
bank.deposit(from_=bob, value="1 ether") # Bob calls deposit() with 1 ETH
assert bank.balances(bob) == Wei.parse("1 ether") # check: the bank owes Bob 1 ETH
with must_revert(Error("deposit amount must be positive")): # this must revert
bank.deposit(from_=bob, value=0)chain.accounts is a list of 10 ready-made test accounts, each with 10,000 test ETH. [0:2] takes the first two and names them: alice is account 0 and bob account 1. Need more, for example for many fans in your semestral task? Ask for them when the chain starts, @chain.connect(accounts=50), or create a fresh account at any time with Account.new() (it starts with 0 ETH, so give it a balance). A test passes when it reaches the end without an error. Run just this one with wake test tests/test_bank.py::test_deposit. Don’t name a helper function setup: pytest runs a function with that name before the chain exists.
How to
| You want to | In Wake |
|---|---|
| get more than 10 accounts | @chain.connect(accounts=50), or fan = Account.new() (starts with 0 ETH) |
| deploy a contract | bank = SimpleBank.deploy(from_=alice) |
| deploy with constructor arguments | thief = BankAttacker.deploy(bank, from_=attacker) |
| call a function from an account | bank.withdraw(Wei.parse("0.5 ether"), from_=bob) |
| call it and attach ETH | bank.deposit(from_=bob, value="1 ether") |
| send plain ETH, no function | contract.transact(value="1 ether", from_=bob): runs its receive() |
| read a value (a view function) | bank.balances(bob), bank.getBalance(): no transaction |
| write an amount as an argument | Wei.parse("0.5 ether"); only value= takes text |
| get the result of a transaction | tx = bank.withdraw(…), then tx.return_value |
| check a value or a balance | assert bank.balances(bob) == Wei.parse("1 ether"), bob.balance |
| expect a revert | with must_revert(Error("insufficient balance")): and the call indented below it |
| expect a custom error or a panic | must_revert(MyContract.NotOwner), must_revert(PanicCodeEnum.UNDERFLOW_OVERFLOW) |
| check an event | assert SimpleBank.Deposit(bob.address, 10**18) in tx.events |
| hash a string like Solidity | keccak256(b"festival") |
| move time forward | chain.mine(lambda t: t + 3600): one hour later |
| give an account ETH | bob.balance = Wei.parse("10 ether") |
| see what happened | print(tx.call_trace), tx.gas_used |
Coverage
Coverage tells you which lines your tests ran. Run wake test --cov 1 tests/test_bank.py; it writes wake-coverage.cov. In VS Code press Ctrl+Shift+P and run Show Coverage: every line is marked as run or not run. Write a test for every line that wasn’t, and run wake up pytypes again after changing a contract, or the marks land on the wrong lines. A modifier’s _; always shows as not covered.
Full coverage doesn’t mean safe: test_deposit and test_withdraw run all 9 statements of SimpleBank, every test passes, and the bank can still be emptied with reentrancy (see the reentrancy example above).
A fuzz test
You won’t need one for the semestral task, and advanced fuzzing is tutorial 9, but this is what one looks like. A fuzz test is a class: pre_sequence runs before every sequence, each @flow is one random action, and each @invariant is checked after every flow. This one makes random deposits (and, in the full version, withdrawals) and checks that it always holds exactly what it owes:
class BankFuzzTest(FuzzTest):
def pre_sequence(self): # before every sequence: a fresh bank
self.bank = SimpleBank.deploy(from_=chain.accounts[0])
self.owed = {a: 0 for a in chain.accounts} # what the bank should owe each account
@flow() # one random action; also flow_withdraw
def flow_deposit(self):
user, amount = random_account(), random_int(1, 10**18)
self.bank.deposit(from_=user, value=amount)
self.owed[user] += amount
@invariant() # checked after every flow
def invariant_bank_holds_what_it_owes(self):
assert self.bank.balance == sum(self.owed.values())
def test_bank_fuzz():
BankFuzzTest().run(sequences_count=10, flows_count=50)When a fuzz test fails, Wake prints the random seed; wake test -S <seed> repeats exactly that run.
Hands-on exercise
Clone the tutorial repository, then run wake up pytypes and wake test: 9 tests pass before you start. contracts/SimpleBank.sol and tests/test_bank.py are the example from class. Your exercise is contracts/ClubVault.sol, the vault of a student club: members deposit ETH and collect points, the owner pays prizes, and there is a weekly puzzle. It has six bugs, one for each exploit on this page. All six tests are in tests/test_club_vault.py, with the setup written and a TODO:
| Test | The question | |
|---|---|---|
| 1 | test_anyone_can_become_owner | Mallory is not the owner. Can she take everything? |
| 2 | test_points_underflow | Alice has 10 points and spends 15. How many are left? |
| 3 | test_share_rounds_to_zero | Alice owns half of 2 ETH. What does shareOf say? |
| 4 | test_one_winner_blocks_everyone | One winner refuses ETH. Does anyone get paid? |
| 5 | test_bot_copies_the_answer | A bot copies Alice’s answer. Who gets the prize? |
| bonus | test_drain_the_vault | Reentrancy, like the bank: write your own attacker contract |
Bonus points: prove all five, +1. Prove the reentrancy, +1.
For each one: read the contract, write a test that makes the bug happen and assert what actually happens, run it alone with wake test -s tests/test_club_vault.py::test_points_underflow (with your test’s name), then fix the contract, run wake up pytypes, and change the test so it expects the safe behaviour.
Recommended reading and resources
- Wake documentation (https://ack3.ai/wake/docs/latest)
- Getting started with testing (https://ack3.ai/wake/docs/latest/testing-framework/getting-started/)
- Fuzzing (https://ack3.ai/wake/docs/latest/testing-framework/fuzzing/)
- Coverage analysis (https://ack3.ai/wake/docs/latest/testing-framework/coverage-analysis/)
- Solidity security considerations (https://docs.soliditylang.org/en/latest/security-considerations.html)
- List of known Solidity compiler bugs (https://docs.soliditylang.org/en/latest/bugs.html)
- OWASP Smart Contract Top 10 (https://owasp.org/www-project-smart-contract-top-10/)
- Rekt, write-ups of real hacks (https://rekt.news/)