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
- Cryptographic layer: private-key theft, weak or reused randomness in ECDSA nonces (a repeated nonce leaks the key), broken key derivation, loss of a seed phrase. Most real losses in India (exchange hacks) are key-management failures, not consensus breaks.
- Consensus layer: 51% / majority-hashpower attack, selfish mining, long-range and nothing-at-stake attacks in PoS, stake-grinding, finality reversal.
- Network layer: eclipse attack (isolating a node's peers), Sybil attack (many fake identities), BGP hijack, transaction censorship, DoS on RPC endpoints.
- Application (smart-contract) layer: logic bugs, reentrancy, access-control gaps, oracle manipulation, arithmetic errors — the layer audits target.
- Operational / human layer: admin keys on one laptop, no multisig, phishing of a signer, malicious insider, rug pull by the deployer, social-engineered governance proposals.
- Bridge layer: cross-chain bridges concentrate custody and have produced the single largest losses (Ronin, Wormhole, Nomad class of incidents).
Protocol-level attacks in detail
- 51% attack: an adversary with majority mining power (PoW) or stake (PoS) can reorganise recent blocks and double-spend — but cannot forge signatures, steal others' coins or change old history cheaply. Cost scales with hashrate price; small chains are cheap to attack.
- Double spending: the same UTXO/balance spent twice. Defences: wait for k confirmations (6 for Bitcoin by convention), use finality-gadget chains, require deeper confirmations for larger amounts.
- Race / Finney / vector-76 attacks: variants that exploit zero-confirmation acceptance by merchants.
- Selfish mining: withholding a found block to gain relative reward; in the classic Eyal–Sirer analysis the profitability threshold ranges from about 25% up to 1/3 of hashpower, depending on how well the attacker's blocks propagate (γ).
- Nothing-at-stake and long-range (PoS): validators can sign multiple histories at no cost; countered by slashing of bonded stake, weak subjectivity checkpoints and finality (e.g. Casper FFG-style two-thirds voting).
- Eclipse attack: fill a victim's peer table so it sees only attacker-supplied blocks; countered by peer diversity, anchor connections, hardened peer selection.
- Private/permissioned chains shift the threat to identity and MSP/CA compromise rather than hashpower.
Smart-contract vulnerability classes (SWC registry / DASP taxonomy)
- 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).
- Access control: missing
onlyOwner, publicinitialize()left callable, unprotectedselfdestruct/delegatecall, default-visibility functions (pre-0.5.0 Solidity). Parity multisig incidents (2017) were access-control and initialisation failures. - 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. - Unchecked low-level calls:
call,sendanddelegatecallreturn a boolean instead of reverting; ignoring it silently continues with a failed transfer. - 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.
- 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.
- 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. - Bad randomness:
block.timestamp,blockhashandblock.prevrandaoare miner/validator-influenceable or predictable; use a VRF (Chainlink VRF) or commit-reveal. - Delegatecall and storage collisions:
delegatecallruns 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. - tx.origin authentication:
tx.originis the original EOA, so a phishing contract passes the check; always usemsg.sender. - 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.
- ERC-20 token oddities: fee-on-transfer and rebasing tokens break balance arithmetic;
transferreturning false instead of reverting; the ERC-20 approve race; ERC-777 hooks enabling reentrancy on "safe" tokens. - 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.
- 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
- Checks-Effects-Interactions (CEI): validate inputs, update state, then call out — the standard structural answer to reentrancy. Add a mutex (
ReentrancyGuard/nonReentrant) for defence in depth. - Pull over push payments: record an amount owed, let the user withdraw.
- Least privilege and separation: role-based access (
AccessControl), timelock on admin actions, 3-of-5 or 4-of-7 multisig (Gnosis Safe) for owner keys, hardware wallets for signers. - Fail-safe: circuit breaker /
Pausable, rate limits and withdrawal caps, emergency withdrawal path. - Reuse audited libraries: OpenZeppelin Contracts, Solmate; do not hand-roll ERC-20, access control or math.
- Static analysis: Slither (detectors on the Solidity AST/IR), Mythril and Manticore (symbolic execution), Semgrep rules, Aderyn. Fast, but noisy — they produce false positives and cannot see intent.
- Dynamic analysis: property-based fuzzing with Echidna or Foundry's built-in fuzzer (
forge test), and invariant testing (e.g. "total supply always equals the sum of balances", "the vault can never pay out more than its assets"). - Formal verification: Certora Prover (CVL specs), Halmos, KEVM, SMTChecker built into solc — proves a property for all inputs within a model, but only the properties you write.
- Differential and mainnet-fork testing: replay against real state with Foundry
--fork-url, Tenderly simulations. - Gas and compiler hygiene: pin the compiler version (no floating
^), enable optimiser deterministically, check for known compiler bugs for that version, verify source on Etherscan/Polygonscan so bytecode matches. - Post-deployment: monitoring (Forta-style alerts), bug bounty (Immunefi), incident runbook, response multisig that can pause.
The audit process, step by step
- Scope and freeze: list contracts, files and the exact commit hash; out-of-scope items (off-chain backend, front-end) are named explicitly.
- 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.
- Automated sweep: compile, run Slither/Mythril/SMTChecker, test coverage report, dependency and compiler version check.
- Manual line-by-line review: two or more independent auditors, each tracing value flows, access control, external calls, arithmetic and upgrade paths.
- Fuzz and invariant campaign: write properties, run long campaigns, triage counterexamples.
- Exploit proof-of-concept: write a failing test that actually drains funds — a finding without a PoC is often disputed.
- 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.
- 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.
- Final report and disclosure: published with the audited commit hash. Deploying code different from the audited commit voids the audit — a point interviewers probe.
- 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
- Legal status: crypto-assets ("virtual digital assets", VDAs) are not legal tender in India and are not banned; there is no dedicated crypto Act as of November 2026 — a discussion paper and FSB/IMF-aligned framework work has been under way, so treat statutory detail as liable to change.
- FIU-IND: VDA service providers (exchanges, custodians, wallet providers) are reporting entities under the Prevention of Money-Laundering Act, 2002, must register with the Financial Intelligence Unit–India and run KYC, record-keeping and STR reporting. Several offshore exchanges were blocked in 2024 for non-registration.
- CERT-In Directions, 28 April 2022: mandatory reporting of specified cyber incidents within 6 hours, logs retained 180 days within India, and VASPs/custodian wallet providers must keep KYC and transaction records for five years. Issued under section 70B of the IT Act, 2000.
- Taxation (for context only; details belong to the crypto-tax topic): VDA income is taxed at a flat 30% with no deduction except cost of acquisition and no set-off of losses, plus 1% TDS on transfers above the threshold; from 1 April 2026 these provisions sit in the Income-tax Act, 2025, which renumbered every section — cite the VDA provisions by name rather than by the old 1961 section numbers unless the mapping is certain.
- Data and evidence: the Digital Personal Data Protection Act, 2023 applies to personal data handled off-chain; under the DPDP Rules, 2025 the core Data Fiduciary duties (notice, consent, breach intimation, erasure) and the omission of IT Act s.43A take effect only from 13 May 2027 — until then s.43A and the SPDI Rules, 2011 apply. Blockchain records produced in court are electronic records; admissibility is governed by the Bharatiya Sakshya Adhiniyam, 2023 (name the certificate-for-electronic-records rule rather than guessing a section number).
- Standards and guidance: ISO/TC 307 blockchain standards (ISO 22739 vocabulary, ISO/TR 23455 smart-contract overview, ISO/TS 23635 governance), ISO/IEC 27001:2022 for the operating organisation, NIST IR 8202 as an introductory reference, and RBI/SEBI cyber-security and cyber-resilience frameworks for regulated entities running DLT pilots. Say "voluntary" unless a scheme is actually mandated — ISO certifications here are voluntary.
Key points
- Immutability - deployed bytecode cannot be patched, so security must be achieved before deployment; upgradeability is itself a new attack surface.
- Public visibility -
privatein Solidity hides from other contracts, not from readers of chain state; never store secrets on-chain. - Reentrancy - an external call returns control to the attacker before state is updated; fixed by Checks-Effects-Interactions plus
nonReentrant. - CEI order - checks (require), then effects (state writes), then interactions (external calls).
- Pull payments - users withdraw rather than the contract pushing funds in a loop, avoiding DoS by one reverting recipient.
- Solidity ≥0.8 - arithmetic reverts on overflow by default; SafeMath is legacy,
uncheckedre-opens the risk. - tx.origin vs msg.sender -
tx.originis phishable; authenticate withmsg.sender. - delegatecall - executes external code against your storage and
msg.sender; mis-aligned storage layout in proxies corrupts state. - Flash loan - borrow and repay within one transaction; weaponises any single-source spot-price oracle.
- Oracle hardening - TWAP, multiple independent feeds, bounds checks, heartbeat/staleness checks.
- MEV / front-running - public mempool allows reordering and sandwiching; mitigate with slippage caps, deadlines, commit-reveal, private order flow.
- On-chain randomness - block variables are manipulable; use a VRF or commit-reveal.
- 51% attack - allows reorg and double-spend, not signature forgery or theft of arbitrary balances.
- Severity = Impact × Likelihood - Critical means direct, probable loss or permanent freeze of user funds.
- Audit ≠ guarantee - point-in-time, scope-bound, commit-specific; re-deploying changed code voids it.
- Defence in depth - multisig + timelock + pause + monitoring + bounty, because code review alone has a known miss rate.
- CERT-In - 6-hour incident reporting, 180-day Indian log retention, 5-year KYC/transaction records for VDA providers.
- FIU-IND registration - mandatory for VDA service providers as PMLA reporting entities.
Formulas and examples
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.
- z = 1: P ≈ (1/3)¹ = 0.3333 → 33.3%
- z = 3: P ≈ (1/3)³ = 1/27 = 0.0370 → 3.70%
- z = 6: P ≈ (1/3)⁶ = 1/729 = 0.001372 → 0.137%
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.
- Attacker flash-borrows 9,000 USDC and swaps it in (ignore fees): new y = 10,000, so new x = 1,000,000/10,000 = 100 TOKEN, i.e. 900 TOKEN received.
- New spot price = 10,000/100 = 100 USDC per TOKEN — a 100× inflation inside one transaction.
- With 100 TOKEN pledged, a protocol reading this spot price values the collateral at 100 × 100 = 10,000 USDC and, at 75% LTV, lends 7,500 USDC against collateral genuinely worth about 100 USDC.
- The attacker reverses the swap, repays the flash loan and keeps the borrowed USDC. A 30-minute TWAP would have reported ≈1 USDC, because the spike existed for part of a single block.
Example 4 — Severity rating and remediation priority.
| Finding | Impact | Likelihood | Score | Severity |
|---|---|---|---|---|
Reentrancy in withdraw() | 5 (all funds) | 5 (trivial) | 25 | Critical |
| Spot-price oracle, no TWAP | 5 | 4 | 20 | Critical |
| Owner is a single EOA, can upgrade | 5 | 2 | 10 | High (centralisation) |
| Unbounded loop over holders array | 3 | 3 | 9 | Medium (DoS) |
| Missing event on parameter change | 1 | 3 | 3 | Informational |
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).
- Density = 21 × 1000 / 4200 = 5.0 findings per kLoC.
- Value at risk at launch: ₹40 crore TVL. If the two Criticals each carry a 30% chance of exploitation within a year, the naive sum 2 × 0.30 × ₹40 cr = ₹24 crore double-counts the same funds; capping at total loss gives EL ≈ (1 − 0.70²) × ₹40 cr = 0.51 × ₹40 cr ≈ ₹20.4 crore of risk removed by fixing both.
- A ₹25 lakh audit plus a ₹50 lakh bounty pool is about 1.9% of TVL — the standard cost-justification argument, and the reason exchanges and DeFi teams budget for two independent audits.
| Technique | Finds | Misses | Effort |
|---|---|---|---|
| Static analysis (Slither) | Known patterns: reentrancy, unchecked calls, shadowing | Business-logic and economic flaws | Minutes, high false positives |
| Symbolic execution (Mythril) | Assertion violations, reachable reverts | Deep multi-transaction paths (path explosion) | Hours |
| Fuzzing / invariants (Echidna, Foundry) | Violated invariants, odd input combinations | Properties you never wrote | Days, needs good properties |
| Formal verification (Certora) | Proves stated properties for all inputs in model | Spec errors, out-of-model assumptions | Weeks, expensive |
| Manual review | Intent, logic, incentives, composability | Human fatigue; scope-bound | Days to weeks, highest value |
Where it is used
- Audit and security firms: QuillAudits, Hashlock-type and Big Four blockchain practices in India hire Solidity auditors; deliverables are the audit report and PoC exploits. Roles: smart-contract auditor, security researcher, exploit developer.
- Indian exchanges and custodians (CoinDCX, CoinSwitch, Mudrex and peers): FIU-IND-registered, so key management (HSMs, MPC, multisig cold storage), CERT-In incident response and SOC monitoring are core job functions.
- Bank and NBFC DLT teams: permissioned-chain pilots for trade finance, bank guarantees and loan syndication — security work is identity/MSP, HSM key custody and RBI cyber-security framework compliance.
- Government and public DLT: certificate-issuance chains (university degrees, caste and land records pilots), National Blockchain Framework / C-DAC work — audit focus is access control, privacy of personal data and tamper-evidence for evidentiary value.
- Product engineering in Web3 startups: writing invariants and Foundry test suites, running Slither in CI, operating Gnosis Safe multisigs with timelocks, bug-bounty triage.
- Academic and exam use: university blockchain electives and viva questions on reentrancy, the DAO fork and 51% attacks; placement coding rounds that ask you to spot a bug in a short Solidity snippet.
Interview questions
- Q: What is reentrancy and how do you prevent it? A: An external call lets the callee re-enter the function before state is updated, so stale state is reused. Prevent it with Checks-Effects-Interactions ordering and a
nonReentrantmutex, and prefer pull payments. - Q: Does marking a variable
privatekeep it secret? A: No.privateonly restricts access from other contracts; all storage is readable from the chain witheth_getStorageAt, so secrets must never be stored on-chain. - Q: Why is
tx.originunsafe for authorisation? A: It is the original externally-owned account, so if a user is tricked into calling an attacker's contract, that contract inherits the user's authority;msg.senderis the immediate caller and is the correct check. - Q: Is SafeMath still needed? A: Not for ordinary arithmetic in Solidity 0.8.0 and later, which reverts on overflow and underflow — but code inside
unchecked { }blocks, inline assembly, and casts between integer sizes can still overflow silently. - Q: What exactly can a 51% attacker do, and what can it not do? A: It can reorder or exclude transactions and reorganise recent blocks to double-spend its own coins; it cannot forge signatures, spend other people's coins, or change the protocol rules.
- Q: How does a flash loan help attack a protocol with no bug in its own math? A: It supplies enormous temporary capital to move a single-source spot price within one transaction, so the protocol's correct math is fed a false price; hardened oracles (TWAP, multiple feeds) are the fix.
- Q: What is front-running / MEV and how is it mitigated in contract design? A: Because the mempool is public, others can place transactions ahead of yours for profit (including sandwich attacks). Mitigate with slippage and deadline parameters, commit-reveal schemes, batch auctions or private relays.
- Q: Why is
block.timestampa poor source of randomness? A: Block proposers have limited but real influence over it and it is predictable within a range, so outcomes can be gamed; use a verifiable random function or commit-reveal. - Q: What goes wrong with upgradeable proxies? A: Mismatched storage layouts between proxy and implementation corrupt variables, an unprotected
initialize()can be called by anyone, and an uninitialised implementation contract can be hijacked — and, before EIP-6780 (Dencun, March 2024) limitedselfdestruct, destroyed, bricking every proxy pointing at it; use audited upgrade tooling,_disableInitializers()and storage gaps. - Q: An audited protocol was hacked. Did the audit fail? A: Not necessarily. An audit is point-in-time, scope-bound and tied to a commit hash; if the deployed code differed, the bug was out of scope, or it was an economic/off-chain failure, the audit's limits were being exceeded rather than its conclusions being wrong.
- Q: How would you rate severity in an audit report? A: By impact against likelihood — Critical for probable direct loss or permanent freeze of user funds, down to Informational for style and missing events — with each finding carrying a proof-of-concept and a concrete recommendation.
- Q: What are an Indian exchange's statutory security obligations? A: Registration with FIU-IND as a PMLA reporting entity with KYC and STR duties, plus the CERT-In Directions of April 2022 — reporting specified incidents within six hours, retaining logs for 180 days in India and KYC/transaction records for five years.
Common mistakes
- Writing the fix as "add
nonReentrant" without reordering to Checks-Effects-Interactions — the guard alone does not stop cross-function or cross-contract reentrancy. - Claiming
privateorinternalmakes data confidential, or that hashing a secret on-chain hides it when the preimage space is small. - Saying a 51% attacker can steal anyone's coins, or that it can rewrite the whole chain history cheaply.
- Still writing SafeMath for Solidity 0.8+ in an interview, or conversely assuming 0.8 protects arithmetic inside
uncheckedblocks and assembly. - Treating tool output as the audit: running Slither, reporting its false positives verbatim, and missing the business-logic flaw that no detector models.
- Using a single AMM spot price as an oracle and asserting it is safe "because the math is correct".
- Calling an audit a guarantee or an insurance, forgetting the commit hash, scope boundary and fix-review step — and forgetting that the deployed bytecode must match the audited source.
- Quoting the old Income-tax Act, 1961 section numbers for VDA tax or omitting FIU-IND/CERT-In duties when asked about Indian compliance.
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