42 lines
1.2 KiB
Markdown
42 lines
1.2 KiB
Markdown
---
|
||
title: "Checks-Effects-Interactions"
|
||
type: concept
|
||
tags: [smart-contract, pattern, security]
|
||
sources: [blockchain-security-auditor]
|
||
last_updated: 2026-04-20
|
||
---
|
||
|
||
## Definition
|
||
Checks-Effects-Interactions(检查-效果-交互)是一种智能合约安全设计模式,通过在执行外部调用前完成所有状态更新来防止重入攻击。
|
||
|
||
## Pattern
|
||
```solidity
|
||
function withdraw() external nonReentrant {
|
||
// 1. CHECKS: 验证条件
|
||
uint256 amount = balances[msg.sender];
|
||
require(amount > 0, "No balance");
|
||
|
||
// 2. EFFECTS: 更新状态
|
||
balances[msg.sender] = 0;
|
||
|
||
// 3. INTERACTIONS: 执行外部调用
|
||
(bool success,) = msg.sender.call{value: amount}("");
|
||
require(success, "Transfer failed");
|
||
}
|
||
```
|
||
|
||
## Why It Works
|
||
1. 状态在外部调用前已更新
|
||
2. 攻击者重入时检查失败
|
||
3. 即使外部调用失败,状态也不会不一致
|
||
|
||
## Limitations
|
||
- 复杂业务逻辑可能无法严格遵循
|
||
- 需要配合 ReentrancyGuard 作为额外防护
|
||
- 异步操作(如 event emission)应在交互后执行
|
||
|
||
## Connections
|
||
- [[Reentrancy]] ← prevents ← [[Checks-Effects-Interactions]]
|
||
- [[Smart Contract Pattern]] ← is_type_of ← [[Checks-Effects-Interactions]]
|
||
|