البرمجة الآمنة باستخدام SafeMath
تعلّم استخدام مكتبات مثل SafeMath لمنع هجمات تجاوز الأعداد الصحيحة ونقصانها في العمليات الحسابية.
البرمجة الآمنة باستخدام SafeMath درس مجاني في Blockchain Smart Contracts with Solidity على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Blockchain Smart Contracts with Solidity، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Blockchain Smart Contracts with Solidity 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
The Integer Problem
In Solidity, integer types like uint256 have a fixed size. This means they can only store numbers up to a certain maximum value and down to a minimum (usually 0 for unsigned integers).
When an arithmetic operation exceeds these limits, it can lead to critical vulnerabilities called integer overflows and underflows.
Unchecked Math Dangers
Solidity's default arithmetic operations (+, -, *, /) do not automatically check for overflows or underflows. Instead, the number 'wraps around'.
This behavior can be exploited by attackers, leading to incorrect token balances, unexpected contract state, and financial losses.
Overflow in Action
Consider a uint8 variable, which can hold values from 0 to 255. What happens if we try to add 1 to 255? Run this code and call incrementUnsafely(). You'll see the value reset to 0!
/*
This contract demonstrates an integer overflow.
A uint8 can only hold values from 0 to 255.
Adding 1 to 255 will cause it to wrap around to 0.
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract UnsafeCounter {
uint8 public count = 255; // Max value for uint8
// Function to increment the counter unsafely
function incrementUnsafely() public {
count = count + 1;
}
}Underflow Example
Similarly, an underflow occurs when a number goes below its minimum value. For a uint (unsigned integer), the minimum is 0.
If you subtract 1 from 0, it wraps around to the maximum value (255 for uint8, or 2^256 - 1 for uint256).
/*
This contract demonstrates an integer underflow.
A uint8 can only hold values from 0 to 255.
Subtracting 1 from 0 will cause it to wrap around to 255.
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract UnderflowDemo {
uint8 public value = 0; // Min value for uint8
// Function to decrement the value unsafely
function decrementUnsafely() public {
value = value - 1;
}
}Introducing SafeMath
To prevent these critical errors, we use libraries like SafeMath. SafeMath provides functions for arithmetic operations (addition, subtraction, multiplication, division) that revert the transaction if an overflow or underflow would occur.
This ensures your contract's state remains consistent and secure, preventing malicious exploits.
Solidity Libraries Explained
A Solidity Library is a special type of contract that contains reusable code. Unlike regular contracts, libraries are stateless (they don't store data directly) and cannot hold Ether.
- They are deployed once and their functions are called via
DELEGATECALL. - This means the library's code runs in the context of the calling contract.
- Libraries are perfect for shared utility functions like SafeMath.
Integrating SafeMath
To use SafeMath, you typically import it from a trusted source like OpenZeppelin. Then, you tell Solidity to apply SafeMath's functions to a specific integer type using the using A for B; directive.
This makes SafeMath's functions available as member functions on type B.
/*
This contract demonstrates how to integrate and use SafeMath.
We're including a simplified mock SafeMath library for demonstration.
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// A simplified mock SafeMath library for demonstration
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
}
contract MySafeContract {
// Use SafeMath functions for all uint256 variables
using SafeMath for uint256;
uint256 public balance = 100;
function deposit(uint256 amount) public {
// Now you can call .add() directly on balance
balance = balance.add(amount);
}
function getBalance() public view returns (uint256) {
return balance;
}
}Safe Addition in Action
With SafeMath integrated, you use .add() instead of the standard + operator. If the addition would overflow, the transaction will revert, preventing incorrect state changes.
Call safeAdd() with a value like 10. Try calling it with a value that would cause an overflow (e.g., if total was max uint8 and you added 1).
/*
This contract uses SafeMath for secure addition.
If the addition causes an overflow, the transaction will revert.
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
}
contract SafeAdder {
using SafeMath for uint256;
uint256 public total = 0;
function safeAdd(uint256 _value) public {
total = total.add(_value); // Uses SafeMath.add
}
}Safe Subtraction in Action
Similarly, use .sub() for subtraction. This prevents underflows, ensuring that a subtraction operation will revert if the result would be negative (below zero for unsigned integers).
Call safeSubtract() with a value like 10. Try calling it with a value larger than balance (e.g., 101) to see it revert.
/*
This contract uses SafeMath for secure subtraction.
If the subtraction causes an underflow, the transaction will revert.
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction underflow");
uint256 c = a - b;
return c;
}
}
contract SafeSubtractor {
using SafeMath for uint256;
uint256 public balance = 100;
function safeSubtract(uint256 _value) public {
balance = balance.sub(_value); // Uses SafeMath.sub
}
}Multiply, Divide, Modulo
SafeMath also provides .mul(), .div(), and .mod() for multiplication, division, and modulo operations, respectively.
.mul()checks for overflow..div()checks for division by zero and overflow..mod()checks for division by zero.
Always use these safe versions for critical arithmetic in your contracts.
Quick Check on SafeMath
You've learned about the importance of SafeMath. Let's test your understanding.
Recap: Secure Math
You've learned about the critical vulnerabilities of integer overflows and underflows in Solidity and how SafeMath provides a robust solution.
- Always use SafeMath (or similar audited libraries) for arithmetic operations on unsigned integers in your smart contracts.
- This prevents unexpected behavior and protects your contract's integrity.
Keep practicing secure coding! The next lessons will dive deeper into advanced security patterns.
الأسئلة الشائعة
هل درس «البرمجة الآمنة باستخدام SafeMath» مجاني؟
نعم — نص درس «البرمجة الآمنة باستخدام SafeMath» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Blockchain Smart Contracts with Solidity، انتقل إلى CoddyKit PRO. تتضمن دورة Blockchain Smart Contracts with Solidity 4 دروس في المجموع.
ماذا ستتعلم في «البرمجة الآمنة باستخدام SafeMath»؟
تعلّم استخدام مكتبات مثل SafeMath لمنع هجمات تجاوز الأعداد الصحيحة ونقصانها في العمليات الحسابية. تتمرن على Blockchain Smart Contracts with Solidity مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Blockchain Smart Contracts with Solidity؟
لا تُشترط خبرة سابقة. Blockchain Smart Contracts with Solidity على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.
كم من الوقت يستغرق درس «البرمجة الآمنة باستخدام SafeMath»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Blockchain Smart Contracts with Solidity هذا؟
نعم. كل درس في Blockchain Smart Contracts with Solidity يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- الثغرات الشائعة (إعادة الدخول وغيرها)
- أنماط التحكم في الوصول
- البرمجة الآمنة باستخدام SafeMath
- التدقيق والاختبار ومكافآت اكتشاف الأخطاء