0Pricing
Web3 & DApp Development Fundamentals · درس

الثغرات الشائعة في العقود الذكية

افحص العيوب الأمنية الشائعة في العقود الذكية، مثل إعادة الدخول وتجاوز سعة الأعداد الصحيحة ونقص سعتها ومشكلات التحكم في الوصول

الثغرات الشائعة في العقود الذكية درس مجاني في Web3 & DApp Development Fundamentals على CoddyKit. هذا هو الدرس 1 من أصل 3. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Web3 & DApp Development Fundamentals، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Web3 & DApp Development Fundamentals 3 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Why Security Matters

Smart contracts manage valuable assets and execute irreversible actions on the blockchain. A single vulnerability can lead to significant financial losses or unauthorized contract manipulation.

Unlike traditional software, deployed smart contracts are often immutable. This means that once a contract is live, fixing bugs or vulnerabilities can be extremely challenging, sometimes requiring complex upgrade mechanisms or even redeployment.

Reentrancy Explained

Reentrancy is a critical vulnerability where an external call from your contract to another contract or an external address can 're-enter' the calling contract before its original function call has completed its execution.

This allows an attacker to repeatedly execute certain parts of a function, often leading to unauthorized fund withdrawals or state manipulation, draining the contract's balance.

Vulnerable Reentrancy Example

In this example, the withdraw function first sends Ether (an external call) and then updates the user's balance. An attacker could re-enter withdraw multiple times before their balance is set to zero.

pragma solidity ^0.8.0;

contract VulnerableWithdraw {
    mapping(address => uint) public balances;

    constructor() payable {
        balances[msg.sender] = msg.value;
    }

    function withdraw() public {
        uint amount = balances[msg.sender];
        require(amount > 0, "No funds to withdraw");

        // Vulnerable: External call BEFORE state update
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Transfer failed");

        balances[msg.sender] = 0; // State updated AFTER call
    }

    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }

    function getBalance() public view returns (uint) {
        return address(this).balance;
    }
}

Preventing Reentrancy

The most effective defense against reentrancy is the Checks-Effects-Interactions pattern. This pattern dictates the order of operations within your functions:

  • Checks: Verify all conditions (e.g., require statements).
  • Effects: Make all necessary state changes (e.g., update balances, modify variables).
  • Interactions: Perform any external calls (e.g., sending Ether, calling another contract).

Always update the contract's state *before* sending Ether or calling external contracts.

Secure Withdrawal Function

Here's the corrected withdraw function. Notice how the user's balance is updated (an 'effect') *before* the Ether is sent (an 'interaction').

pragma solidity ^0.8.0;

contract SecureWithdraw {
    mapping(address => uint) public balances;

    constructor() payable {
        balances[msg.sender] = msg.value;
    }

    function withdraw() public {
        uint amount = balances[msg.sender];
        require(amount > 0, "No funds to withdraw");

        balances[msg.sender] = 0; // Effect: State updated BEFORE call

        (bool success, ) = msg.sender.call{value: amount}(""); // Interaction
        require(success, "Transfer failed");
    }

    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }

    function getBalance() public view returns (uint) {
        return address(this).balance;
    }
}

Integer Overflow & Underflow

Integer types in Solidity (like uint or int) have a fixed size. An overflow occurs when an arithmetic operation results in a value larger than the maximum an integer type can hold, causing it to 'wrap around' to its minimum value (e.g., 255 + 1 on a uint8 becomes 0).

An underflow occurs when an operation results in a value smaller than the minimum (usually 0 for uint), causing it to wrap around to its maximum value (e.g., 0 - 1 on a uint8 becomes 255).

Vulnerable Integer Logic

Before Solidity 0.8.0, these wrap-around behaviors were not automatically checked. This example, using an older Solidity version, shows how an attacker could exploit an underflow to gain a massive balance.

pragma solidity ^0.7.0; // Using 0.7.x to demonstrate vulnerability

