Knowledge / Computer Science and Engineering / Blockchain security and smart-contract audits

Blockchain security and smart-contract audits

Computer Science and Engineering (B.E./B.Tech) · Blockchain · free study notes for exams, placements and interviews

In short

Blockchain security covers two different layers: the security of the protocol itself (consensus, keys, networking) and the security of the application code — smart contracts — deployed on it. A smart-contract audit is a structured review of that code (manual review plus static analysis, fuzzing and sometimes formal proofs) carried out before deployment, because a contract on a public chain is immutable, publicly readable and holds bearer assets, so a bug is directly a theft. The subject is examined in B.E./B.Tech blockchain electives and in GATE DA/CS security questions, and is asked in interviews at Indian audit and Web3 firms (QuillAudits, Hashlock-type firms, Zeeve, Polygon, CoinDCX, WazirX engineering), bank and NBFC blockchain teams, and security roles at TCS, Infosys, Wipro and Deloitte/EY/PwC India. Indian legal context matters too: the IT Act, 2000 with the CERT-In Directions of 28 April 2022 (6-hour incident reporting, 180-day log retention) governs exchange and node operators, and crypto-asset service providers must register with FIU-IND.

Explained

Layered threat model: what can be attacked

Protocol-level attacks in detail

Smart-contract vulnerability classes (SWC registry / DASP taxonomy)

  1. Reentrancy: an external call hands control to the attacker, who re-enters before state is updated. Classic single-function, plus cross-function and cross-contract variants. Cause of The DAO hack, 2016 (~3.6M ETH drained; led to the Ethereum/Ethereum Classic hard fork).
  2. Access control: missing onlyOwner, public initialize() left callable, unprotected selfdestruct/delegatecall, default-visibility functions (pre-0.5.0 Solidity). Parity multisig incidents (2017) were access-control and initialisation failures.
  3. Arithmetic: integer overflow/underflow. Solidity 0.8.0 and later reverts on overflow by default; earlier code needed SafeMath, and unchecked { } blocks re-enable the old behaviour.
  4. Unchecked low-level calls: call, send and delegatecall return a boolean instead of reverting; ignoring it silently continues with a failed transfer.
  5. Oracle / price manipulation: reading a spot price from a single AMM pool lets an attacker move it with a flash loan (uncollateralised loan repaid in the same transaction) and borrow or liquidate at a false price. Fix: TWAP, multiple feeds, decentralised oracles, sanity bounds.
  6. Front-running and MEV: the mempool is public, so searchers reorder, sandwich or censor transactions. Fix: commit-reveal, slippage limits, deadlines, batch auctions, private relays.
  7. Denial of service: unbounded loops over growing arrays (gas limit), a push-payment loop blocked by one reverting recipient, griefing by a contract with a reverting receive(). Fix: pull payments.
  8. Bad randomness: block.timestamp, blockhash and block.prevrandao are miner/validator-influenceable or predictable; use a VRF (Chainlink VRF) or commit-reveal.
  9. Delegatecall and storage collisions: delegatecall runs foreign code in your storage context; in proxy patterns an implementation whose storage layout differs from the proxy's corrupts variables. Fix: unstructured/diamond storage, storage gaps, OpenZeppelin upgrade plugins.
  10. tx.origin authentication: tx.origin is the original EOA, so a phishing contract passes the check; always use msg.sender.
  11. Signature issues: missing nonce (replay), missing chain-id/domain separator (cross-chain replay), ECDSA signature malleability (s and n−s both valid), non-EIP-712 raw hashes.
  12. ERC-20 token oddities: fee-on-transfer and rebasing tokens break balance arithmetic; transfer returning false instead of reverting; the ERC-20 approve race; ERC-777 hooks enabling reentrancy on "safe" tokens.
  13. Business-logic and economic flaws: wrong rounding direction, first-depositor share inflation in vaults, mis-set liquidation thresholds, missing pause. These are the hardest to find and the most expensive.
  14. Centralisation risk as a finding: an EOA owner who can mint or upgrade is reported as a High/Critical in Indian and global audit practice even if the code is correct.

Secure coding patterns and tooling

The audit process, step by step

  1. Scope and freeze: list contracts, files and the exact commit hash; out-of-scope items (off-chain backend, front-end) are named explicitly.
  2. Documentation and threat model: read spec, whitepaper, invariants; ask "who are the actors, what can each do, what must never happen". Lack of spec is itself a finding.
  3. Automated sweep: compile, run Slither/Mythril/SMTChecker, test coverage report, dependency and compiler version check.
  4. Manual line-by-line review: two or more independent auditors, each tracing value flows, access control, external calls, arithmetic and upgrade paths.
  5. Fuzz and invariant campaign: write properties, run long campaigns, triage counterexamples.
  6. Exploit proof-of-concept: write a failing test that actually drains funds — a finding without a PoC is often disputed.
  7. Severity rating: Critical / High / Medium / Low / Informational / Gas, usually from Impact × Likelihood (OWASP-style risk matrix); Critical = direct loss of user funds or permanent freeze.
  8. Report and remediation: issue description, affected lines, impact, PoC, recommendation; the client fixes; the auditor does a fix-review on the new commit and marks each finding Fixed / Acknowledged / Mitigated.
  9. Final report and disclosure: published with the audited commit hash. Deploying code different from the audited commit voids the audit — a point interviewers probe.
  10. Alternatives / complements: competitive audit contests (Code4rena, Sherlock), continuous auditing, bug bounties. An audit is a point-in-time reduction of risk, never a guarantee or an insurance.

