Show contents
Chapter 4 of 6 · 20 min
Smart contracts, gas and reentrancy
By the end of this chapter, you'll be able to
- Explain what a smart contract is and why its execution must be deterministic
- Simulate a contract's execution with gas and a complete revert on error
- Replay a reentrancy attack in a simulation
- Fix the flaw with the checks-effects-interactions pattern and a lock
A program run by every node
A smart contract is a program deployed on the blockchain, with its own state (its variables) and its own balance. Anyone can call its functions by sending a transaction. Every node runs the call and must get exactly the same result: the code must therefore be deterministic (no local clock, no local randomness, no Internet access).
Each instruction costs gas, paid by the caller. Gas prevents a program from blocking the network with an infinite loop: when the planned gas runs out, execution stops. And a transaction is atomic: if an error occurs, all its effects are reverted (the gas consumed is still paid).
Otherwise, the new state is written into the block.
Text description of the animation
- The transaction is signed and broadcast like any other.
- The caller sets a limit and pays for the gas actually consumed.
- Every node runs the same code on the same state: the results must be identical.
- On error or when gas runs out, no change remains.
- Otherwise, the new state is written into the block.
import copy
class OutOfGas(Exception):
pass
class Chain:
"""Mini execution machine: accounts, contracts, gas and revert."""
def __init__(self, balances):
self.balances, self.contracts = dict(balances), {}
def deploy(self, name, contract):
self.contracts[name] = contract
self.balances.setdefault(name, 0)
def transfer(self, sender, recipient, amount):
if self.balances[sender] < amount:
raise ValueError("insufficient balance")
self.balances[sender] -= amount
self.balances[recipient] = self.balances.get(recipient, 0) + amount
if recipient in self.contracts and hasattr(self.contracts[recipient], "receive"):
self.contracts[recipient].receive(self, sender, amount) # a contract can react to a payment
def call(self, caller, contract, function, value=0, gas=50_000):
backup = copy.deepcopy((self.balances, {n: vars(c) for n, c in self.contracts.items()}))
self.gas = gas
try:
self.transfer(caller, contract, value)
getattr(self.contracts[contract], function)(self, caller, value)
return f"ok (gas used: {gas - self.gas})"
except Exception as error:
balances, states = backup # complete revert
self.balances = balances
for n, state in states.items():
vars(self.contracts[n]).clear()
vars(self.contracts[n]).update(state)
return f"reverted: {type(error).__name__} {error}"
def consume(self, n):
self.gas -= n
if self.gas < 0:
raise OutOfGas("out of gas")
class PiggyBank:
def __init__(self):
self.deposits = {}
def deposit(self, ch, caller, value):
ch.consume(5_000)
self.deposits[caller] = self.deposits.get(caller, 0) + value
def withdraw(self, ch, caller, value):
ch.consume(5_000)
amount = self.deposits.get(caller, 0)
if amount == 0:
raise ValueError("nothing to withdraw")
self.deposits[caller] = 0
ch.transfer("piggybank", caller, amount)
def loop(self, ch, caller, value):
while True:
ch.consume(3) # an infinite loop… stops when gas runs out
ch = Chain({"Kofi": 10_000, "Mei": 4_000})
ch.deploy("piggybank", PiggyBank())
print(ch.call("Kofi", "piggybank", "deposit", 6_000))
print(ch.call("Mei", "piggybank", "withdraw"))
print(ch.call("Mei", "piggybank", "loop", 1_000))
print(ch.call("Kofi", "piggybank", "withdraw"))
print("balances:", ch.balances)
ok (gas used: 5000)
reverted: ValueError nothing to withdraw
reverted: OutOfGas out of gas
ok (gas used: 5000)
balances: {'Kofi': 10000, 'Mei': 4000, 'piggybank': 0}
Mei's infinite loop stops for lack of gas, and the 1,000 sent is reverted with the rest: the piggy bank keeps only the state from before the call. This combination of gas and atomicity is what lets thousands of nodes run code written by anyone.
Mini-lab: the price of a loopPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: the fixed vault
Write SafeVault, a fixed version of the vault: the withdraw function applies the checks-effects-interactions pattern and uses a lock (self.locked) that raises an error if it is called again while running. Replay the attack with the same attacker and show that the attacker only gets back its own deposit.
Hint 1
withdraw: read the amount, check it is positive, set self.deposits[who] = 0, then only transfer.Hint 2
if self.locked: raise RuntimeError("reentrancy forbidden"), then self.locked = True before the transfer and self.locked = False in a finally block.Show the solution and common mistakes
class Chain:
def __init__(self, balances):
self.balances, self.contracts = dict(balances), {}
def transfer(self, sender, recipient, amount):
if self.balances[sender] < amount:
raise ValueError("insufficient balance")
self.balances[sender] -= amount
self.balances[recipient] = self.balances.get(recipient, 0) + amount
if recipient in self.contracts:
self.contracts[recipient].receive(self, sender, amount)
class SafeVault:
def __init__(self):
self.deposits, self.locked = {}, False
def deposit(self, ch, who, amount):
ch.transfer(who, "vault", amount)
self.deposits[who] = self.deposits.get(who, 0) + amount
def withdraw(self, ch, who):
if self.locked:
raise RuntimeError("reentrancy forbidden")
amount = self.deposits.get(who, 0) # checks
if amount <= 0:
raise ValueError("nothing to withdraw")
self.deposits[who] = 0 # effects
self.locked = True
try:
ch.transfer("vault", who, amount) # interactions, last
finally:
self.locked = False
def receive(self, ch, sender, amount):
pass
class Attacker:
def __init__(self):
self.attempts = []
def receive(self, ch, sender, amount):
if sender == "vault" and ch.balances["vault"] >= 1_000:
try:
ch.contracts["vault"].withdraw(ch, "attacker")
except Exception as e:
self.attempts.append(f"{type(e).__name__}: {e}")
ch = Chain({"Awa": 5_000, "Kofi": 4_000, "attacker": 1_000, "vault": 0})
attacker = Attacker()
ch.contracts = {"vault": SafeVault(), "attacker": attacker}
for who, a in [("Awa", 5_000), ("Kofi", 4_000), ("attacker", 1_000)]:
ch.contracts["vault"].deposit(ch, who, a)
ch.contracts["vault"].withdraw(ch, "attacker")
print("vault:", ch.balances["vault"], "| attacker:", ch.balances["attacker"])
print("reentrancy attempt:", attacker.attempts)
vault: 9000 | attacker: 1000
reentrancy attempt: ['RuntimeError: reentrancy forbidden']
The two protections complement each other: thanks to the checks-effects-interactions order, a second withdrawal would find a zero deposit anyway; the lock even blocks entry into the function. The vault keeps Awa's and Kofi's 9,000.
Common mistakes:
- Resetting the lock to
Falseoutside afinally: if the transfer fails, the vault stays locked forever. - Protecting
withdrawbut not another function that reads the same deposits (transfer_deposit, for example): the attacker comes in through the side door ("cross-function" reentrancy). - Believing that a transfer to an "ordinary" address cannot call the contract back: you do not always know in advance whether an address is a contract.
Summary
- 1A smart contract is a program deployed on the chain, run identically by every node.
- 2Each instruction costs gas; an error or exhausted gas reverts all the transaction's effects.
- 3An external call before the state update opens the door to reentrancy, as with The DAO.
- 4Apply the checks-effects-interactions pattern, plus a lock against reentrancy.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.