Bonnes pratiques de sécurité des contrats
Découvrez les pratiques de sécurité essentielles pour développer des contrats intelligents, notamment les protections contre la réentrance, le modèle vérifications-effets-interactions et le contrôle d’accès.
Bonnes pratiques de sécurité des contrats est une leçon Web3 & DApp Development Fundamentals gratuite sur CoddyKit. Ceci est la leçon 2 sur 3. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Web3 & DApp Development Fundamentals, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Web3 & DApp Development Fundamentals comprend 3 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
Smart Contract Security Intro
Welcome to the critical world of smart contract security! Unlike traditional software, bugs in smart contracts can lead to irreversible loss of funds.
Because smart contracts are immutable once deployed, fixing vulnerabilities is extremely difficult, often requiring complex upgrade mechanisms or even redeploying a new contract.
In this lesson, we'll explore essential practices to build more secure and robust smart contracts.
Understanding Reentrancy
One of the most infamous vulnerabilities is reentrancy. It occurs when an external call to another contract or address "re-enters" the calling contract before the initial function's state updates are complete.
Imagine a bank ATM that lets you withdraw money. If it debits your account *after* giving you cash, a reentrancy attack would be like repeatedly asking for cash before the system updates your balance, draining the ATM.
Vulnerable Withdrawal Code
Consider this simplified contract where a user can deposit and withdraw Ether. Can you spot the danger?
The withdraw() function first sends Ether, then updates the balance. An attacker can call withdraw() again from their malicious contract during the external call, before their balance is set to zero.
/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VulnerableBank {
mapping(address => uint) public balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw(uint _amount) public {
require(balances[msg.sender] >= _amount, "Insufficient balance");
// Vulnerable point: send Ether BEFORE updating balance
(bool success, ) = msg.sender.call{value: _amount}("");
require(success, "Failed to send Ether");
balances[msg.sender] -= _amount; // This happens AFTER the external call
}
function getBalance() public view returns (uint) {
return address(this).balance;
}
}Preventing Reentrancy: State Locks
A common and effective way to prevent reentrancy is using a reentrancy guard. This involves locking the state of the contract during an external call and unlocking it afterward.
If a re-entrant call tries to execute the locked function, it will revert. OpenZeppelin's ReentrancyGuard is a popular implementation, but you can also build a simple one.
Implementing Reentrancy Guard
Let's add a simple reentrancy guard using a boolean flag. This ensures that the withdraw function cannot be called again until the current execution is complete and the state has been updated.
The nonReentrant modifier sets a lock, performs the operation, and then releases the lock.
/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SecureBank {
mapping(address => uint) public balances;
bool private _locked; // Reentrancy guard flag
modifier nonReentrant() {
require(!_locked, "Reentrant call detected");
_locked = true;
_;
_locked = false;
}
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw(uint _amount) public nonReentrant {
require(balances[msg.sender] >= _amount, "Insufficient balance");
balances[msg.sender] -= _amount; // Update balance BEFORE external call (CEI)
(bool success, ) = msg.sender.call{value: _amount}("");
require(success, "Failed to send Ether");
}
function getBalance() public view returns (uint) {
return address(this).balance;
}
}The CEI Pattern
The Checks-Effects-Interactions (CEI) pattern is a fundamental security best practice. It dictates a specific order for operations within a function:
- Checks: Validate conditions (e.g.,
requirestatements,onlyOwner). - Effects: Update the contract's state (e.g.,
balances[msg.sender] -= amount). - Interactions: Perform external calls to other contracts or addresses.
Following CEI helps prevent various attacks, including reentrancy, by ensuring your contract's state is finalized *before* external calls.
CEI in Withdrawal Function
Notice how our SecureBank's withdraw function already follows the CEI pattern:
- Checks:
require(balances[msg.sender] >= _amount, ...)andrequire(!_locked, ...)from the modifier. - Effects:
balances[msg.sender] -= _amount;updates the state. - Interactions:
msg.sender.call{value: _amount}("");performs the external transfer.
This order is crucial for preventing reentrancy and ensuring consistent state.
/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract CEIDemo {
mapping(address => uint) public balances;
bool private _locked;
modifier nonReentrant() {
require(!_locked, "Reentrant call detected");
_locked = true;
_;
_locked = false;
}
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw(uint _amount) public nonReentrant {
// --- CHECKS ---
require(balances[msg.sender] >= _amount, "Insufficient balance");
// --- EFFECTS ---
balances[msg.sender] -= _amount; // State updated BEFORE external call
// --- INTERACTIONS ---
(bool success, ) = msg.sender.call{value: _amount}("");
require(success, "Failed to send Ether");
}
}Restricting Access
Not all functions in a smart contract should be callable by everyone. Access control ensures that only authorized addresses or roles can execute specific sensitive operations.
Common examples include:
- An
onlyOwnermodifier for administrative functions. - Role-based access control (RBAC) where different roles (e.g.,
MINTER,PAUSER) have specific permissions.
Proper access control is vital to prevent unauthorized actions and maintain contract integrity.
Owner-Restricted Function
Here's how to implement a simple onlyOwner access control using a modifier. The contract stores the deployer's address as the owner, and only this address can call the setNewAdmin function.
This pattern is widely used for critical administrative functions.
/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract AccessControlled {
address public owner;
address public admin;
constructor() {
owner = msg.sender; // Deployer is the owner
admin = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "Only owner can call this function");
_;
}
function setNewAdmin(address _newAdmin) public onlyOwner {
admin = _newAdmin;
}
function getAdmin() public view returns (address) {
return admin;
}
}Security Best Practices Check
You've learned about reentrancy, the CEI pattern, and access control. Which of the following statements are true regarding secure smart contract development?
Recap: Secure Contracts
Great job! You've grasped fundamental smart contract security practices:
- Reentrancy: A critical vulnerability where external calls can "re-enter" a function before state updates.
- Reentrancy Guards: Mechanisms (like mutexes or modifiers) to lock contract state during external calls.
- CEI Pattern: The recommended order of operations (Checks, Effects, Interactions) to ensure state is updated before external calls.
- Access Control: Restricting sensitive functions to authorized addresses, often using
onlyOwnermodifiers.
These practices are crucial for building robust and trustworthy decentralized applications. Keep practicing and stay vigilant!
Questions Fréquemment Posées
La leçon « Bonnes pratiques de sécurité des contrats » est-elle gratuite ?
Oui — le texte complet de « Bonnes pratiques de sécurité des contrats » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Web3 & DApp Development Fundamentals, passe à CoddyKit PRO. Le cours Web3 & DApp Development Fundamentals comprend 3 leçons au total.
Qu'est-ce que j'apprendrai dans « Bonnes pratiques de sécurité des contrats » ?
Découvrez les pratiques de sécurité essentielles pour développer des contrats intelligents, notamment les protections contre la réentrance, le modèle vérifications-effets-interactions et le contrôle… Tu pratiques Web3 & DApp Development Fundamentals avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Web3 & DApp Development Fundamentals ?
Aucune expérience préalable n'est requise. Web3 & DApp Development Fundamentals sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 3.
Combien de temps prend la leçon « Bonnes pratiques de sécurité des contrats » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Web3 & DApp Development Fundamentals ?
Oui. Chaque leçon Web3 & DApp Development Fundamentals inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Normes ERC (ERC-20, ERC-721)
- Bonnes pratiques de sécurité des contrats
- Contrats évolutifs