Reentrancy Pattern Analysis 标志

Reentrancy Pattern Analysis

组织
quillai-network
reentrancy-pattern-analysis

系统地检测智能合约中的各种重入漏洞,包括经典重入、跨函数重入、跨合约重入和只读重入。构建调用图,验证是否遵循 CEI(检查-效果-交互)模式,追踪外部调用前后的状态变化,并识别通过 ERC-777/ERC-1155 钩子实现的回调攻击路径。审计会发起外部调用、转移 ETH 或 Token、与支持回调的标准交互,或采用复杂多合约架构的合约时使用。

Add to TypingMind

概览

发布者quillai-network
代码仓库quillshield_skills
技能名称reentrancy-pattern-analysis
星标数
131
复刻数
28
附带文件
2
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 2 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 quillai-network 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Reentrancy Pattern Analysis AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/quillai-network/quillshield_skills/tree/main/plugins/reentrancy-pattern-analysis/skills/reentrancy-pattern-analysis
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/quillai-network/quillshield_skills.git /tmp/quillshield_skills
mkdir -p .claude/skills
cp -r /tmp/quillshield_skills/plugins/reentrancy-pattern-analysis/skills/reentrancy-pattern-analysis .claude/skills/reentrancy-pattern-analysis
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Reentrancy Pattern Analysis,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Reentrancy Pattern Analysis。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Reentrancy Pattern Analysis 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Reentrancy Pattern Analysis

Systematically detect all variants of reentrancy vulnerabilities by mapping the relationship between external calls and state changes across the entire contract system.

When to Use

  • Auditing any contract that makes external calls (ETH transfers, token interactions, cross-contract calls)
  • Reviewing contracts integrating with callback-enabled token standards (ERC-777, ERC-1155)
  • Analyzing DeFi protocols with multi-contract architectures
  • Verifying reentrancy guard coverage across all entry points
  • When traditional tools only check for classic reentrancy but miss cross-function or read-only variants

When NOT to Use

  • Pure state variable analysis without external calls (use state-invariant-detection)
  • Access control consistency checking (use semantic-guard-analysis)
  • Full multi-dimensional audit (use behavioral-state-analysis, which orchestrates this skill)

Core Concept: The CEI Invariant

Checks-Effects-Interactions (CEI) is the fundamental safety pattern:

1. CHECKS   — Validate all conditions (require statements, access control)
2. EFFECTS  — Update all state variables
3. INTERACTIONS — Make external calls (ETH transfers, token calls, cross-contract)

Any function that performs INTERACTIONS before completing all EFFECTS is potentially vulnerable to reentrancy.

The Five Reentrancy Variants

Variant 1: Classic Single-Function Reentrancy

The original and most well-known pattern. A function makes an external call before updating its own state, allowing the callee to re-enter the same function.

solidity
// VULNERABLE
function withdraw(uint256 amount) public {
    require(balances[msg.sender] >= amount);
    (bool success, ) = msg.sender.call{value: amount}(""); // INTERACTION before EFFECT
    require(success);
    balances[msg.sender] -= amount; // State update AFTER external call
}

Detection: Find functions where state writes to variables used in require checks occur AFTER external calls.

Variant 2: Cross-Function Reentrancy

Two or more functions share state, and an attacker re-enters through a DIFFERENT function than the one making the external call.

solidity
function withdraw(uint256 amount) public {
    require(balances[msg.sender] >= amount);
    (bool success, ) = msg.sender.call{value: amount}("");
    require(success);
    balances[msg.sender] -= amount;
}

// Attacker re-enters HERE during withdraw's external call
function transfer(address to, uint256 amount) public {
    require(balances[msg.sender] >= amount);
    balances[msg.sender] -= amount;
    balances[to] += amount;
}

Detection: For each external call in function F, check if any OTHER public function reads/writes the same state variables that F modifies after the call.

Variant 3: Cross-Contract Reentrancy

The re-entry occurs through a different contract that shares state or trust relationships with the vulnerable contract.

solidity
// Contract A
function withdrawFromVault() public {
    uint256 shares = vault.balanceOf(msg.sender);
    vault.burn(msg.sender, shares);
    // External call — attacker can re-enter Contract B
    (bool success, ) = msg.sender.call{value: shares * pricePerShare}("");
    require(success);
}

// Contract B (attacker re-enters here)
function borrow() public {
    uint256 collateral = vault.balanceOf(msg.sender); // Reads stale state!
    // Shares not yet burned, so collateral appears inflated
    uint256 loanAmount = collateral * maxLTV;
    token.transfer(msg.sender, loanAmount);
}

Detection: Map all cross-contract dependencies. For each external call, identify which other contracts read the state that should have been updated.

Variant 4: Read-Only Reentrancy

