Распространённые уязвимости (повторный вход и другие)
Разберитесь в распространённых уязвимостях смарт-контрактов и способах их устранения, включая повторный вход, переполнение и потерю значимости целых чисел, а также атаки с опережением.
«Распространённые уязвимости (повторный вход и другие)» — бесплатный урок Blockchain Smart Contracts with Solidity на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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!
Изучай Blockchain Smart Contracts with Solidity с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 12
- Уроки
- 48
Часто задаваемые вопросы
Урок «Распространённые уязвимости (повторный вход и другие)» бесплатный?
Да — полный текст урока «Распространённые уязвимости (повторный вход и другие)» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Blockchain Smart Contracts with Solidity, подпишись на CoddyKit PRO. Курс Blockchain Smart Contracts with Solidity содержит 4 уроков всего.
Чему я научусь в уроке «Распространённые уязвимости (повторный вход и другие)»?
Разберитесь в распространённых уязвимостях смарт-контрактов и способах их устранения, включая повторный вход, переполнение и потерю значимости целых чисел, а также атаки с опережением. Ты практикуешь Blockchain Smart Contracts with Solidity с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Blockchain Smart Contracts with Solidity?
Предыдущий опыт не требуется. Blockchain Smart Contracts with Solidity на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Распространённые уязвимости (повторный вход и другие)»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Blockchain Smart Contracts with Solidity?
Да. Каждый урок Blockchain Smart Contracts with Solidity включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Распространённые уязвимости (повторный вход и другие)
- Шаблоны управления доступом
- Безопасное программирование с SafeMath
- Аудит, тестирование и программы поиска ошибок