[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,89 +2,215 @@
|
||||
id: wiki-2026-0508-smart-contract-auditing
|
||||
title: Smart Contract Auditing
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [SEC-BC-AUDIT-001]
|
||||
aliases: [Solidity Audit, Web3 Security Audit, Contract Security Review]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: ["Blockchain|[Blockchain", security, smart-contract, auditing, ethereum, solidity, cybersecurity, web3]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [security, web3, solidity, audit, ai-security]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: solidity
|
||||
framework: foundry/slither/mythril
|
||||
---
|
||||
|
||||
# Smart Contract Auditing (스마트 컨트랙트 감사)
|
||||
# Smart Contract Auditing
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "수정 불가능한 코드(Immutability)의 무게를 견디기 위해, 배포 전 단 한 점의 논리적 틈새도 허용하지 않는 철저한 검증으로 디지털 자산의 안전을 담보하라" — 블록체인상에 구현된 스마트 컨트랙트의 취약점, 버그, 논리적 결함을 분석하여 해킹 사고를 예방하는 보안 검증 공정.
|
||||
## 매 한 줄
|
||||
> **"매 smart contract audit 의 layered defense — static (Slither) + symbolic (Mythril/Manticore) + fuzz (Echidna/Foundry invariant) + formal (Certora) + AI (Claude / GPT-5 audit) + human review"**. 매 2026 의 reality 의 single tool 의 X — 매 ensemble + AI-augmented review 의 ROI 의 best. 매 SWC registry, 매 Trail of Bits 의 building security in 의 reference.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Multi-layered Vulnerability Scanning and [[Logic|Logic]]al Verification" — 자동화된 정적 분석 도구로 알려진 보안 패턴(재진입 공격, 가스 리미트 등)을 검출하고, 전문가의 수동 리뷰를 통해 비즈니스 로직의 모순을 찾아내며, 수학적 형식 검증으로 모든 경우의 수에 대한 안전성을 입증하는 패턴.
|
||||
- **주요 감사 단계:**
|
||||
- **Automated Scanning:** Slither, Mythril 등을 활용한 빠른 취약점 탐지.
|
||||
- **Manual [[Code Review|Code Review]]:** 코드의 의도와 실제 구현 사이의 괴리 분석.
|
||||
- **Economic [[Analysis|Analysis]]:** 토큰 이코노미나 거버넌스 공격 가능성 검토.
|
||||
- **Formal Verification:** 수학적 모델링을 통해 계약 조건의 완벽성 증명.
|
||||
- **의의:** DeFi, NFT 등 거대한 자본이 흐르는 Web3 생태계에서 사용자 신뢰를 얻기 위한 필수 관문이며, 코드의 실수가 돌이킬 수 없는 자산 손실로 이어지는 것을 막는 최후의 방어선.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 사람이 일일이 코드를 보던 방식에서, 이제는 AI 기반의 스마트 컨트랙트 분석기가 실시간으로 새로운 공격 패턴을 학습하고 감지하며 인간 감사자의 직관과 도구의 정밀함이 결합된 하이브리드 감사 방식으로 진화함.
|
||||
- **정책 변화:** Antigravity 프로젝트는 향후 지식 자산의 소유권이나 에이전트 간 보상 체계를 블록체인화할 경우, 배포 전 반드시 공인된 외부 감사를 거치는 'Security-First' 배포 프로토콜을 준수함.
|
||||
### 매 Tool layers
|
||||
- **Static (Slither, Aderyn)**: 매 known pattern detector — reentrancy, tx.origin, ...
|
||||
- **Symbolic (Mythril, Manticore)**: 매 path explore + SMT solver.
|
||||
- **Fuzz (Echidna, Foundry invariant)**: 매 property-based.
|
||||
- **Formal (Certora Prover, halmos)**: 매 spec proof.
|
||||
- **AI (Claude Opus 4.7, GPT-5, OpenZeppelin AI)**: 매 nuanced logic bug, NatSpec 의 intent vs code 의 mismatch.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Security-Best-Practices|Security-Best-Practices]], [[Trustworthy-AI|Trustworthy-AI]], Risk-Assessment-with-AI, Software-Architecture-Patterns
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Smart-Contract-Auditing.md
|
||||
### 매 Common vuln (SWC)
|
||||
- **Reentrancy** (SWC-107): CEI pattern, ReentrancyGuard.
|
||||
- **Integer over/underflow**: Solidity 0.8+ checked, 매 unchecked block 의 careful.
|
||||
- **Access control**: onlyOwner, role-based, 매 init function 의 protect.
|
||||
- **Oracle manipulation**: 매 single-block TWAP X, Chainlink + heartbeat.
|
||||
- **MEV / front-run**: commit-reveal, private mempool.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. **Pre-deploy audit** — 매 mainnet deploy 의 prerequisite.
|
||||
2. **CI gate** — 매 PR 의 Slither / Foundry test 의 fail 의 block.
|
||||
3. **Bug bounty** — Immunefi 등록 의 ongoing.
|
||||
4. **Upgrade audit** — UUPS / Transparent proxy 의 upgrade diff review.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### Slither CI (GitHub Actions)
|
||||
```yaml
|
||||
name: slither
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
analyze:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: crytic/slither-action@v0.4.0
|
||||
with:
|
||||
fail-on: medium
|
||||
slither-args: "--exclude-informational --filter-paths node_modules"
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Foundry invariant test
|
||||
```solidity
|
||||
// test/Invariant.t.sol
|
||||
import "forge-std/Test.sol";
|
||||
import {Vault} from "src/Vault.sol";
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
contract VaultInvariant is Test {
|
||||
Vault vault;
|
||||
address[] users;
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
function setUp() public {
|
||||
vault = new Vault();
|
||||
for (uint i; i < 5; i++) users.push(makeAddr(string(abi.encodePacked("u", i))));
|
||||
}
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
function invariant_totalShares_eq_sumBalances() public view {
|
||||
uint sum;
|
||||
for (uint i; i < users.length; i++) sum += vault.balanceOf(users[i]);
|
||||
assertEq(vault.totalSupply(), sum);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Reentrancy (CEI + Guard)
|
||||
```solidity
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
contract Pool is ReentrancyGuard {
|
||||
mapping(address => uint) public balance;
|
||||
|
||||
// BAD
|
||||
function withdrawBad() external {
|
||||
uint b = balance[msg.sender];
|
||||
(bool ok,) = msg.sender.call{value: b}(""); // 매 external before state
|
||||
require(ok);
|
||||
balance[msg.sender] = 0;
|
||||
}
|
||||
|
||||
// GOOD: CEI + nonReentrant
|
||||
function withdraw() external nonReentrant {
|
||||
uint b = balance[msg.sender];
|
||||
balance[msg.sender] = 0; // Effects
|
||||
(bool ok,) = msg.sender.call{value: b}(""); // Interaction
|
||||
require(ok, "send fail");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Echidna property test
|
||||
```solidity
|
||||
contract VaultEchidna is Vault {
|
||||
function echidna_no_negative_balance() public view returns (bool) {
|
||||
// 매 reachable balance 의 always >= 0 (uint, but check via burn)
|
||||
return totalSupply() >= 0;
|
||||
}
|
||||
|
||||
function echidna_total_eq_deposits() public view returns (bool) {
|
||||
return address(this).balance == totalDeposited;
|
||||
}
|
||||
}
|
||||
// echidna . --contract VaultEchidna --test-mode property
|
||||
```
|
||||
|
||||
### AI audit (Claude 4.7)
|
||||
```python
|
||||
import anthropic
|
||||
client = anthropic.Anthropic()
|
||||
|
||||
def ai_audit(contract_src: str) -> str:
|
||||
msg = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=4000,
|
||||
system="""You are a senior smart contract auditor. Review for:
|
||||
1. Reentrancy, access control, integer issues
|
||||
2. Oracle / price manipulation
|
||||
3. Logic bugs vs NatSpec intent
|
||||
4. Gas / DoS
|
||||
5. Upgrade safety
|
||||
For each finding: severity (H/M/L), location, exploit, fix.""",
|
||||
messages=[{"role": "user", "content": f"```solidity\n{contract_src}\n```"}],
|
||||
)
|
||||
return msg.content[0].text
|
||||
```
|
||||
|
||||
### Certora spec
|
||||
```
|
||||
// MyToken.spec
|
||||
methods {
|
||||
function balanceOf(address) external returns (uint) envfree;
|
||||
function totalSupply() external returns (uint) envfree;
|
||||
}
|
||||
|
||||
invariant totalSupply_eq_sum_balances()
|
||||
totalSupply() == sumOfBalances()
|
||||
{ preserved transfer(address to, uint amt) with (env e) {
|
||||
require balanceOf(e.msg.sender) >= amt;
|
||||
} }
|
||||
```
|
||||
|
||||
### Chainlink oracle (safe)
|
||||
```solidity
|
||||
import "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
|
||||
|
||||
contract PriceConsumer {
|
||||
AggregatorV3Interface immutable feed;
|
||||
uint constant STALE = 3600;
|
||||
|
||||
function price() public view returns (uint) {
|
||||
(, int answer,, uint updatedAt,) = feed.latestRoundData();
|
||||
require(answer > 0, "neg price");
|
||||
require(block.timestamp - updatedAt < STALE, "stale");
|
||||
return uint(answer);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Tool |
|
||||
|---|---|
|
||||
| CI gate | Slither + Foundry test |
|
||||
| Pre-deploy | Slither + Mythril + Echidna + AI + human |
|
||||
| High-value protocol | + Certora formal |
|
||||
| Upgrade | diff + storage layout check |
|
||||
| Bounty | Immunefi |
|
||||
|
||||
**기본값**: Slither CI + Foundry invariant + AI review + manual senior review before mainnet.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Smart-Contracts]] · [[Web3-Security]]
|
||||
- 변형: [[Slither]] · [[Mythril]] · [[Echidna]] · [[Certora]]
|
||||
- 응용: [[DeFi-Security]] · [[Bridge-Security]] · [[Oracle-Security]]
|
||||
- Adjacent: [[Foundry]] · [[OpenZeppelin]] · [[SWC-Registry]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: NatSpec vs code intent diff, logic bug, gas optimization, exploit hypothesis 의 generate.
|
||||
**언제 X**: deterministic detection (Slither faster), formal proof (Certora).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Single tool reliance**: 매 Slither alone 의 logic bug miss.
|
||||
- **No mainnet rehearsal**: 매 fork test X.
|
||||
- **Owner = EOA**: 매 multisig / timelock 의 use.
|
||||
- **Unchecked external call**: low-level call 의 return 의 ignore.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Trail of Bits, OpenZeppelin, ConsenSys Diligence).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full content with tool stack + AI audit pattern |
|
||||
|
||||
Reference in New Issue
Block a user