常见漏洞(重入等)
了解并缓解常见的智能合约漏洞,例如重入攻击、整数溢出与下溢,以及抢先交易攻击。
常见漏洞(重入等) 是 CoddyKit 上的免费 Blockchain Smart Contracts with Solidity 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Blockchain Smart Contracts with Solidity 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Blockchain Smart Contracts with Solidity 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Smart Contract Security: Overview
Welcome to this crucial lesson on smart contract security! Unlike traditional software, bugs in smart contracts can lead to irreversible loss of funds.
Because contracts on the blockchain are often immutable, fixing vulnerabilities after deployment is incredibly difficult, if not impossible. Security must be a top priority from day one.
Understanding Reentrancy Attacks
Reentrancy is a critical vulnerability where an external call to an untrusted contract can 're-enter' the original contract before the first function call has completed its execution.
This allows the attacker to repeatedly drain funds or manipulate state by calling the vulnerable function multiple times.
Reentrancy: A Vulnerable Example
Consider this simplified withdrawal contract. Can you spot the potential issue?
The state (balances[msg.sender]) is updated *after* the external call to msg.sender.call. This delay creates a window for attack.
pragma solidity ^0.8.0;
contract VulnerableWithdraw {
mapping(address => uint) public balances;
constructor() payable {
// Fund contract for demo purposes
}
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw(uint _amount) public {
require(balances[msg.sender] >= _amount, "Insufficient balance");
// External call FIRST, state update LATER
(bool success, ) = msg.sender.call{value: _amount}("");
require(success, "Transfer failed");
balances[msg.sender] -= _amount; // This line is vulnerable!
}
function getBalance() public view returns (uint) {
return address(this).balance;
}
}The Reentrancy Attack Flow
Here's how an attacker exploits the previous contract:
- 1. Deposit: Attacker deposits funds into
VulnerableWithdraw. - 2. Withdraw: Attacker calls
withdraw(amount). - 3. Re-enter: When
msg.sender.calltransfers Ether to the attacker, their malicious fallback function is triggered. - 4. Repeat: The fallback function immediately calls
withdraw(amount)again, before the original call updates the balance. This repeats until funds are drained.
Mitigating Reentrancy: The Fix
The most effective way to prevent reentrancy is to follow the Checks-Effects-Interactions (CEI) pattern:
- 1. Checks: Verify all conditions (e.g.,
requirestatements). - 2. Effects: Update all state variables (e.g.,
balances[msg.sender] -= _amount). - 3. Interactions: Make external calls (e.g.,
msg.sender.call).
This ensures state is updated *before* any untrusted external code can execute.
Reentrancy: The Fixed Contract
Here's the corrected version of the withdrawal contract, applying the CEI pattern. Notice the order of operations.
Now, the balance is decremented *before* the external call, closing the reentrancy window.
pragma solidity ^0.8.0;
contract SafeWithdraw {
mapping(address => uint) public balances;
constructor() payable {
// Fund contract for demo purposes
}
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw(uint _amount) public {
// 1. Checks
require(balances[msg.sender] >= _amount, "Insufficient balance");
// 2. Effects: Update state BEFORE external call
balances[msg.sender] -= _amount;
// 3. Interactions: Make external call LAST
(bool success, ) = msg.sender.call{value: _amount}("");
require(success, "Transfer failed");
}
function getBalance() public view returns (uint) {
return address(this).balance;
}
}Integer Overflows & Underflows
Integer overflows occur when an arithmetic operation results in a value larger than the maximum that the variable type can hold. It 'wraps around' to its minimum value.
Integer underflows are the opposite: when a result is smaller than the minimum value, wrapping around to the maximum.
For example, a uint8 can hold values from 0 to 255. If it's 255 and you add 1, it becomes 0 (overflow). If it's 0 and you subtract 1, it becomes 255 (underflow).
Overflow/Underflow Example
Prior to Solidity 0.8.0, these operations would silently wrap around. Since Solidity 0.8.0, arithmetic operations default to checking for overflows/underflows and will revert if one occurs.
However, understanding the concept is vital, especially when working with older codebases or using unchecked blocks for gas optimization.
pragma solidity ^0.8.0;
contract MathVulnerabilities {
uint8 public smallNumber = 255; // Max for uint8
function triggerOverflow() public {
// In Solidity 0.8.0+, this transaction will revert.
// In older versions, smallNumber would become 0.
smallNumber = smallNumber + 1;
}
function triggerUnderflow() public {
smallNumber = 0; // Reset for demo
// In Solidity 0.8.0+, this transaction will revert.
// In older versions, smallNumber would become 255.
smallNumber = smallNumber - 1;
}
}Front-Running Attacks
Front-running is an attack where a malicious actor observes a pending transaction and submits their own transaction with a higher gas fee to have it executed first.
This is common in DeFi (Decentralized Finance) where transactions like large swaps or liquidations can be anticipated and exploited for profit.
Mitigating Front-Running
Preventing front-running is challenging due to the public nature of the mempool (pending transaction pool). However, some strategies exist:
- Commit-Reveal Schemes: Users submit a hashed version of their intent (commit), then later reveal the actual data.
- Batching: Grouping transactions together to reduce individual transaction visibility.
- Decentralized Sequencers/L2s: Using solutions that offer more private or controlled transaction ordering.
- Slippage Control: Users setting maximum acceptable price slippage for swaps.
Vulnerability Check
You've learned about three major smart contract vulnerabilities. Let's test your understanding!
Recap: Security First
In this lesson, we explored critical smart contract vulnerabilities: reentrancy, integer overflows/underflows, and front-running.
- We saw how reentrancy exploits external calls and how the Checks-Effects-Interactions pattern provides a robust defense.
- We understood how integer arithmetic can lead to unexpected values and the importance of compiler checks (Solidity 0.8.0+).
- Finally, we discussed front-running and methods like commit-reveal to mitigate it.
Always prioritize security in your smart contract development!
常见问题解答
「常见漏洞(重入等)」课时是免费的吗?
是的 — 「常见漏洞(重入等)」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Blockchain Smart Contracts with Solidity 课程的其余内容,请升级到 CoddyKit PRO。 Blockchain Smart Contracts with Solidity 课程共包含 4 节课。
「常见漏洞(重入等)」这节课中我会学到什么?
了解并缓解常见的智能合约漏洞,例如重入攻击、整数溢出与下溢,以及抢先交易攻击。 你通过在浏览器中直接运行的动手代码来练习 Blockchain Smart Contracts with Solidity,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Blockchain Smart Contracts with Solidity 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Blockchain Smart Contracts with Solidity 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「常见漏洞(重入等)」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Blockchain Smart Contracts with Solidity 课中编写并运行代码吗?
能。每节 Blockchain Smart Contracts with Solidity 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 常见漏洞(重入等)
- 访问控制模式
- 使用 SafeMath 进行安全编码
- 审计、测试与漏洞赏金