Show contents
Chapter 5 of 6 · 25 min
Project: auditing a lending protocol
By the end of this chapter, you'll be able to
- State a protocol's invariants: what must remain true whatever happens
- Write reproducible exploits that demonstrate each flaw on a test copy
- Fix the flaws: robust oracle, access control, solvency check
- Prove the fixes by replaying the same exploits
The method: invariants, exploits, fixes
The exploits become permanent tests: a future regression would be detected.
Text description of the animation
- The central promise: no loan is covered by less than its collateral.
- We assume a rich (flash loan), fast attacker who reads all the code.
- Each exploit starts from a fresh copy and measures the attacker's gain.
- We fix the cause, not the symptom, without rewriting the whole protocol.
- The exploits become permanent tests: a future regression would be detected.
Here is the protocol as it was handed to you, and three exploits. The "real" value of a TOKEN is 5 STABLE (the pool's equilibrium price). The attacker's gain is measured at that price.
class Pool:
def __init__(self, tokens, stables):
self.tokens, self.stables = tokens, stables
def price(self):
return self.stables / self.tokens
def buy_tokens(self, amount_in):
out = self.tokens - self.tokens * self.stables / (self.stables + amount_in * 0.997)
self.stables += amount_in; self.tokens -= out
return out
def sell_tokens(self, amount_in):
out = self.stables - self.tokens * self.stables / (self.tokens + amount_in * 0.997)
self.tokens += amount_in; self.stables -= out
return out
class SolidarityLend:
def __init__(self, pool, admin):
self.pool, self.admin = pool, admin
self.oracle = lambda: pool.price() # instantaneous price
self.collateral, self.debts, self.cash = {}, {}, 1_000_000
def deposit(self, who, tokens):
self.collateral[who] = self.collateral.get(who, 0) + tokens
def capacity(self, who):
return self.collateral.get(who, 0) * self.oracle() * 0.75 - self.debts.get(who, 0)
def borrow(self, who, amount):
if amount > self.capacity(who) or amount > self.cash:
raise ValueError("loan refused")
self.debts[who] = self.debts.get(who, 0) + amount
self.cash -= amount
return amount
def withdraw_collateral(self, who, tokens):
if tokens > self.collateral.get(who, 0):
raise ValueError("insufficient collateral")
self.collateral[who] -= tokens # no debt check!
return tokens
def change_oracle(self, caller, new_oracle):
self.oracle = new_oracle # no caller check!
REAL_PRICE = 5.0
def oracle_exploit(P):
p = P(Pool(100_000, 500_000), admin="team")
p.deposit("attacker", 10_000)
flash_loan = 2_000_000
bought = p.pool.buy_tokens(flash_loan)
loan = p.borrow("attacker", min(p.capacity("attacker"), p.cash))
returned = p.pool.sell_tokens(bought)
return loan + returned - flash_loan - 10_000 * REAL_PRICE # the collateral is abandoned
def admin_exploit(P):
p = P(Pool(100_000, 500_000), admin="team")
p.deposit("attacker", 100)
p.change_oracle("attacker", lambda: 1_000_000.0)
return p.borrow("attacker", p.cash) - 100 * REAL_PRICE
def withdrawal_exploit(P):
p = P(Pool(100_000, 500_000), admin="team")
p.deposit("attacker", 10_000)
loan = p.borrow("attacker", p.capacity("attacker"))
taken_back = p.withdraw_collateral("attacker", 10_000)
return loan + taken_back * REAL_PRICE - 10_000 * REAL_PRICE
def audit(P):
for exploit in (oracle_exploit, admin_exploit, withdrawal_exploit):
try:
print(f"{exploit.__name__:<18} → SUCCEEDED, attacker's gain: {exploit(P):>10.0f} STABLE")
except ValueError as e:
print(f"{exploit.__name__:<18} → blocked ({e})")
audit(SolidarityLend)
oracle_exploit → SUCCEEDED, attacker's gain: 882842 STABLE
admin_exploit → SUCCEEDED, attacker's gain: 999500 STABLE
withdrawal_exploit → SUCCEEDED, attacker's gain: 37500 STABLE
Three broken promises: the attacker inflates the price to borrow almost all the cash, replaces the oracle without being the administrator, or takes back the collateral while keeping the loan. Each exploit is a small reproducible program: it is the evidence attached to the report.
Mini-lab: stating the invariantsPython 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
Project: SolidarityLend fixed
Write SolidarityLendFixed, which inherits from SolidarityLend and fixes the three flaws, without touching anything else:
- the oracle is an average of the prices recorded at the end of each block (you can simulate a history of stable prices at start-up);
change_oraclechecks that the caller is the administrator;withdraw_collateralrefuses a withdrawal that would make the debt exceed the capacity.
Replay audit on the fixed version, then check that a normal path (deposit, reasonable loan, simulated repayment, withdrawal) still works.
Hint 1
__init__, call super().__init__(...) then replace self.oracle with a function that returns the average of self.history, initialised to [pool.price()] * 8.Hint 2
self.capacity(who), and if it is negative, put the collateral back and raise ValueError("withdrawal refused: debt not covered").Show the solution and common mistakes
class Pool:
def __init__(self, tokens, stables):
self.tokens, self.stables = tokens, stables
def price(self):
return self.stables / self.tokens
def buy_tokens(self, amount_in):
out = self.tokens - self.tokens * self.stables / (self.stables + amount_in * 0.997)
self.stables += amount_in; self.tokens -= out
return out
def sell_tokens(self, amount_in):
out = self.stables - self.tokens * self.stables / (self.tokens + amount_in * 0.997)
self.tokens += amount_in; self.stables -= out
return out
class SolidarityLend:
def __init__(self, pool, admin):
self.pool, self.admin = pool, admin
self.oracle = lambda: pool.price()
self.collateral, self.debts, self.cash = {}, {}, 1_000_000
def deposit(self, who, tokens):
self.collateral[who] = self.collateral.get(who, 0) + tokens
def capacity(self, who):
return self.collateral.get(who, 0) * self.oracle() * 0.75 - self.debts.get(who, 0)
def borrow(self, who, amount):
if amount > self.capacity(who) or amount > self.cash:
raise ValueError("loan refused")
self.debts[who] = self.debts.get(who, 0) + amount
self.cash -= amount
return amount
def withdraw_collateral(self, who, tokens):
if tokens > self.collateral.get(who, 0):
raise ValueError("insufficient collateral")
self.collateral[who] -= tokens
return tokens
def change_oracle(self, caller, new_oracle):
self.oracle = new_oracle
class SolidarityLendFixed(SolidarityLend):
def __init__(self, pool, admin):
super().__init__(pool, admin)
self.history = [pool.price()] * 8 # prices recorded at the end of each block
self.oracle = lambda: sum(self.history[-8:]) / len(self.history[-8:])
def end_of_block(self):
self.history.append(self.pool.price())
def change_oracle(self, caller, new_oracle):
if caller != self.admin:
raise ValueError("reserved for the administrator")
self.oracle = new_oracle
def withdraw_collateral(self, who, tokens):
super().withdraw_collateral(who, tokens)
if self.capacity(who) < 0:
self.collateral[who] += tokens # undo the withdrawal
raise ValueError("withdrawal refused: debt not covered")
return tokens
REAL_PRICE = 5.0
def oracle_exploit(P):
p = P(Pool(100_000, 500_000), admin="team")
p.deposit("attacker", 10_000)
bought = p.pool.buy_tokens(2_000_000)
loan = p.borrow("attacker", min(p.capacity("attacker"), p.cash))
returned = p.pool.sell_tokens(bought)
gain = loan + returned - 2_000_000 - 10_000 * REAL_PRICE
if gain <= 0:
raise ValueError(f"loan limited to {loan:.0f}, the attack costs {-gain:.0f}")
return gain
def admin_exploit(P):
p = P(Pool(100_000, 500_000), admin="team")
p.deposit("attacker", 100)
p.change_oracle("attacker", lambda: 1_000_000.0)
return p.borrow("attacker", p.cash) - 100 * REAL_PRICE
def withdrawal_exploit(P):
p = P(Pool(100_000, 500_000), admin="team")
p.deposit("attacker", 10_000)
loan = p.borrow("attacker", p.capacity("attacker"))
return loan + p.withdraw_collateral("attacker", 10_000) * REAL_PRICE - 10_000 * REAL_PRICE
def audit(P):
for exploit in (oracle_exploit, admin_exploit, withdrawal_exploit):
try:
print(f"{exploit.__name__:<18} → SUCCEEDED, gain: {exploit(P):>10.0f} STABLE")
except ValueError as e:
print(f"{exploit.__name__:<18} → blocked ({e})")
print("fixed version:")
audit(SolidarityLendFixed)
p = SolidarityLendFixed(Pool(100_000, 500_000), admin="team")
p.deposit("Awa", 1_000)
p.borrow("Awa", 2_000)
p.end_of_block()
p.debts["Awa"] = 0 # repayment (simplified)
print("normal path: withdrawal of", p.withdraw_collateral("Awa", 1_000), "TOKENS accepted")
fixed version:
oracle_exploit → blocked (loan limited to 37500, the attack costs 14908)
admin_exploit → blocked (reserved for the administrator)
withdrawal_exploit → blocked (withdrawal refused: debt not covered)
normal path: withdrawal of 1000 TOKENS accepted
All three exploits fail, each for the right reason, and the honest path still works. The final report would list for each flaw: the broken invariant, the exploit (the code above), the severity, the fix, and the test that checks it. It would also recommend giving the administrator role to a multisignature wallet (for example 3 signatures out of 5) and imposing a delay before any parameter change, so that users can react.
Common mistakes:
- Fixing the exploit instead of the cause (for example forbidding purchases above 1,000,000 in the pool): the attacker splits the purchase into several pieces.
- Checking solvency before the withdrawal instead of after: the condition must apply to the state that would result from the withdrawal.
- Forgetting that the administrator is a risk too: a single stolen key is enough to change the oracle, hence the multisignature and the delay.
Summary
- 1A protocol audit starts from the invariants: what must remain true whatever users do.
- 2Assume a rich attacker (flash loan) who controls transaction ordering and calls every function.
- 3Each flaw is demonstrated by a reproducible exploit on a test copy, never on a real protocol.
- 4Fixes target the cause (oracle, access control, solvency) and the exploits become permanent tests.
- 5Normal-path tests prove nothing about security: abuse tests are needed.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.