{
 "schema": "bsv.security.classes/1.1",
 "version": "1.1.0",
 "generated_at": "2026-11-22T09:40:54Z",
 "license": "CC-BY-4.0",
 "policy": "Attack-side steps, checklist items, vulnerability questions, PoC workflows and prompts are published only when the matching defense, mitigation and detection sit next to them on this page. Do not copy an attack path on its own. Every test stays on a local fork; Immunefi prohibits testing on mainnet or public testnet. Illegal use stays illegal.",
 "classes": [
  {
   "id": "reentrancy",
   "name": "Reentrancy",
   "swc": "SWC-107",
   "summary": "An external call hands control to an attacker contract before the caller has finished updating its own state. Variants: single-function, cross-function, cross-contract, and read-only (a view function returns stale state mid-call and another protocol prices off it).",
   "attacker_questions": [
    "Which external calls happen before balances, shares or debt are written? (checks-effects-interactions order)",
    "Do ERC777 / ERC721 / ERC1155 receive hooks, native ETH sends or arbitrary token transfers give a callback?",
    "Is the reentrancy guard shared across every function that touches the same state, including in sibling contracts?",
    "Does any view function (get_virtual_price, totalAssets, exchangeRate) read state that is mid-update during a callback?",
    "Can a compiler or language bug disable the guard? (the Vyper 0.2.15–0.3.0 lock bug)"
   ],
   "defense_for_question": [
    "Write all effects first (balances, shares, debt, flags), then interact. Prefer pull payments over push. A function that still calls out before writing state is not finished.",
    "Treat every token transfer and every ETH send as a callback into untrusted code. Put OpenZeppelin ReentrancyGuard (nonReentrant), or an equivalent mutex, on every function that touches the same state. Do not assume ERC-20 transfers are non-reentrant.",
    "Use one mutex for all functions that share state. If state lives across contracts, share the guard or make the callee both CEI-safe and non-reentrant. A per-function lock that another entry point can bypass is not a defense.",
    "For views that other protocols price off: take the same lock, or return a snapshot from before the external call, and document that integrators must not read the view mid-update. A mutex on the writer only does not stop read-only reentrancy.",
    "Pin a compiler version with a known-good mutex (do not use Vyper 0.2.15–0.3.0). Confirm the lock compiles as intended, and keep a test that reenters and must revert."
   ],
   "pairs": [
    {
     "attacker_question": "Which external calls happen before balances, shares or debt are written? (checks-effects-interactions order)",
     "defense": "Write all effects first (balances, shares, debt, flags), then interact. Prefer pull payments over push. A function that still calls out before writing state is not finished."
    },
    {
     "attacker_question": "Do ERC777 / ERC721 / ERC1155 receive hooks, native ETH sends or arbitrary token transfers give a callback?",
     "defense": "Treat every token transfer and every ETH send as a callback into untrusted code. Put OpenZeppelin ReentrancyGuard (nonReentrant), or an equivalent mutex, on every function that touches the same state. Do not assume ERC-20 transfers are non-reentrant."
    },
    {
     "attacker_question": "Is the reentrancy guard shared across every function that touches the same state, including in sibling contracts?",
     "defense": "Use one mutex for all functions that share state. If state lives across contracts, share the guard or make the callee both CEI-safe and non-reentrant. A per-function lock that another entry point can bypass is not a defense."
    },
    {
     "attacker_question": "Does any view function (get_virtual_price, totalAssets, exchangeRate) read state that is mid-update during a callback?",
     "defense": "For views that other protocols price off: take the same lock, or return a snapshot from before the external call, and document that integrators must not read the view mid-update. A mutex on the writer only does not stop read-only reentrancy."
    },
    {
     "attacker_question": "Can a compiler or language bug disable the guard? (the Vyper 0.2.15–0.3.0 lock bug)",
     "defense": "Pin a compiler version with a known-good mutex (do not use Vyper 0.2.15–0.3.0). Confirm the lock compiles as intended, and keep a test that reenters and must revert."
    }
   ],
   "mitigation": [
    "Checks-effects-interactions on every path that moves value.",
    "A shared ReentrancyGuard (or equivalent) on all functions that share state, including cross-contract entry points.",
    "Snapshot or lock views that other contracts use as oracles.",
    "Pinned compiler; regression test that a reentrant callback reverts."
   ],
   "detection": [
    "CI: Slither reentrancy detectors, plus a Foundry test whose callback tries to reenter and must revert.",
    "Production: alert on more than one value-moving call into the same contract in a single transaction, and on one-transaction profit after a flash loan."
   ],
   "grep": "grep -rnE \"\\.call\\{|safeTransfer|_safeMint|onERC721Received|tokensReceived|nonReentrant\" src/",
   "defense_checks": "grep -rnE \"nonReentrant|ReentrancyGuard|_status|locked|mutex\" src/; # CI: slither . --detect reentrancy-eth,reentrancy-no-eth,reentrancy-benign,reentrancy-eth-infinite",
   "tagged_incidents": 67,
   "case_studies": [
    {
     "name": "Curve pools, Vyper compiler lock bug (2023-07)",
     "rekt": "https://rekt.news/curve-vyper-rekt/",
     "poc_file": "src/test/2023-07/Curve_exp01.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2023-07/Curve_exp01.sol",
     "forge_command": "forge test --contracts ./src/test/2023-07/Curve_exp01.sol -vvv"
    },
    {
     "name": "Cream Finance (2021-08)",
     "rekt": "https://rekt.news/cream-rekt/",
     "poc_file": "src/test/2021-08/Cream_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2021-08/Cream_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2021-08/Cream_exp.sol -vvv"
    },
    {
     "name": "Sentiment, read-only reentrancy (2023-04)",
     "rekt": null,
     "poc_file": "src/test/2023-04/Sentiment_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2023-04/Sentiment_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2023-04/Sentiment_exp.sol -vvv"
    },
    {
     "name": "Conic Finance (2023-07)",
     "rekt": "https://rekt.news/conic-finance-rekt/",
     "poc_file": "src/test/2023-07/Conic_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2023-07/Conic_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2023-07/Conic_exp.sol -vvv"
    }
   ]
  },
  {
   "id": "access-control",
   "name": "Access control and privileged functions",
   "swc": "SWC-105 · SWC-115",
   "summary": "A state-changing function that should be restricted is callable by anyone, or authorization is checked against the wrong principal (tx.origin, a spoofable parameter, a caller-supplied contract).",
   "attacker_questions": [
    "List every external/public function that writes state. Which ones lack a modifier, and why?",
    "Can an initializer be called twice, or on the implementation contract directly?",
    "Does authorization depend on msg.sender of a contract that forwards arbitrary calls?",
    "Can the attacker become the keeper, the relayer, or the \"trusted\" contract by deploying something?",
    "Are roles granted by a function that is itself unprotected?"
   ],
   "defense_for_question": [
    "Default-deny: every state-changing external or public function has an explicit onlyOwner, onlyRole, or a written reason it is meant to be open. A function with no modifier needs a reviewed justification and a test that an outsider cannot abuse it.",
    "Call initialize once, in the same transaction as deploy when you can. Use _disableInitializers() in the implementation constructor. Add a test that a second initialize and a direct initialize on the implementation both revert.",
    "Authorize against the immediate msg.sender. Do not use tx.origin. Do not trust a caller-supplied \"trusted\" address or a forwarder unless it is a fixed, audited adapter whose sender is recovered correctly (for example ERC-2771 with a locked trusted forwarder).",
    "Keepers and relayers are an allowlist or a role set by governance, not \"first contract to show up\". Require a role, a signature with a nonce, or a governance-set address. Test that a freshly deployed contract cannot assume the role.",
    "Role grants require a higher, already-assigned role (OpenZeppelin AccessControl). Transfer of admin is two-step. Review role members on every release."
   ],
   "pairs": [
    {
     "attacker_question": "List every external/public function that writes state. Which ones lack a modifier, and why?",
     "defense": "Default-deny: every state-changing external or public function has an explicit onlyOwner, onlyRole, or a written reason it is meant to be open. A function with no modifier needs a reviewed justification and a test that an outsider cannot abuse it."
    },
    {
     "attacker_question": "Can an initializer be called twice, or on the implementation contract directly?",
     "defense": "Call initialize once, in the same transaction as deploy when you can. Use _disableInitializers() in the implementation constructor. Add a test that a second initialize and a direct initialize on the implementation both revert."
    },
    {
     "attacker_question": "Does authorization depend on msg.sender of a contract that forwards arbitrary calls?",
     "defense": "Authorize against the immediate msg.sender. Do not use tx.origin. Do not trust a caller-supplied \"trusted\" address or a forwarder unless it is a fixed, audited adapter whose sender is recovered correctly (for example ERC-2771 with a locked trusted forwarder)."
    },
    {
     "attacker_question": "Can the attacker become the keeper, the relayer, or the \"trusted\" contract by deploying something?",
     "defense": "Keepers and relayers are an allowlist or a role set by governance, not \"first contract to show up\". Require a role, a signature with a nonce, or a governance-set address. Test that a freshly deployed contract cannot assume the role."
    },
    {
     "attacker_question": "Are roles granted by a function that is itself unprotected?",
     "defense": "Role grants require a higher, already-assigned role (OpenZeppelin AccessControl). Transfer of admin is two-step. Review role members on every release."
    }
   ],
   "mitigation": [
    "Explicit access modifier on every state-changing entry point; AccessControl or Ownable2Step, not ad-hoc address checks.",
    "Initializers disabled on the implementation; two-step ownership and role admin.",
    "No tx.origin; no caller-supplied authority."
   ],
   "detection": [
    "CI: Slither vars-and-auth printer; a test that an unprivileged address cannot call each privileged function or initialize twice.",
    "Production: alert on RoleGranted, OwnershipTransferred, initialize, and the first call of a previously unused admin function, especially from a new address."
   ],
   "grep": "grep -rnE \"function [a-zA-Z_]+\\([^)]*\\) (external|public)\" src/ | grep -vE \"view|pure|only[A-Z]\"",
   "defense_checks": "grep -rnE \"onlyOwner|onlyRole|AccessControl|Ownable|initialize|tx\\.origin|_disableInitializers\" src/; # CI: slither . --print vars-and-auth",
   "tagged_incidents": 100,
   "case_studies": [
    {
     "name": "Poly Network (2021-08)",
     "rekt": "https://rekt.news/polynetwork-rekt/",
     "poc_file": "src/test/2021-08/PolyNetwork_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2021-08/PolyNetwork_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2021-08/PolyNetwork_exp.sol -vvv"
    }
   ]
  },
  {
   "id": "price-oracle-manipulation",
   "name": "Price and oracle manipulation",
   "swc": "—",
   "summary": "The protocol values collateral, shares or swaps from a price the attacker can move within one transaction: AMM spot reserves, a thin pool, a vault share price, or an oracle with a stale or manipulable input.",
   "attacker_questions": [
    "Where does every price come from? Spot reserves, TWAP (window length?), Chainlink (staleness and min/max checks?), an internal exchange rate?",
    "How much capital moves that price by 10%? Is that capital flash-loanable?",
    "Can the attacker donate tokens to a pool or vault to change balanceOf-based accounting?",
    "Is the same price used for both borrowing and liquidation, and can it be moved between the two?"
   ],
   "defense_for_question": [
    "Do not use spot AMM reserves or a raw balanceOf-based rate for collateral, solvency or liquidation. Prefer a manipulation-resistant oracle (for example Chainlink) with heartbeat, sequenced rounds, and min/max deviation checks, plus a documented fallback if the feed is stale.",
    "If a flash-loan-sized trade can move the price used for solvency, that price is not safe. Use an oracle the same trade cannot move in one transaction, or a TWAP whose window is long compared with a flash loan, and still avoid thin pools. Cap how much can be borrowed or liquidated in one block.",
    "Do not price shares or collateral off balanceOf(this)/totalSupply alone. Use virtual offsets or an external oracle, and reject donations that change the rate used for solvency.",
    "Read the oracle once per transaction and use that snapshot for every check, or require that the price not move more than a bound between borrow and liquidation in the same block. Add a circuit breaker if the price moves more than N% in one block."
   ],
   "pairs": [
    {
     "attacker_question": "Where does every price come from? Spot reserves, TWAP (window length?), Chainlink (staleness and min/max checks?), an internal exchange rate?",
     "defense": "Do not use spot AMM reserves or a raw balanceOf-based rate for collateral, solvency or liquidation. Prefer a manipulation-resistant oracle (for example Chainlink) with heartbeat, sequenced rounds, and min/max deviation checks, plus a documented fallback if the feed is stale."
    },
    {
     "attacker_question": "How much capital moves that price by 10%? Is that capital flash-loanable?",
     "defense": "If a flash-loan-sized trade can move the price used for solvency, that price is not safe. Use an oracle the same trade cannot move in one transaction, or a TWAP whose window is long compared with a flash loan, and still avoid thin pools. Cap how much can be borrowed or liquidated in one block."
    },
    {
     "attacker_question": "Can the attacker donate tokens to a pool or vault to change balanceOf-based accounting?",
     "defense": "Do not price shares or collateral off balanceOf(this)/totalSupply alone. Use virtual offsets or an external oracle, and reject donations that change the rate used for solvency."
    },
    {
     "attacker_question": "Is the same price used for both borrowing and liquidation, and can it be moved between the two?",
     "defense": "Read the oracle once per transaction and use that snapshot for every check, or require that the price not move more than a bound between borrow and liquidation in the same block. Add a circuit breaker if the price moves more than N% in one block."
    }
   ],
   "mitigation": [
    "Manipulation-resistant oracle with staleness, sequence and deviation checks; no spot reserves for solvency.",
    "One price snapshot per transaction; borrow and liquidation caps; pause on extreme moves.",
    "No donation-sensitive balanceOf pricing without virtual shares or an external feed."
   ],
   "detection": [
    "CI: an invariant that deposit-borrow-withdraw (or donate-then-borrow) in one transaction cannot extract value, including under a flash-loan-sized reserve move.",
    "Production: alert on large intra-block reserve changes in the pricing pool, missed oracle heartbeats, and deviation against a second source."
   ],
   "grep": "grep -rnE \"getReserves|slot0|latestRoundData|latestAnswer|balanceOf\\(address\\(this\\)\\)|totalAssets|pricePerShare\" src/",
   "defense_checks": "grep -rnE \"latestRoundData|updatedAt|minAnswer|maxAnswer|heartbeat|TWAP|oracle|circuit\" src/",
   "tagged_incidents": 136,
   "case_studies": [
    {
     "name": "Harvest Finance (2020-10)",
     "rekt": "https://rekt.news/harvest-finance-rekt/",
     "poc_file": "src/test/2020-10/HarvestFinance_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2020-10/HarvestFinance_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2020-10/HarvestFinance_exp.sol -vvv"
    },
    {
     "name": "Inverse Finance (2022-06)",
     "rekt": "https://rekt.news/inverse-rekt2/",
     "poc_file": "src/test/2022-06/InverseFinance_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2022-06/InverseFinance_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2022-06/InverseFinance_exp.sol -vvv"
    },
    {
     "name": "Mango Markets (2022-10)",
     "rekt": "https://rekt.news/mango-markets-rekt/",
     "poc_file": null,
     "poc_url": null,
     "forge_command": null
    },
    {
     "name": "bZx (2020-09)",
     "rekt": "https://rekt.news/bzx-rekt/",
     "poc_file": "src/test/2020-09/bzx_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2020-09/bzx_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2020-09/bzx_exp.sol -vvv"
    }
   ]
  },
  {
   "id": "governance",
   "name": "Flash-loan governance and voting power",
   "swc": "—",
   "summary": "Voting power is read at the current block, so borrowed tokens can pass or execute a proposal inside one transaction.",
   "attacker_questions": [
    "Is voting power snapshotted at a past block, or read live?",
    "Is there a delay between proposal, vote and execution? Can emergencyCommit-style paths skip it?",
    "Can delegated or wrapped tokens be counted twice?"
   ],
   "defense_for_question": [
    "Read voting power from a past snapshot (ERC20Votes getPastVotes or equivalent), never from the current balance. A live balance is flash-loanable.",
    "Queue execution behind a timelock (OpenZeppelin TimelockController or equivalent). An emergency path, if it exists, must itself be delayed or held by a separate guardian with a narrow, documented scope — and must be tested as a privileged function.",
    "Count each underlying token once. Exclude wrappers that already vote, or unwrap before tallying. Add a test that a wrapped-and-delegated position cannot vote twice."
   ],
   "pairs": [
    {
     "attacker_question": "Is voting power snapshotted at a past block, or read live?",
     "defense": "Read voting power from a past snapshot (ERC20Votes getPastVotes or equivalent), never from the current balance. A live balance is flash-loanable."
    },
    {
     "attacker_question": "Is there a delay between proposal, vote and execution? Can emergencyCommit-style paths skip it?",
     "defense": "Queue execution behind a timelock (OpenZeppelin TimelockController or equivalent). An emergency path, if it exists, must itself be delayed or held by a separate guardian with a narrow, documented scope — and must be tested as a privileged function."
    },
    {
     "attacker_question": "Can delegated or wrapped tokens be counted twice?",
     "defense": "Count each underlying token once. Exclude wrappers that already vote, or unwrap before tallying. Add a test that a wrapped-and-delegated position cannot vote twice."
    }
   ],
   "mitigation": [
    "Past-block vote snapshots; timelock between queue and execute; no skip-the-timelock path without a reviewed guardian.",
    "Single counting of delegated and wrapped supply; proposal thresholds that are not flash-loanable in practice."
   ],
   "detection": [
    "CI: a test that a same-transaction flash-loan vote or execute cannot pass.",
    "Production: alert if a voter's balance jumps in the vote block, if a proposal is executed in the same transaction as a flash loan, or if an emergency path is used."
   ],
   "grep": "grep -rnE \"getVotes|getPastVotes|balanceOf|propose|execute|emergency\" src/",
   "defense_checks": "grep -rnE \"getPastVotes|getVotes|timelock|queue|execute|emergency\" src/",
   "tagged_incidents": 9,
   "case_studies": [
    {
     "name": "Beanstalk (2022-04)",
     "rekt": "https://rekt.news/beanstalk-rekt/",
     "poc_file": "src/test/2022-04/Beanstalk_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2022-04/Beanstalk_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2022-04/Beanstalk_exp.sol -vvv"
    }
   ]
  },
  {
   "id": "business-logic",
   "name": "Accounting and business-logic flaws",
   "swc": "—",
   "summary": "The code does what it says, but the rules are wrong: a missing health check after one action, debt that can be shed, rewards computed from a value the user controls.",
   "attacker_questions": [
    "Write the protocol's invariants in one sentence each (total debt ≤ total collateral × LTV, sum of shares = total supply). Which function can break each one?",
    "After every user action, is solvency checked? (Euler's donateToReserves skipped it)",
    "Can a user self-liquidate at a profit?",
    "Do two code paths compute the same quantity differently?"
   ],
   "defense_for_question": [
    "Encode each invariant as a test and, where feasible, as an in-contract check that every public path must pass — including \"internal\" or admin paths such as donate. A function that can break an invariant needs a revert or a narrower permission.",
    "Run the solvency or health check at the end of every state-changing path, including donate, liquidate, and admin helpers. Add a test that a path which used to skip the check now reverts when insolvent.",
    "Liquidation math must not pay the borrower for liquidating themselves. Test the self-liquidation path and assert it cannot extract value.",
    "One function (or one library) computes each quantity. If two paths must exist, add a test that they agree on a shared fixture, and delete or wrap the weaker path."
   ],
   "pairs": [
    {
     "attacker_question": "Write the protocol's invariants in one sentence each (total debt ≤ total collateral × LTV, sum of shares = total supply). Which function can break each one?",
     "defense": "Encode each invariant as a test and, where feasible, as an in-contract check that every public path must pass — including \"internal\" or admin paths such as donate. A function that can break an invariant needs a revert or a narrower permission."
    },
    {
     "attacker_question": "After every user action, is solvency checked? (Euler's donateToReserves skipped it)",
     "defense": "Run the solvency or health check at the end of every state-changing path, including donate, liquidate, and admin helpers. Add a test that a path which used to skip the check now reverts when insolvent."
    },
    {
     "attacker_question": "Can a user self-liquidate at a profit?",
     "defense": "Liquidation math must not pay the borrower for liquidating themselves. Test the self-liquidation path and assert it cannot extract value."
    },
    {
     "attacker_question": "Do two code paths compute the same quantity differently?",
     "defense": "One function (or one library) computes each quantity. If two paths must exist, add a test that they agree on a shared fixture, and delete or wrap the weaker path."
    }
   ],
   "mitigation": [
    "Invariants enforced after every state-changing path, including admin and donate.",
    "Single source of truth for each accounting quantity; no profitable self-liquidation."
   ],
   "detection": [
    "CI: invariant and fuzz campaigns that include donate, admin, and liquidation handlers.",
    "Production: alert on a sudden gap between total debt and collateral, on accounting residuals, and on a transaction where the same address is borrower and profitable liquidator."
   ],
   "grep": "grep -rnE \"checkLiquidity|healthFactor|isSolvent|donate|liquidat\" src/",
   "defense_checks": "grep -rnE \"checkLiquidity|healthFactor|isSolvent|invariant|donate|liquidat\" src/",
   "tagged_incidents": 193,
   "case_studies": [
    {
     "name": "Euler Finance (2023-03)",
     "rekt": "https://rekt.news/euler-rekt/",
     "poc_file": "src/test/2023-03/Euler_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2023-03/Euler_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2023-03/Euler_exp.sol -vvv"
    },
    {
     "name": "Raft (2023-11)",
     "rekt": "https://rekt.news/raft-rekt/",
     "poc_file": "src/test/2023-11/Raft_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2023-11/Raft_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2023-11/Raft_exp.sol -vvv"
    },
    {
     "name": "Velocore (2024-06)",
     "rekt": "https://rekt.news/velocore-rekt/",
     "poc_file": "src/test/2024-06/Velocore_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2024-06/Velocore_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2024-06/Velocore_exp.sol -vvv"
    }
   ]
  },
  {
   "id": "rounding-precision",
   "name": "Rounding, precision and empty-market inflation",
   "swc": "SWC-101 (related)",
   "summary": "Integer division rounds in the attacker's favour, usually when a market or vault has almost no supply: donate to inflate the exchange rate, then redeem or borrow with rounding that never charges you.",
   "attacker_questions": [
    "Is any market, vault or pool deployable with zero or tiny supply? What happens at totalSupply = 1?",
    "In every mulDiv, which way does it round, and who benefits?",
    "Can the attacker repeat a 1-wei rounding gain in a loop or across many accounts?",
    "ERC4626: are virtual shares/assets or a dead-share mint used?"
   ],
   "defense_for_question": [
    "Do not leave a market empty and writable by a first depositor. Mint dead shares on init, use a virtual offset (OpenZeppelin ERC4626 inflation-attack pattern), and set a minimum deposit. Test totalSupply = 0 and 1.",
    "Round against the user and in the protocol's favour when issuing shares or paying assets out. Document the direction on each mulDiv and test the off-by-one at the extremes.",
    "A 1-wei gain that can be looped is a real loss. Cap iteration, charge a minimum fee, or change the rounding so the loop cannot profit. Test a tight loop of dust operations.",
    "Use virtual shares and assets or a dead-share mint, as in current OpenZeppelin ERC4626. Reject a first-depositor rate set by a donation."
   ],
   "pairs": [
    {
     "attacker_question": "Is any market, vault or pool deployable with zero or tiny supply? What happens at totalSupply = 1?",
     "defense": "Do not leave a market empty and writable by a first depositor. Mint dead shares on init, use a virtual offset (OpenZeppelin ERC4626 inflation-attack pattern), and set a minimum deposit. Test totalSupply = 0 and 1."
    },
    {
     "attacker_question": "In every mulDiv, which way does it round, and who benefits?",
     "defense": "Round against the user and in the protocol's favour when issuing shares or paying assets out. Document the direction on each mulDiv and test the off-by-one at the extremes."
    },
    {
     "attacker_question": "Can the attacker repeat a 1-wei rounding gain in a loop or across many accounts?",
     "defense": "A 1-wei gain that can be looped is a real loss. Cap iteration, charge a minimum fee, or change the rounding so the loop cannot profit. Test a tight loop of dust operations."
    },
    {
     "attacker_question": "ERC4626: are virtual shares/assets or a dead-share mint used?",
     "defense": "Use virtual shares and assets or a dead-share mint, as in current OpenZeppelin ERC4626. Reject a first-depositor rate set by a donation."
    }
   ],
   "mitigation": [
    "Dead shares or virtual offsets on vaults and markets; minimum deposit.",
    "Rounding in the protocol's favour; no profitable dust loops."
   ],
   "detection": [
    "CI: invariants that donate-then-deposit-or-redeem cannot extract value, and that convertToAssets stays consistent with totalAssets.",
    "Production: alert on the first deposit into an empty market, on a sudden jump in exchange rate, and on many dust-sized operations in one transaction."
   ],
   "grep": "grep -rnE \"mulDiv|/ totalSupply|\\* 1e18 /|convertToShares|convertToAssets|exchangeRate\" src/",
   "defense_checks": "grep -rnE \"virtualOffset|DECIMAL_OFFSET|dead|minDeposit|mulDiv|convertToShares\" src/",
   "tagged_incidents": 34,
   "case_studies": [
    {
     "name": "Hundred Finance (2023-04)",
     "rekt": "https://rekt.news/hundred-rekt2/",
     "poc_file": "src/test/2023-04/HundredFinance_2_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2023-04/HundredFinance_2_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2023-04/HundredFinance_2_exp.sol -vvv"
    },
    {
     "name": "Sonne Finance (2024-05)",
     "rekt": "https://rekt.news/sonne-finance-rekt/",
     "poc_file": "src/test/2024-05/Sonne_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2024-05/Sonne_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2024-05/Sonne_exp.sol -vvv"
    },
    {
     "name": "Radiant Capital (2024-01)",
     "rekt": "https://rekt.news/radiant-capital-rekt/",
     "poc_file": "src/test/2024-01/RadiantCapital_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2024-01/RadiantCapital_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2024-01/RadiantCapital_exp.sol -vvv"
    }
   ]
  },
  {
   "id": "arbitrary-call-approval",
   "name": "Arbitrary external calls and leftover approvals",
   "swc": "SWC-112 (related)",
   "summary": "A router, aggregator or zap executes caller-supplied calldata against caller-supplied targets. Any user who approved that contract can be drained through transferFrom.",
   "attacker_questions": [
    "Can the caller choose both target and calldata of a low-level call?",
    "Do users grant this contract unlimited approvals?",
    "Is the swap result checked by \"balance went up\" only, without checking what was spent?"
   ],
   "defense_for_question": [
    "Do not execute caller-supplied calldata against an arbitrary target from a contract that holds user approvals. Allowlist targets and selectors, or remove the generic call and use a fixed adapter per integration.",
    "Prefer finite allowances, Permit2 with per-token limits, or pull patterns that do not leave an unlimited allowance on a router. Document that integrators should not approve max uint.",
    "Check both the amount spent and the amount received against a minOut and a token allowlist. A \"balance went up\" check on an unexpected token is not a defense."
   ],
   "pairs": [
    {
     "attacker_question": "Can the caller choose both target and calldata of a low-level call?",
     "defense": "Do not execute caller-supplied calldata against an arbitrary target from a contract that holds user approvals. Allowlist targets and selectors, or remove the generic call and use a fixed adapter per integration."
    },
    {
     "attacker_question": "Do users grant this contract unlimited approvals?",
     "defense": "Prefer finite allowances, Permit2 with per-token limits, or pull patterns that do not leave an unlimited allowance on a router. Document that integrators should not approve max uint."
    },
    {
     "attacker_question": "Is the swap result checked by \"balance went up\" only, without checking what was spent?",
     "defense": "Check both the amount spent and the amount received against a minOut and a token allowlist. A \"balance went up\" check on an unexpected token is not a defense."
    }
   ],
   "mitigation": [
    "Allowlisted targets and selectors; no arbitrary call while holding user allowances.",
    "Finite allowances or Permit2; spent and received amounts both checked against expected tokens and minOut."
   ],
   "detection": [
    "CI: a test that a caller-supplied target cannot transferFrom a third-party approver.",
    "Production: alert on a router call to a non-allowlisted target, and on a single transaction that transferFroms many users."
   ],
   "grep": "grep -rnE \"\\.call\\(|functionCall|executor|_execute|multicall|transferFrom\\(\" src/",
   "defense_checks": "grep -rnE \"onlyAllowed|allowlist|minOut|Permit2|safeApprove|approve\\(\" src/",
   "tagged_incidents": 45,
   "case_studies": [
    {
     "name": "Socket Gateway (2024-01)",
     "rekt": "https://rekt.news/socket-rekt/",
     "poc_file": "src/test/2024-01/SocketGateway_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2024-01/SocketGateway_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2024-01/SocketGateway_exp.sol -vvv"
    },
    {
     "name": "Transit Swap (2022-10)",
     "rekt": "https://rekt.news/transit-swap-rekt/",
     "poc_file": "src/test/2022-10/TransitSwap_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2022-10/TransitSwap_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2022-10/TransitSwap_exp.sol -vvv"
    }
   ]
  },
  {
   "id": "bridge-cross-chain",
   "name": "Bridges and cross-chain message verification",
   "swc": "—",
   "summary": "A message, proof or signature set from another chain is accepted without being proven: a zero root treated as valid, a guardian set not checked, a deprecated verifier still callable.",
   "attacker_questions": [
    "What exactly proves that a message happened on the source chain? Trace it to a signature check or a light-client proof.",
    "Can an initializer or upgrade set the trusted root to a default value?",
    "Can the same message be processed twice?"
   ],
   "defense_for_question": [
    "Every message must verify against the current validator set or a light-client proof. There is no \"trusted default\". Add a test that a message with an empty or default proof reverts.",
    "Initialize so the trusted root or guardian set cannot be zero or a known default. Upgrades go through a timelock. Test that initialize cannot be used after deploy to weaken verification.",
    "Consume a message hash or nonce before minting or releasing funds. Test replay of the same payload and of a payload already executed on another path."
   ],
   "pairs": [
    {
     "attacker_question": "What exactly proves that a message happened on the source chain? Trace it to a signature check or a light-client proof.",
     "defense": "Every message must verify against the current validator set or a light-client proof. There is no \"trusted default\". Add a test that a message with an empty or default proof reverts."
    },
    {
     "attacker_question": "Can an initializer or upgrade set the trusted root to a default value?",
     "defense": "Initialize so the trusted root or guardian set cannot be zero or a known default. Upgrades go through a timelock. Test that initialize cannot be used after deploy to weaken verification."
    },
    {
     "attacker_question": "Can the same message be processed twice?",
     "defense": "Consume a message hash or nonce before minting or releasing funds. Test replay of the same payload and of a payload already executed on another path."
    }
   ],
   "mitigation": [
    "Current validator set or light-client verification; reject zero or default roots.",
    "Replay protection (nonce or message hash consumed first); timelocked upgrades; pause and a watchdog."
   ],
   "detection": [
    "CI: tests that a zero root, a replayed message, and a stale guardian set all revert.",
    "Production: alert on messages from an unexpected root, reused message hashes, guardian-set changes, unusually large unlocks, and initialize events after deploy."
   ],
   "grep": "grep -rnE \"process|proveAndProcess|verify|acceptableRoot|guardian|nonce\" src/",
   "defense_checks": "grep -rnE \"acceptableRoot|guardian|verify|nonce|messageHash|processed\" src/",
   "tagged_incidents": 16,
   "case_studies": [
    {
     "name": "Nomad Bridge (2022-08)",
     "rekt": "https://rekt.news/nomad-rekt/",
     "poc_file": "src/test/2022-08/NomadBridge_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2022-08/NomadBridge_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2022-08/NomadBridge_exp.sol -vvv"
    },
    {
     "name": "Wormhole (2022-02)",
     "rekt": "https://rekt.news/wormhole-rekt/",
     "poc_file": null,
     "poc_url": null,
     "forge_command": null
    }
   ]
  },
  {
   "id": "signature-replay",
   "name": "Signatures, replay and permit",
   "swc": "SWC-117 · SWC-121",
   "summary": "A signed message can be reused (no nonce, no chain id, no deadline), malleated, or verified against the wrong signer.",
   "attacker_questions": [
    "Does the signed payload include nonce, chainId, contract address and deadline?",
    "Is the nonce consumed before or after the external call?",
    "Is ecrecover's zero address return rejected?"
   ],
   "defense_for_question": [
    "Use EIP-712 typed data with name, version, chainId, verifyingContract, nonce and deadline. Reject expired or foreign-chain signatures. Test a signature replayed on another chain or contract.",
    "Consume the nonce before any external call so a reentrant or cycled use cannot reuse it. Test that a second use of the same signature reverts.",
    "Use OpenZeppelin ECDSA (or equivalent) which rejects a zero-address recovery and handles malleability. Never use raw ecrecover without those checks."
   ],
   "pairs": [
    {
     "attacker_question": "Does the signed payload include nonce, chainId, contract address and deadline?",
     "defense": "Use EIP-712 typed data with name, version, chainId, verifyingContract, nonce and deadline. Reject expired or foreign-chain signatures. Test a signature replayed on another chain or contract."
    },
    {
     "attacker_question": "Is the nonce consumed before or after the external call?",
     "defense": "Consume the nonce before any external call so a reentrant or cycled use cannot reuse it. Test that a second use of the same signature reverts."
    },
    {
     "attacker_question": "Is ecrecover's zero address return rejected?",
     "defense": "Use OpenZeppelin ECDSA (or equivalent) which rejects a zero-address recovery and handles malleability. Never use raw ecrecover without those checks."
    }
   ],
   "mitigation": [
    "EIP-712 with nonce, chainId, verifyingContract and deadline; nonce consumed first.",
    "OpenZeppelin ECDSA or equivalent (no raw ecrecover, no zero signer)."
   ],
   "detection": [
    "CI: tests for replay, expired deadline, wrong chainId, wrong contract, and a zero-address recovery.",
    "Production: alert on a reused (signer, nonce) pair or the same digest observed on two chains."
   ],
   "grep": "grep -rnE \"ecrecover|ECDSA|permit|nonces|DOMAIN_SEPARATOR|deadline\" src/",
   "defense_checks": "grep -rnE \"DOMAIN_SEPARATOR|EIP712|nonces|ECDSA|tryRecover\" src/",
   "tagged_incidents": 18,
   "case_studies": [
    {
     "name": "Argent-style wallet module (2026-10)",
     "rekt": null,
     "poc_file": "src/test/2026-10/Argent_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2026-10/Argent_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2026-10/Argent_exp.sol -vvv"
    }
   ]
  },
  {
   "id": "proxy-storage-init",
   "name": "Proxies, storage collisions and initialization",
   "swc": "SWC-124 (related)",
   "summary": "Upgradeable contracts share storage between proxy and implementation. Wrong slot layout, an unprotected initializer, or a delegatecall into attacker code changes who owns the system.",
   "attacker_questions": [
    "Is the implementation initialized, or can anyone call initialize() on it?",
    "Do proxy admin variables collide with implementation storage?",
    "Does an upgrade change storage order?"
   ],
   "defense_for_question": [
    "Disable initializers in the implementation constructor (_disableInitializers). Initialize the proxy atomically at deploy. Test that a direct initialize on the implementation reverts.",
    "Use ERC-1967 (or another standard) slots for proxy admin and implementation. Do not pack admin state into the same slots as the implementation. Check layout with the OpenZeppelin Upgrades plugin or equivalent on every upgrade.",
    "Keep storage append-only, with reserved gaps on base contracts. Run a storage-layout diff in CI; reject upgrades that reorder or change existing slots. Timelock the upgrade itself."
   ],
   "pairs": [
    {
     "attacker_question": "Is the implementation initialized, or can anyone call initialize() on it?",
     "defense": "Disable initializers in the implementation constructor (_disableInitializers). Initialize the proxy atomically at deploy. Test that a direct initialize on the implementation reverts."
    },
    {
     "attacker_question": "Do proxy admin variables collide with implementation storage?",
     "defense": "Use ERC-1967 (or another standard) slots for proxy admin and implementation. Do not pack admin state into the same slots as the implementation. Check layout with the OpenZeppelin Upgrades plugin or equivalent on every upgrade."
    },
    {
     "attacker_question": "Does an upgrade change storage order?",
     "defense": "Keep storage append-only, with reserved gaps on base contracts. Run a storage-layout diff in CI; reject upgrades that reorder or change existing slots. Timelock the upgrade itself."
    }
   ],
   "mitigation": [
    "_disableInitializers on the implementation; atomic initialize at deploy; two-step admin.",
    "Standard proxy slots; append-only storage with CI layout checks; timelocked upgrades."
   ],
   "detection": [
    "CI: OpenZeppelin Upgrades storage-layout check; tests that a second initialize and an implementation initialize revert.",
    "Production: alert on initialize after deploy, unexpected upgradeTo, and a change of proxy admin."
   ],
   "grep": "grep -rnE \"initialize|initializer|delegatecall|upgradeTo|_IMPLEMENTATION_SLOT\" src/",
   "defense_checks": "grep -rnE \"_disableInitializers|initializer|upgradeTo|_IMPLEMENTATION_SLOT|ERC1967\" src/",
   "tagged_incidents": 12,
   "case_studies": [
    {
     "name": "Audius (2022-07)",
     "rekt": "https://rekt.news/audius-rekt/",
     "poc_file": "src/test/2022-07/Audius_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2022-07/Audius_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2022-07/Audius_exp.sol -vvv"
    }
   ]
  },
  {
   "id": "token-mechanics",
   "name": "Non-standard tokens: fee-on-transfer, rebasing, reflection",
   "swc": "—",
   "summary": "Code assumes amount sent equals amount received, or that balances only change on transfer. Reflection and rebasing tokens break AMM reserve accounting (skim/sync).",
   "attacker_questions": [
    "Is the received amount measured (balance before/after) or assumed?",
    "Can the attacker call skim/sync or deliver() on a reflection token to desync reserves?"
   ],
   "defense_for_question": [
    "Measure the actual received amount (balance after minus balance before) for every transfer in, so fee-on-transfer cannot desync accounting. Do not assume amount sent equals amount received.",
    "Allowlist standard tokens, or handle rebase and reflection explicitly and restrict skim/sync so a listed non-standard token cannot desync reserves. Test a fee-on-transfer and a rebasing token against the pool."
   ],
   "pairs": [
    {
     "attacker_question": "Is the received amount measured (balance before/after) or assumed?",
     "defense": "Measure the actual received amount (balance after minus balance before) for every transfer in, so fee-on-transfer cannot desync accounting. Do not assume amount sent equals amount received."
    },
    {
     "attacker_question": "Can the attacker call skim/sync or deliver() on a reflection token to desync reserves?",
     "defense": "Allowlist standard tokens, or handle rebase and reflection explicitly and restrict skim/sync so a listed non-standard token cannot desync reserves. Test a fee-on-transfer and a rebasing token against the pool."
    }
   ],
   "mitigation": [
    "Balance-before/after accounting for every inbound transfer.",
    "Token allowlists, or explicit rebase/reflection handling; restricted skim/sync."
   ],
   "detection": [
    "CI: tests with fee-on-transfer and rebasing tokens that accounting still matches.",
    "Production: alert when transfer amount ≠ balance delta, on unexpected skim/sync, and on reserve/balance desync."
   ],
   "grep": "grep -rnE \"skim|sync\\(|deliver|reflect|_rOwned|balanceOf\\(address\\(this\\)\\)\" src/",
   "defense_checks": "grep -rnE \"balanceOf\\(address\\(this\\)\\)|allowedToken|feeOnTransfer|skim|sync\\(\" src/",
   "tagged_incidents": 25,
   "case_studies": []
  },
  {
   "id": "randomness",
   "name": "On-chain randomness",
   "swc": "SWC-120",
   "summary": "Outcomes derived from block values or contract state can be predicted or retried by a contract that reverts on a bad roll.",
   "attacker_questions": [
    "Is randomness from blockhash, timestamp, prevrandao or internal state?",
    "Can the caller revert and retry within the same transaction?"
   ],
   "defense_for_question": [
    "Do not use blockhash, timestamp, prevrandao, or contract state alone for any outcome of value. Use a VRF (for example Chainlink VRF) or a commit-reveal with a long enough delay and a penalty for not revealing.",
    "If a bad roll can be retried, the roll is worthless. Bind the caller to the outcome (VRF callback, or a reveal that cannot be repeated) so a revert cannot re-roll in the same transaction. Test that a contract which reverts on a losing roll cannot retry."
   ],
   "pairs": [
    {
     "attacker_question": "Is randomness from blockhash, timestamp, prevrandao or internal state?",
     "defense": "Do not use blockhash, timestamp, prevrandao, or contract state alone for any outcome of value. Use a VRF (for example Chainlink VRF) or a commit-reveal with a long enough delay and a penalty for not revealing."
    },
    {
     "attacker_question": "Can the caller revert and retry within the same transaction?",
     "defense": "If a bad roll can be retried, the roll is worthless. Bind the caller to the outcome (VRF callback, or a reveal that cannot be repeated) so a revert cannot re-roll in the same transaction. Test that a contract which reverts on a losing roll cannot retry."
    }
   ],
   "mitigation": [
    "VRF or delayed commit-reveal for any valued outcome; no raw block properties.",
    "Outcomes bind the caller; a revert cannot re-roll."
   ],
   "detection": [
    "CI: a static scan for block.timestamp, blockhash and prevrandao on value paths, and a test that a revert-retry attacker cannot improve a roll.",
    "Production: alert on contracts that loop or revert-retry around a randomness call in one transaction."
   ],
   "grep": "grep -rnE \"blockhash|block\\.timestamp|prevrandao|difficulty|keccak256\\(abi\\.encodePacked\\(block\" src/",
   "defense_checks": "grep -rnE \"VRF|commitReveal|requestRandom|blockhash|prevrandao\" src/",
   "tagged_incidents": 4,
   "case_studies": []
  },
  {
   "id": "integer-overflow",
   "name": "Integer overflow and unchecked math",
   "swc": "SWC-101",
   "summary": "Solidity < 0.8 wraps silently; ≥ 0.8 still wraps inside unchecked blocks and in casts (uint256 → uint128).",
   "attacker_questions": [
    "Which unchecked blocks handle user-influenced values?",
    "Which downcasts are not SafeCast?"
   ],
   "defense_for_question": [
    "Prefer Solidity 0.8+ with checked math. Do not put user-influenced values in unchecked. If unchecked is required, prove the bound and test at the extrema.",
    "Downcast only through SafeCast (or an equivalent revert-on-overflow cast). Test uint256 values just above the target type's maximum."
   ],
   "pairs": [
    {
     "attacker_question": "Which unchecked blocks handle user-influenced values?",
     "defense": "Prefer Solidity 0.8+ with checked math. Do not put user-influenced values in unchecked. If unchecked is required, prove the bound and test at the extrema."
    },
    {
     "attacker_question": "Which downcasts are not SafeCast?",
     "defense": "Downcast only through SafeCast (or an equivalent revert-on-overflow cast). Test uint256 values just above the target type's maximum."
    }
   ],
   "mitigation": [
    "Solidity ≥ 0.8 checked math; no user-influenced unchecked arithmetic.",
    "SafeCast (or equivalent) on every downcast; explicit range checks."
   ],
   "detection": [
    "CI: compiler and Slither warnings on unchecked and downcasts; fuzz and unit tests at type maxima.",
    "Production: alert on sudden wraparound-shaped jumps in accounting totals (a total that drops by about 2^n)."
   ],
   "grep": "grep -rnE \"unchecked|uint(8|16|32|64|96|112|128)\\(\" src/",
   "defense_checks": "grep -rnE \"unchecked|SafeCast|uint(8|16|32|64|96|112|128)\\(\" src/",
   "tagged_incidents": 12,
   "case_studies": []
  },
  {
   "id": "dos-griefing",
   "name": "Denial of service and griefing",
   "swc": "SWC-128",
   "summary": "An attacker cannot steal but can block withdrawals, liquidations or upgrades: unbounded loops, a reverting receiver, a front-run initializer.",
   "attacker_questions": [
    "Is there a loop over a user-growable array?",
    "Can one reverting recipient block a batch payout?",
    "Can liquidations be blocked by the borrower?"
   ],
   "defense_for_question": [
    "Bound every loop, or switch to a pull pattern so users claim individually. Do not iterate an array that any user can grow without a hard cap. Test a large array against the block gas limit.",
    "Use pull payments, or try/catch per recipient, so one reverting receiver cannot block the rest. Test a recipient that reverts on receive or on ERC-20 hooks.",
    "A liquidation must not depend on the borrower being able to receive tokens, or on a single permissioned keeper. Allow a third-party liquidator and send the borrower's remainder with a pattern that cannot revert the whole transaction."
   ],
   "pairs": [
    {
     "attacker_question": "Is there a loop over a user-growable array?",
     "defense": "Bound every loop, or switch to a pull pattern so users claim individually. Do not iterate an array that any user can grow without a hard cap. Test a large array against the block gas limit."
    },
    {
     "attacker_question": "Can one reverting recipient block a batch payout?",
     "defense": "Use pull payments, or try/catch per recipient, so one reverting receiver cannot block the rest. Test a recipient that reverts on receive or on ERC-20 hooks."
    },
    {
     "attacker_question": "Can liquidations be blocked by the borrower?",
     "defense": "A liquidation must not depend on the borrower being able to receive tokens, or on a single permissioned keeper. Allow a third-party liquidator and send the borrower's remainder with a pattern that cannot revert the whole transaction."
    }
   ],
   "mitigation": [
    "Bounded loops or pull payments; isolated recipients (try/catch or claim).",
    "Liquidations that cannot be blocked by the borrower or by a single keeper."
   ],
   "detection": [
    "CI: tests with a reverting receiver, a large user-grown array, and a borrower who tries to block liquidation.",
    "Production: alert if a payout batch reverts, if liquidations fail repeatedly, or if gas use of a loop grows with user count."
   ],
   "grep": "grep -rnE \"for \\(|while \\(|\\.transfer\\(|require\\(success\" src/",
   "defense_checks": "grep -rnE \"for \\(|while \\(|try |claim\\(|pull\" src/",
   "tagged_incidents": 0,
   "case_studies": []
  },
  {
   "id": "key-compromise",
   "name": "Operational key compromise (out of contract scope)",
   "swc": "—",
   "summary": "Not a code bug: validator or multisig keys taken. Listed because many large losses are this class; most bounty programs treat it as out of scope.",
   "attacker_questions": [
    "How many keys control upgrades or bridge validation, and where are they held?"
   ],
   "defense_for_question": [
    "Use a threshold multisig or MPC so no single machine holds enough shares. Separate keys geographically and operationally, keep them in hardware security modules, and put a timelock plus a watcher that can pause on upgrades and validator-set changes. Rotate keys and rehearse a compromise plan."
   ],
   "pairs": [
    {
     "attacker_question": "How many keys control upgrades or bridge validation, and where are they held?",
     "defense": "Use a threshold multisig or MPC so no single machine holds enough shares. Separate keys geographically and operationally, keep them in hardware security modules, and put a timelock plus a watcher that can pause on upgrades and validator-set changes. Rotate keys and rehearse a compromise plan."
    }
   ],
   "mitigation": [
    "Threshold multisig or MPC; hardware-backed, separated shares; no single laptop with enough keys.",
    "Timelock on upgrades and validator-set changes; an independent watcher that can pause; practiced key rotation."
   ],
   "detection": [
    "Ops: alert on signer-set changes, unexpected upgrade or privileged withdrawal, and a known key appearing from a new host.",
    "On-chain: monitor the guardian or validator set and the timelock queue; treat an unscheduled change as an incident."
   ],
   "grep": "",
   "defense_checks": "grep -rnE \"owner|guardian|validator|multisig|timelock\" src/ || true",
   "tagged_incidents": 3,
   "case_studies": [
    {
     "name": "Ronin Bridge (2022-03)",
     "rekt": "https://rekt.news/ronin-rekt/",
     "poc_file": "src/test/2022-03/Ronin_exp.sol",
     "poc_url": "https://github.com/SunWeb3Sec/DeFiHackLabs/blob/49c6604ed67b5c41e005f067c8987567d9e8ab22/src/test/2022-03/Ronin_exp.sol",
     "forge_command": "forge test --contracts ./src/test/2022-03/Ronin_exp.sol -vvv"
    }
   ]
  }
 ]
}