contract VulnerableCounter {
    uint public count = 0;

    // If count is 0 and _amount is 1, count becomes type(uint).max
    function decrement(uint _amount) public {
        count -= _amount; // Vulnerable to underflow
    }

    // If count + _amount exceeds type(uint).max, count wraps around to a small number
    function increment(uint _amount) public {
        count += _amount; // Vulnerable to overflow
    }
}

Mitigating Overflow/Underflow

Since Solidity 0.8.0, arithmetic operations automatically revert (fail) on overflow or underflow. This provides robust protection against these issues by default, making your contracts much safer.

For contracts written in older Solidity versions (pre-0.8.0), it was common to use libraries like OpenZeppelin's SafeMath. SafeMath provided functions (add, sub, mul, div) that performed checked arithmetic, reverting if an overflow or underflow would occur.

Access Control Issues

Access control ensures that only authorized users or roles can perform specific, sensitive actions within a smart contract. Incorrect access control is a very common source of vulnerabilities.

Common mistakes include:

  • Missing authorization checks for critical functions (e.g., administrative functions).
  • Using msg.sender directly without verifying ownership or role.
  • Weak or easily guessable authorization mechanisms.

Vulnerable Access Control

In this example, the setCriticalValue function is intended to be for the contract owner only, but it lacks any check to enforce this. Any user could call this function and change the critical value.

The onlyOwner modifier shows the correct way to restrict access.

pragma solidity ^0.8.0;

contract VulnerableAccess {
    address public owner;
    uint public criticalValue;

    constructor() {
        owner = msg.sender;
        criticalValue = 100;
    }

    // Vulnerable: This function should be owner-only, but it's public!
    function setCriticalValue(uint _newValue) public {
        criticalValue = _newValue; // Anyone can call this!
    }

    // Correct way to restrict access using a modifier
    function setCriticalValueSecure(uint _newValue) public onlyOwner {
        criticalValue = _newValue;
    }

    modifier onlyOwner() {
        require(msg.sender == owner, "Not owner");
        _;
    }
}

Vulnerability Check

Which of the following patterns is designed to prevent reentrancy attacks by ensuring state changes occur before external calls?

Recap: Secure Smart Contracts

Today, we've covered some of the most common and critical smart contract vulnerabilities:

  • Reentrancy: Prevented by following the Checks-Effects-Interactions pattern.
  • Integer Overflow/Underflow: Mitigated by using Solidity 0.8.0+ (automatic checks) or SafeMath for older versions.
  • Access Control Issues: Secured by implementing proper authorization checks using modifiers like onlyOwner.

Always prioritize security in your smart contract development. Thoroughly auditing your code and adhering to best practices are essential steps to protect assets and ensure the reliability of your decentralized applications.

الأسئلة الشائعة

هل درس «الثغرات الشائعة في العقود الذكية» مجاني؟

نعم — نص درس «الثغرات الشائعة في العقود الذكية» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Web3 & DApp Development Fundamentals، انتقل إلى CoddyKit PRO. تتضمن دورة Web3 & DApp Development Fundamentals 3 دروس في المجموع.

ماذا ستتعلم في «الثغرات الشائعة في العقود الذكية»؟

افحص العيوب الأمنية الشائعة في العقود الذكية، مثل إعادة الدخول وتجاوز سعة الأعداد الصحيحة ونقص سعتها ومشكلات التحكم في الوصول تتمرن على Web3 & DApp Development Fundamentals مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Web3 & DApp Development Fundamentals؟

لا تُشترط خبرة سابقة. Web3 & DApp Development Fundamentals على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 3.

كم من الوقت يستغرق درس «الثغرات الشائعة في العقود الذكية»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Web3 & DApp Development Fundamentals هذا؟

نعم. كل درس في Web3 & DApp Development Fundamentals يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. الثغرات الشائعة في العقود الذكية
  2. أدوات الأمان وعمليات التدقيق
  3. تقنيات تحسين استهلاك Gas
← العودة إلى Web3 & DApp Development Fundamentals