Indian regulatory and compliance context

Key points

Formulas and examples

Confirmation security (double-spend probability, Nakamoto model): P(catch-up) ≈ (q/p)z for q < p, where q = attacker's share of hashpower, p = 1 − q, z = number of confirmations. Dimensionless probability.
Majority-attack cost (rough): Cost ≈ H × t × c, where H = network hashrate to rent (TH/s), t = attack duration (hours), c = rental price per TH/s per hour (₹ or $). Add block-reward income earned back during the attack.
Risk severity: Severity = f(Impact, Likelihood) on a 3×3 or 5×5 matrix; numeric form Risk score = Impact (1–5) × Likelihood (1–5), max 25.
Finding density: Findings per kLoC = (number of findings × 1000) / lines of Solidity in scope.
Audit cost estimate: Cost ≈ nSLoC × rate per line, or auditor-days × day rate; Indian firms commonly quote per-week engagements.
Expected loss: EL = Σ (probability of exploit × value at risk); compare with audit + bounty spend to justify the budget.
Flash-loan price impact in a constant-product AMM: x·y = k; after swapping Δx in, the new price ratio is (y − Δy)/(x + Δx) with Δy = y·Δx/(x + Δx).

Example 1 — Double-spend risk versus confirmations. An attacker controls q = 0.25 of hashpower, so p = 0.75 and q/p = 1/3.

So accepting a ₹10,00,000 payment at 1 confirmation carries an expected loss of about ₹3,33,000, falling to about ₹1,370 at 6 confirmations. (The simple (q/p)z form is the Nakamoto approximation; the exact Poisson-sum result is slightly larger at small z.)

Example 2 — Reentrancy: the bug and the fix.

// VULNERABLE
mapping(address => uint256) public balance;
function withdraw() external {
    uint256 amt = balance[msg.sender];      // check
    require(amt > 0, "nothing");
    (bool ok, ) = msg.sender.call{value: amt}("");  // interaction FIRST
    require(ok, "send failed");
    balance[msg.sender] = 0;                // effect LAST  <-- too late
}
// FIXED: Checks-Effects-Interactions + guard
function withdraw() external nonReentrant {
    uint256 amt = balance[msg.sender];
    require(amt > 0, "nothing");
    balance[msg.sender] = 0;                // effect BEFORE interaction
    (bool ok, ) = msg.sender.call{value: amt}("");
    require(ok, "send failed");
}

Attack arithmetic: the pool holds 100 ETH, the attacker deposits 1 ETH, then re-enters from receive(). Because balance is still 1 ETH on each re-entry, each pass sends 1 ETH; the attacker can loop until the contract is empty — 100 re-entries drain 100 ETH for a 1 ETH stake, a 100× loss, limited only by the 63/64 gas rule and the block gas limit.

Example 3 — Flash-loan oracle manipulation. A lending protocol prices TOKEN from a single AMM pool holding x = 1,000 TOKEN and y = 1,000 USDC, so k = 1,000,000 and the spot price is 1.00 USDC.

Example 4 — Severity rating and remediation priority.

FindingImpactLikelihoodScoreSeverity
Reentrancy in withdraw()5 (all funds)5 (trivial)25Critical
Spot-price oracle, no TWAP5420Critical
Owner is a single EOA, can upgrade5210High (centralisation)
Unbounded loop over holders array339Medium (DoS)
Missing event on parameter change133Informational

Fix order follows the score; the first two must be fixed and re-reviewed before any mainnet deployment.

Example 5 — Finding density and audit economics. A protocol has 4,200 nSLoC in scope; the audit reports 21 findings (2 Critical, 3 High, 6 Medium, 10 Low/Info).

TechniqueFindsMissesEffort
Static analysis (Slither)Known patterns: reentrancy, unchecked calls, shadowingBusiness-logic and economic flawsMinutes, high false positives
Symbolic execution (Mythril)Assertion violations, reachable revertsDeep multi-transaction paths (path explosion)Hours
Fuzzing / invariants (Echidna, Foundry)Violated invariants, odd input combinationsProperties you never wroteDays, needs good properties
Formal verification (Certora)Proves stated properties for all inputs in modelSpec errors, out-of-model assumptionsWeeks, expensive
Manual reviewIntent, logic, incentives, composabilityHuman fatigue; scope-boundDays to weeks, highest value

Where it is used

Interview questions

Common mistakes

Related topics

Smart contracts and Solidity · Cryptographic hash functions and digital signatures · Consensus mechanisms: PoW, PoS and BFT · Web application security and OWASP Top 10 · Cyber law: IT Act, 2000 and CERT-In directions · Key management, HSMs and multi-party computation

Open in the Knowledge reader →Find jobs →