A view/pure function returns stale state during a reentrancy callback. No state is modified during re-entry — the attacker exploits the READING of inconsistent state by a third-party contract.

solidity
// Pool contract
function removeLiquidity() external {
    uint256 shares = balances[msg.sender];
    // Burns LP tokens (updates internal accounting)
    _burn(msg.sender, shares);
    // External call BEFORE updating reserves
    (bool success, ) = msg.sender.call{value: ethAmount}("");
    // Reserves updated AFTER the call
    totalReserves -= ethAmount;
}

// This view function returns stale data during the callback
function getRate() public view returns (uint256) {
    return totalReserves / totalSupply(); // totalReserves not yet updated!
}

// Third-party contract reads the inflated rate
function priceOracle() external view returns (uint256) {
    return pool.getRate(); // Returns wrong value during reentrancy
}

Detection: For each external call, identify view functions that read state variables modified AFTER the call. Check if any external protocol depends on those view functions.

Variant 5: ERC-777 / ERC-1155 Callback Reentrancy

Token standards with built-in callback hooks that execute arbitrary code on the receiver during transfers.

solidity
// ERC-777: tokensReceived() hook called on recipient
// ERC-1155: onERC1155Received() hook called on recipient
// ERC-721: onERC721Received() hook called on recipient

function deposit(uint256 amount) public {
    token.transferFrom(msg.sender, address(this), amount); // Triggers callback!
    // If token is ERC-777, msg.sender's tokensReceived() runs HERE
    balances[msg.sender] += amount; // State update after callback
}

Detection: Identify all token transfer/transferFrom/safeTransfer calls. Check if the token could be ERC-777/ERC-1155/ERC-721. Verify state updates happen before the transfer.

Three-Phase Detection Architecture

Phase 1: Call Graph Construction

Build a complete map of all external interactions.

For each function, extract:

Function: withdraw()
├── External Calls:
│   ├── msg.sender.call{value: amount}("") at line 45
│   ├── token.transfer(user, amount) at line 48
│   └── oracle.getPrice() at line 42
├── State Writes:
│   ├── balances[msg.sender] -= amount at line 50
│   └── totalWithdrawn += amount at line 51
├── State Reads (in requires):
│   └── balances[msg.sender] at line 41
└── Modifiers:
    └── nonReentrant: NO

Call Classification:

Call TypeReentrancy RiskExamples
ETH transfer via callHIGHaddr.call{value: x}("")
Token transfer/transferFromMEDIUM-HIGHERC-777 hooks, ERC-1155 callbacks
safeTransferFrom (NFT)MEDIUMERC-721 onERC721Received callback
Cross-contract function callMEDIUMotherContract.doSomething()
staticcall / view callsLOWCannot modify state but can trigger read-only reentrancy in callers
delegatecallHIGHExecutes in caller's context

Phase 2: CEI Violation Detection

For each function with external calls, verify CEI ordering.

Algorithm:

For each function F with external calls:
  1. E = set of all state variables written by F
  2. C = set of all state variables read in require/if checks
  3. I = position of each external call in F
  4. For each external call at position P:
     a. W_after = state writes that occur AFTER position P
     b. If W_after ∩ (E ∪ C) ≠ ∅:
        → CEI VIOLATION: state modified after external call
     c. Classify violation:
        - W_after ∩ C ≠ ∅ → Classic reentrancy (check variable modified after call)
        - W_after ∩ E ≠ ∅ → State inconsistency window

Cross-Function Extension:

For each external call in function F at position P:
  W_before = state variables NOT yet updated at position P
  For each OTHER public function G:
    R_G = state variables read by G
    W_G = state variables written by G
    If R_G ∩ W_before ≠ ∅ OR W_G ∩ W_before ≠ ∅:
      → CROSS-FUNCTION REENTRANCY: G can be called during F's external call
         with inconsistent state

Phase 3: Guard Coverage Verification

Check that reentrancy protections are correctly applied.

Guard Types:

GuardCoverageLimitations
nonReentrant modifier (OpenZeppelin)Single contract, all functions with modifierDoes not protect cross-contract reentrancy
CEI pattern compliancePer-functionMust be verified for every function individually
transfer() / send() (2300 gas)Limits callback gasNOT safe — EIP-1884 changed gas costs; don't rely on this
Pull payment patternEliminates external calls from state changesRequires architectural change

Verification:

For each function F with CEI violations:
  1. Check if F has nonReentrant modifier → Mitigated (single-contract only)
  2. Check if ALL functions sharing state also have nonReentrant → Mitigated (cross-function)
  3. Check if cross-contract consumers are protected → Requires manual review
  4. If no guard → VULNERABLE

Workflow

