Web3 & DApp Development Fundamentals · 课时

合约安全最佳实践

探索智能合约开发的关键安全实践,包括重入保护、检查-效果-交互模式和访问控制。

第 2 / 3 课11 个步骤

合约安全最佳实践 是 CoddyKit 上的免费 Web3 & DApp Development Fundamentals 课时。 这是第 2 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web3 & DApp Development Fundamentals 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web3 & DApp Development Fundamentals 课程共包含 3 节课。

本课时的部分内容尚未翻译,以英文显示。

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., require statements, 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, ...) and require(!_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 onlyOwner modifier 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 onlyOwner modifiers.

These practices are crucial for building robust and trustworthy decentralized applications. Keep practicing and stay vigilant!

免费开始

用 AI 导师学习 Web3 & DApp Development Fundamentals — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
29
课程
105

常见问题解答

「合约安全最佳实践」课时是免费的吗?

是的 — 「合约安全最佳实践」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web3 & DApp Development Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Web3 & DApp Development Fundamentals 课程共包含 3 节课。

「合约安全最佳实践」这节课中我会学到什么?

探索智能合约开发的关键安全实践,包括重入保护、检查-效果-交互模式和访问控制。 你通过在浏览器中直接运行的动手代码来练习 Web3 & DApp Development Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web3 & DApp Development Fundamentals 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web3 & DApp Development Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。

「合约安全最佳实践」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web3 & DApp Development Fundamentals 课中编写并运行代码吗?

能。每节 Web3 & DApp Development Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. ERC 标准(ERC-20、ERC-721)
  2. 合约安全最佳实践
  3. 可升级合约
← 返回 Web3 & DApp Development Fundamentals