Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 41 ยท Smart Contracts

Smart Contract Security Pitfalls

See how reentrancy, integer overflow, missing access control, front-running and oracle manipulation break contracts, with live Python models and real incidents.

Smart contracts have an unusual combination of properties. Their code is public, they often hold money directly, anyone in the world can call them, and once deployed they usually cannot be patched. A normal web application bug might leak data that you fix next week. A contract bug can let a stranger empty the contract in a single transaction, and there may be no way to take it back.

This lesson walks through the classic classes of mistakes. For each one you will see what goes wrong, a small model you can run in Python, and the habit that prevents it. The models use plain Python classes like those in Building a Toy Smart Contract Engine, so you can follow the logic without learning a new language. The real fixes are written in Solidity, which you met in Reading Solidity: A First Contract.

Reentrancy

When a contract sends money or calls another contract, the receiver gets control. If the receiver is itself a contract, its code runs in the middle of your function. If your function has not finished updating its own state, the receiver can call back in and see stale data. This is reentrancy.

The vulnerable pattern is: check the balance, send the money, and only then set the balance to zero. The attacker's receiving code calls withdraw again before the balance is zeroed, and each nested call passes the same check.

sequenceDiagram
    participant A as Attacker contract
    participant B as Bank contract
    A->>B: withdraw()
    B->>B: check balance (10) is fine
    B->>A: send 10
    A->>B: withdraw() again
    B->>B: balance is still 10
    B->>A: send 10 again
    Note over A,B: repeats until the bank is empty

The bank sends money before updating its records, so the attacker re-enters while the old balance is still visible.

In the model, the bank holds a pool of funds and a table of what each user is owed. The safe flag switches between the vulnerable order and the fixed order.

Python A reentrancy attack, and the fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the vulnerable run the attacker puts in 10 and takes out 110, the entire pool. The bank is left holding 0 while it still owes 100 to Alice and Bob. In the safe run, the nested call sees a zero balance and fails.

Defenses, in order of importance:

  1. Checks-effects-interactions. First check conditions, then update your state, and make external calls last.
  2. Reentrancy guards. A lock flag (a "mutex") that makes a function refuse to run while it is already running. Libraries provide a ready-made modifier.
  3. Pull instead of push. Record what users are owed and let them withdraw it, instead of looping over users and sending money.

Integer overflow and underflow

Contract numbers have a fixed size, for example a 256-bit unsigned integer (uint256) or an 8-bit one (uint8). Older Solidity versions silently wrapped around when a result did not fit: 255 + 1 became 0, and 0 - 1 became 255. Since Solidity 0.8, arithmetic reverts on overflow by default, but code that uses unchecked blocks, assembly, or old compilers can still wrap, and so can smaller casts such as uint8(x).

Python Wrap-around versus checked arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A real incident of this kind appeared in 2018 (the "BatchOverflow" bug in several ERC-20 tokens, where a batch transfer multiplied an amount by the number of receivers and the product wrapped to zero). The modern rule: use a recent compiler, treat every unchecked block as something that needs a written proof, and test boundary values.

Missing or weak access control

Who is allowed to call this function? If the answer is not written in code, the answer is "everyone". Typical mistakes:

  • A function that sets the owner, mints tokens or withdraws funds has no onlyOwner check.
  • An initializer meant to run once can be called by anyone, or called again.
  • The contract checks tx.origin (the wallet that started the whole chain of calls) instead of msg.sender. A malicious contract can trick the real owner into calling it and then act with the owner's identity.
  • A function is public when it should be internal.
Python Missing access control

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The fix is boring and essential: every state-changing function names who may call it, and sensitive roles are given to multi-signature wallets or timelocks, not to a single key.

Front-running and transaction ordering

Pending transactions wait in the public mempool (Transactions and the Mempool), and block producers choose their order, usually by fee. Anyone can read a pending transaction and submit their own with a higher fee so that it lands first. This is front-running. Related attacks are back-running (placing a transaction right after a target) and sandwiching (one transaction before and one after a trade to profit from the price move it causes). The profit available from ordering transactions is called MEV (maximal extractable value).

