Skip to main content
ClaudeWave
Skill109 estrellas del repoactualizado 2mo ago

input-arithmetic-safety

Detects input validation failures and arithmetic vulnerabilities in smart contracts. Covers missing zero-address and zero-amount checks, division-before-multiplication precision loss, rounding direction exploitation, ERC4626 vault share inflation attacks, unsafe integer casting, dust amount exploitation, and Solidity 0.8+ unchecked block edge cases. Use when auditing contracts with fee calculations, share pricing, exchange rates, unchecked blocks, or any public-facing functions that accept user input.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/quillai-network/quillshield_skills /tmp/input-arithmetic-safety && cp -r /tmp/input-arithmetic-safety/plugins/input-arithmetic-safety/skills/input-arithmetic-safety ~/.claude/skills/input-arithmetic-safety
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# Input & Arithmetic Safety

Detect **input validation failures** (the #1 direct exploitation cause at 34.6% of all contract exploits) and **arithmetic vulnerabilities** that persist even with Solidity 0.8+ checked math — precision loss, rounding exploitation, unsafe casting, and share price manipulation.

## When to Use

- Auditing any contract with public/external functions accepting user-supplied parameters
- Reviewing DeFi protocols with fee calculations, share pricing, or exchange rates
- Analyzing vault/staking contracts for rounding or first-depositor attacks
- Checking contracts with `unchecked` blocks for overflow/underflow risks
- Verifying arithmetic in token minting, burning, and distribution logic

## When NOT to Use

- Access control analysis (use semantic-guard-analysis)
- Reentrancy detection (use reentrancy-pattern-analysis)
- Full multi-dimensional audit (use behavioral-state-analysis)

## Part 1: Input Validation Analysis

### Critical Missing Validations

**Zero Address Check:**

```solidity
// VULNERABLE: No zero address check
function setAdmin(address newAdmin) external onlyOwner {
    admin = newAdmin; // Can set admin to address(0) — locking out admin forever
}

// SAFE
function setAdmin(address newAdmin) external onlyOwner {
    require(newAdmin != address(0), "Zero address");
    admin = newAdmin;
}
```

**Zero Amount Check:**

```solidity
// VULNERABLE: Allows zero-amount operations
function deposit(uint256 amount) external {
    balances[msg.sender] += amount;
    emit Deposit(msg.sender, amount);
    // Zero deposit: wastes gas, pollutes events, may affect accounting
}

// SAFE
function deposit(uint256 amount) external {
    require(amount > 0, "Zero amount");
    balances[msg.sender] += amount;
}
```

**Array Length Validation:**

```solidity
// VULNERABLE: No length check
function batchTransfer(address[] calldata recipients, uint256[] calldata amounts) external {
    for (uint i = 0; i < recipients.length; i++) {
        transfer(recipients[i], amounts[i]); // Out-of-bounds if arrays differ in length
    }
}

// SAFE
function batchTransfer(address[] calldata recipients, uint256[] calldata amounts) external {
    require(recipients.length == amounts.length, "Length mismatch");
    require(recipients.length <= MAX_BATCH_SIZE, "Batch too large");
    // ...
}
```

**Bounds Checking:**

```solidity
// VULNERABLE: No upper bound on fee
function setFee(uint256 newFee) external onlyOwner {
    fee = newFee; // Owner can set 100% fee, stealing all user funds
}

// SAFE
function setFee(uint256 newFee) external onlyOwner {
    require(newFee <= MAX_FEE, "Fee too high"); // e.g., MAX_FEE = 1000 (10%)
    fee = newFee;
}
```

### Input Validation Detection Algorithm

```
For each public/external function F:
  For each parameter P:
    1. Is P an address? → Check for require(P != address(0))
    2. Is P an amount/value? → Check for require(P > 0) if zero is invalid
    3. Is P an array? → Check for length validation and max size
    4. Is P a percentage/rate? → Check for upper bound
    5. Is P used as an index? → Check for bounds checking
    6. Is P a deadline/timestamp? → Check for require(P > block.timestamp)

  Flag any parameter without appropriate validation as:
    - CRITICAL if parameter controls fund flow or access
    - HIGH if parameter affects protocol state
    - MEDIUM if parameter affects non-critical functionality
```

## Part 2: Arithmetic Vulnerability Analysis

### Pattern 1: Division-Before-Multiplication (Precision Loss)

```solidity
// VULNERABLE: Division first truncates, then multiplication amplifies error
uint256 result = (amount / totalShares) * price;
// If amount = 100, totalShares = 3: 100/3 = 33 (truncated from 33.33)
// 33 * price = less than expected

// SAFE: Multiply first, then divide
uint256 result = (amount * price) / totalShares;
// 100 * price / 3 = more precise (only one truncation at the end)
```

**Detection:**

```
For each arithmetic expression:
  If division (/) appears BEFORE multiplication (*) in the same expression:
    → PRECISION LOSS: division-before-multiplication
  Exception: If the division result is stored and intentionally used as a floored value
```

### Pattern 2: Rounding Direction Exploitation

In financial protocols, rounding direction determines who benefits:

```
Protocol-favorable rounding:
  - Deposits: round DOWN shares (user gets fewer shares)
  - Withdrawals: round DOWN assets (user gets fewer assets)
  - Fees: round UP fee amount (protocol collects more)

User-favorable rounding (VULNERABLE to extraction):
  - Deposits: round UP shares → user gets more than entitled
  - Withdrawals: round UP assets → user extracts more than entitled
  - Fees: round DOWN → protocol collects less
```

```solidity
// VULNERABLE: Rounds in user's favor on withdrawal
function withdraw(uint256 shares) external returns (uint256 assets) {
    assets = (shares * totalAssets()) / totalSupply(); // Rounds DOWN — correct for withdrawal
    // BUT if this rounds UP somehow (e.g., via ceiling division):
    assets = (shares * totalAssets() + totalSupply() - 1) / totalSupply(); // Rounds UP — BAD
}

// SAFE: Use mulDiv with explicit rounding direction
assets = shares.mulDiv(totalAssets(), totalSupply(), Math.Rounding.Down); // For withdrawals
shares = assets.mulDiv(totalSupply(), totalAssets(), Math.Rounding.Up);   // For deposits
```

### Pattern 3: ERC4626 Vault Share Inflation Attack

```solidity
// Attack on first deposit
contract VulnerableVault is ERC4626 {
    function totalAssets() public view returns (uint256) {
        return asset.balanceOf(address(this)); // Manipulable via donation!
    }

    // No virtual shares offset
    function _convertToShares(uint256 assets) internal view returns (uint256) {
        uint256 supply = totalSupply();
        return supply == 0 ? assets : assets.mulDiv(supply, totalAssets());
    }
}
```

**Attack Sequence:**

```
1. Vault is empty (totalSupply = 0, totalAssets = 0)
2. Attacker dep
behavioral-state-analysisSkill

Token-efficient smart contract security auditing via Behavioral State Analysis (BSA). Scopes analysis to contract type, runs only relevant threat engines, and uses tiered output depth. Use for auditing smart contracts, security reviews, or DeFi threat modeling.

defenderSkill

Blue-team release-gate analysis for smart contract deployment and upgrade readiness. Classifies repositories, checks deploy/upgrade execution paths, CI/CD trust boundaries, config drift, secrets/signer operational security, and outputs evidence-backed release verdicts.

dos-griefing-analysisSkill

Detects Denial of Service and griefing vulnerabilities in smart contracts. Covers unbounded loop DoS, block gas limit exhaustion, external call failure DoS, insufficient gas griefing (63/64 rule), storage bloat attacks, timestamp griefing, self-destruct force-feeding, and push vs pull payment pattern analysis. Use when auditing contracts with batch operations, loops over user data, reward distribution, dividend systems, or any logic that depends on address(this).balance or iterates over growing collections.

external-call-safetySkill

Detects unsafe external call patterns and token integration vulnerabilities in smart contracts. Covers unchecked call/delegatecall/staticcall return values, fee-on-transfer tokens, rebasing tokens, tokens with missing return values (USDT), ERC-777 callback risks, unsafe approve race conditions, return data bombs, gas stipend limitations, and push vs pull payment patterns. Use when auditing contracts that interact with external contracts, integrate arbitrary ERC20 tokens, distribute payments, or make low-level calls.

oracle-flashloan-analysisSkill

Detects price oracle manipulation and flash loan attack vectors in DeFi smart contracts. Classifies oracle trust models (Chainlink, TWAP, spot price, custom), identifies stale price risks, circular price dependencies, and flash loan atomicity exploitation patterns. Use when auditing DeFi protocols that depend on price data, oracle integrations, lending protocols, DEXs, derivatives, or any contract where flash loans could manipulate state within a single transaction.

proxy-upgrade-safetySkill

Detects vulnerabilities in upgradeable proxy smart contracts including storage layout collisions, uninitialized implementations, function selector clashing, delegatecall context issues, and upgrade path safety. Covers Transparent Proxy, UUPS (EIP-1822), Beacon, Diamond (EIP-2535), and Minimal Proxy (EIP-1167) patterns. Use when auditing upgradeable contracts, reviewing implementation upgrades, analyzing delegatecall architectures, or verifying proxy pattern compliance.

reentrancy-pattern-analysisSkill

Systematically detects all reentrancy vulnerability variants in smart contracts — classic, cross-function, cross-contract, and read-only reentrancy. Builds call graphs, verifies CEI (Checks-Effects-Interactions) pattern compliance, traces state changes relative to external calls, and identifies callback vectors through ERC-777/ERC-1155 hooks. Use when auditing contracts that make external calls, transfer ETH or tokens, interact with callback-enabled standards, or have complex multi-contract architectures.

semantic-guard-analysisSkill

Detects logic vulnerabilities in smart contracts by analyzing guard-state consistency patterns. Identifies functions that bypass security checks (require, modifiers) that other functions consistently apply. Uses the Consistency Principle — a contract is its own specification. Use when auditing smart contracts for missing access controls, inconsistent pause checks, logic bugs, forgotten modifiers, or when traditional tools report no issues but logic errors may exist.