Логотип Reentrancy Pattern Analysis

Reentrancy Pattern Analysis

Організація
quillai-network
reentrancy-pattern-analysis

Систематично виявляє всі різновиди вразливостей повторного входу в смартконтрактах: класичний повторний вхід, між функціями, між контрактами та повторний вхід лише для читання. Будує графи викликів, перевіряє дотримання патерну CEI (Checks-Effects-Interactions), відстежує зміни стану відносно зовнішніх викликів і виявляє вектори зворотного виклику через хуки ERC-777/ERC-1155. Використовуйте під час аудиту контрактів, що здійснюють зовнішні виклики, переказують ETH або токени, взаємодіють зі стандартами з підтримкою зворотних викликів або мають складну архітектуру з кількох контрактів.

Add to TypingMind

Огляд

Видавецьquillai-network
Репозиторійquillshield_skills
Назва навичкиreentrancy-pattern-analysis
Зірки
131
Форки
28
Файли в пакеті
2
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Файлів у комплекті: 2

    Скрипти, шаблони й довідкові матеріали, які модель може читати під час роботи. Файли доступні лише для читання й ніколи не виконуються.

  • Відкритий вихідний код

    Видавець на GitHub: quillai-network. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Reentrancy Pattern Analysis у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає 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. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте 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

Увімкніть навичку Reentrancy Pattern Analysis в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Reentrancy Pattern Analysis, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Reentrancy Pattern Analysis не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл 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?

Систематично виявляє всі різновиди вразливостей повторного входу в смартконтрактах: класичний повторний вхід, між функціями, між контрактами та повторний вхід лише для читання. Будує графи викликів, перевіряє дотримання патерну CEI (Checks-Effects-Interactions), відстежує зміни стану відносно зовнішніх викликів і виявляє вектори зворотного виклику через хуки ERC-777/ERC-1155. Використовуйте під час аудиту контрактів, що здійснюють зовнішні виклики, переказують ETH або токени, взаємодіють зі стандартами з підтримкою зворотних викликів або мають складну архітектуру з кількох контрактів.

Навіщо використовувати Reentrancy Pattern Analysis у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Reentrancy Pattern Analysis — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Reentrancy Pattern Analysis у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/quillai-network/quillshield_skills/tree/main/plugins/reentrancy-pattern-analysis/skills/reentrancy-pattern-analysis. TypingMind прочитає файл SKILL.md, додасть супровідні файли та встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Reentrancy Pattern Analysis?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Reentrancy Pattern Analysis?

Зі скількома забажаєте. У TypingMind ви можете використовувати Reentrancy Pattern Analysis із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Reentrancy Pattern Analysis?

Так. На GitHub цю навичку публікує quillai-network за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі
Логотип affaan-m

Change Impact

affaan-m
СпільнотаПопулярне

Perform evidence-backed impact analysis before changing code, data, interfaces, or governance documents, then compare the planned impact with the actual diff after implementation. Covers call paths,…

41.4K
277.3K
Файлів: 1
Відкрити
Логотип affaan-m

Test Collaboration

affaan-m
СпільнотаПопулярне

Inventory and govern a project's test assets. Connect requirements, business rules, risks, bugs, and cross-boundary contracts to stable TEST-IDs and executable evidence in the repository's existing…

41.4K
277.3K
Файлів: 2
Відкрити
Логотип affaan-m

Product Capability

affaan-m
СпільнотаПопулярне

Перетворюйте задум PRD, запити щодо дорожньої карти або обговорення продукту на готовий до реалізації план можливостей, у якому визначено обмеження, інваріанти, інтерфейси та невирішені питання ще до початку роботи з кількома…

40.4K
270.2K
Файлів: 1
Відкрити
Логотип affaan-m

Django Patterns

affaan-m
СпільнотаПопулярне

Шаблони архітектури Django, проєктування REST API за допомогою DRF, найкращі практики ORM, кешування, сигнали, проміжне програмне забезпечення та створення Django-застосунків промислового рівня.

39.1K
261.1K
Інструкції
Відкрити

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