Python A bot copies a winning solution

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Defenses include commit-reveal schemes (first publish a hash of your answer, later reveal it), slippage limits on trades, private transaction channels that skip the public mempool, and designing so that ordering does not matter.

Oracle manipulation

Contracts cannot look up prices themselves; they read them from an oracle (see dApps, Oracles and Wallet Integration). If the "oracle" is just the current price in a small trading pool, an attacker can distort it inside one transaction, borrow against the fake price and walk away. Attackers often fund the distortion with a flash loan, a loan that must be repaid within the same transaction, so they need no capital of their own.

The model below uses a constant-product pool (price follows x * y = k, explained in DeFi, DAOs and Governance) and a lending protocol that trusts the pool's spot price.

Python Manipulating a spot price

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Safer designs read prices from decentralized oracle networks, use time-weighted average prices (an average over minutes, which is expensive to distort), add sanity bounds and avoid using a thin pool as the only source.

Famous incidents

Year Incident Lesson
2016 The DAO: reentrancy let an attacker drain about 3.6 million ETH. The community hard-forked Ethereum to reverse it; the unforked chain continues as Ethereum Classic. Reentrancy, and the limits of "code is law"
2017 Parity multisig wallets: first an unprotected initializer let attackers steal funds; later a shared library contract was accidentally destroyed, freezing hundreds of thousands of ETH in other wallets. Access control, shared-code risk
2021 Poly Network: a cross-chain bridge flaw let an attacker move hundreds of millions of dollars; most was returned. Bridges hold huge pooled funds
2022 Ronin bridge: attackers gained control of enough validator keys. The code was not at fault; the key management was. Off-chain trust and key custody
2022 Beanstalk: a flash loan bought temporary voting power and passed a malicious proposal. Governance can be attacked like prices

Notice that several of these are not "coding errors" in the narrow sense. Security also includes who holds keys, how upgrades work and how governance is designed.

A practical security checklist

  • Use a current compiler and audited, widely used libraries rather than writing token or access-control code from scratch.
  • Follow checks-effects-interactions and add reentrancy guards.
  • Give every sensitive function an explicit permission, and put admin powers behind multi-signature wallets and timelocks.
  • Write tests for edge cases and attacks, use fuzzing and static analysis tools, then get independent audits.
  • Limit the damage: caps on deposits, circuit breakers, bug bounties and a plan for incidents.
  • Remember that "audited" does not mean "safe". It means a reviewer looked for problems in a given version of the code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What makes the vulnerable bank in the lesson reentrant?

    The external call hands control to the attacker while the old balance is still recorded, so nested withdraw calls pass the same check. Updating state first closes the hole.
  2. 2. What does the checks-effects-interactions pattern say?

    By the time control leaves your contract, your state is already consistent, so a re-entering caller sees the updated values.
  3. 3. In a uint8, what is 0 - 1 with wrap-around arithmetic?

    Unsigned values wrap modulo 256, so 0 - 1 becomes 255. Solidity 0.8 and later reverts instead, unless the code is inside an unchecked block.
  4. 4. Why is reading a price from the current state of a small trading pool dangerous?

    A single large swap moves a thin pool's spot price. Time-weighted averages and robust oracle networks make that much more expensive.
  5. 5. What is front-running?

    Pending transactions are visible and ordering is chosen by block producers, often by fee. That allows others to react to your transaction before it is included.

Summary

  • Contracts are public, hold value and are hard to patch, so small mistakes become expensive.
  • Reentrancy happens when an external call runs before your state is updated; update state first and add a guard.
  • Integer wrap-around is blocked by default in modern Solidity, but unchecked code and casts still need care.
  • Every sensitive function needs an explicit access check; tx.origin is not a safe identity.
  • Transaction ordering is public and can be exploited, which is called front-running or MEV; commit-reveal and slippage limits help.
  • Oracles and governance can be manipulated, and many real losses came from keys and design, not only code.

Next: dApps, Oracles and Wallet Integration, where contracts meet front ends and the outside world.