Task Progress:
- [ ] Step 1: Identify all external calls in every function (ETH transfers, token calls, cross-contract)
- [ ] Step 2: Build call graph with state read/write positions relative to each call
- [ ] Step 3: Detect CEI violations (state writes after external calls)
- [ ] Step 4: Detect cross-function reentrancy (shared state across functions)
- [ ] Step 5: Detect callback vectors (ERC-777, ERC-1155, ERC-721 token interactions)
- [ ] Step 6: Detect read-only reentrancy (view functions reading stale state)
- [ ] Step 7: Verify guard coverage (nonReentrant, CEI compliance, pull patterns)
- [ ] Step 8: Score findings and generate report

Output Format

markdown
## Reentrancy Analysis Report

### Finding: [Title]

**Function:** `functionName()` at `Contract.sol:L42`
**Variant:** [Classic | Cross-Function | Cross-Contract | Read-Only | Callback]
**Severity:** [CRITICAL | HIGH | MEDIUM]
**Guard Status:** [Unguarded | Partially Guarded | Guarded]

**CEI Violation:**
  - External call at line [X]: `[call expression]`
  - State write AFTER call at line [Y]: `[state variable] = [expression]`

**Re-Entry Path:**
  1. Attacker calls `functionName()`
  2. External call triggers callback to attacker contract
  3. Attacker re-enters via `[re-entry function]`
  4. State variable `[name]` still has pre-update value
  5. [Exploit consequence]

**Impact:**
[Funds drained, state corrupted, price manipulated, etc.]

**Recommendation:**
[Specific fix — reorder state updates, add nonReentrant, use pull pattern]

Severity Classification

VariantState ModifiedFunds at RiskSeverity
Classic — ETH drainYesYesCRITICAL
Cross-function — balance manipulationYesYesCRITICAL
Cross-contract — oracle/price manipulationIndirectlyYesHIGH
Read-only — stale price in third-partyNo (view only)PossiblyHIGH
Callback — ERC-777 deposit inflationYesPossiblyHIGH
Any variant with nonReentrant on targetMitigatedNoLOW/INFO

Advanced Detection: Transitive Reentrancy

Trace reentrancy through multiple contract hops:

Contract A calls Contract B
Contract B calls Contract C
Contract C calls back to Contract A (or reads A's stale state)

Detection: Build transitive call graph across all contracts in scope.
For each call chain A → B → ... → X:
  If X can call back to any contract in the chain → TRANSITIVE REENTRANCY

Quick Detection Checklist

When analyzing a contract, immediately check:

  • Does any function make an external call (ETH transfer, token transfer, cross-contract) BEFORE completing all state updates?
  • Are there multiple public functions that modify the same state variables, where at least one makes an external call?
  • Does the contract interact with ERC-777, ERC-1155, or ERC-721 tokens (callback hooks)?
  • Do view functions read state that is only partially updated during an external call?
  • Is nonReentrant applied to ALL functions that share state with a function making external calls, not just the calling function itself?
  • Does the contract rely on transfer() or send() for reentrancy protection? (Unsafe assumption)

For detailed variant taxonomy, see {baseDir}/references/reentrancy-variants.md. For real-world case studies, see {baseDir}/references/case-studies.md.

Rationalizations to Reject

  • "We use transfer() so reentrancy is impossible" → EIP-1884 changed gas costs; transfer is no longer considered safe
  • "The function has nonReentrant" → Check cross-function and cross-contract paths; one modifier doesn't protect everything
  • "It's just a view function" → Read-only reentrancy can manipulate prices and oracles in third-party contracts
  • "We only interact with standard ERC20 tokens" → ERC-777 is backward-compatible with ERC20; token type may change
  • "The external call is to a trusted contract" → Trust boundaries shift; verify the actual code path through all intermediaries
  • "State is updated right after the call" → "Right after" is too late; the call already happened

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Reentrancy Pattern Analysis AI 技能有什么作用?

系统地检测智能合约中的各种重入漏洞,包括经典重入、跨函数重入、跨合约重入和只读重入。构建调用图,验证是否遵循 CEI(检查-效果-交互)模式,追踪外部调用前后的状态变化,并识别通过 ERC-777/ERC-1155 钩子实现的回调攻击路径。审计会发起外部调用、转移 ETH 或 Token、与支持回调的标准交互,或采用复杂多合约架构的合约时使用。

为什么在 TypingMind 中使用 Reentrancy Pattern Analysis?

因为您只需安装一次,就能搭配任何模型使用。Reentrancy Pattern Analysis 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Reentrancy Pattern Analysis?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/quillai-network/quillshield_skills/tree/main/plugins/reentrancy-pattern-analysis/skills/reentrancy-pattern-analysis。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Reentrancy Pattern Analysis?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Reentrancy Pattern Analysis 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Reentrancy Pattern Analysis 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Reentrancy Pattern Analysis AI 技能免费吗?

是的。quillai-network 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