智能合约编写注意事项

简介: 智能合约编写注意事项

今天区块链技术圈被美链(BEC)智能合约的漏洞导致代币价值几乎归零的事件刷遍朋友圈。这篇文章就带大家了解一些智能合约编写的注意事项。

Overflow 与 Underflow

Solidity 可以处理 256 位数字, 最高为 2256 - 1, 所以对 (2 256 - 1) 加 1 会导致归 0。同理, 对 unsigned 类型 0 做减 1 运算会得到 (2**256 - 1)

测试代码如下:

  1. pragma solidity 0.4.18;
  2. contract OverflowUnderflow{
  3.    uintpublic zero =0;
  4.    uintpublic max =2**256-1;
  5.    // zero will end up at  2 ** 256 - 1
  6.    function underflow()public{
  7.        zero -=1;
  8.    }
  9.    function overflow()public{
  10.        max +=1;
  11.    }
  12. }

尽管他们同样危险, 但是在智能合约中, underflow 造成的影响更大.

比如, 账号 A 持有 X tokens, 如果他发起一笔 X + 1 tokens 的交易, 如果代码不进行校验, 则账号 A 的余额可能发生 underflow 导致余额变多.

可以引入 SafeMath Library 解决:

  1. pragma solidity 0.4.18;
  2. library SafeMath{
  3.    function mul(uint256 a, uint256 b)internal pure returns (uint256){
  4.        if(a==0){
  5.            return0;
  6.        }
  7.        uint c = a * b;
  8.        assert(c / a == b);
  9.        return c;
  10.    }
  11.    function div(uint256 a, uint256 b)internal pure returns (uint256){
  12.        uint256 c = a / b;
  13.        return c;
  14.    }
  15.    functionsub(uint256 a, uint256 b)internal pure returns (uint256){
  16.        assert(b <= a);
  17.        return a - b;
  18.    }
  19.    function add(uint256 a, uint256 b)internal pure returns (uint256){
  20.        uint256 c = a + b;
  21.        assert(c >= a);
  22.        return c;
  23.    }
  24. }
  25. contract OverflowUnderflow{
  26.    usingSafeMathforuint;
  27.    uintpublic zero =0;
  28.    uintpublic max =2**256-1;
  29.    function underflow()public{
  30.        zero = zero.sub(1);
  31.    }
  32.    function overflow()public{
  33.        max = max.add(1);
  34.    }
  35. }

Visibility 与 Delegatecall

  • Public functions 可以被任意地址调用
  • External functions 只能从合约外部调用
  • Private functions 只能从合约内部调用
  • Internal functions 允许从合约及其子合约调用

External functions 消耗的 gas 比 public 少, 因为其使用 calldata 而 Public 需要复制所有参数到 memory。

Delegatecall

Delegatecall is identical to a message call apart from the fact that the code at the target address is executed in the context of the calling contract and msg.sender and msg.value do not change their values. This means that a contract can dynamically load code from a different address at runtime. Storage, current address and balance still refer to the calling contract, only the code is taken from the called address.

这个特性可以用于构建 Library 和模块化代码. 但是与此同时, 这也有可能造成别人对你的代码进行操作。

下例中, 攻击者调用 pwn 方法获得了合约的拥有权。

  1. pragma solidity 0.4.18;
  2. contract Delegate{
  3.    address public owner;
  4.    functionDelegate(address _owner)public{
  5.        owner = _owner;
  6.    }
  7.    function pwn()public{
  8.        owner = msg.sender;
  9.    }
  10. }
  11. contract Deletagion{
  12.    address public owner;
  13.    Delegatedelegate;
  14.    functionDelegation(address _delegateAddreses)public{
  15.        delegate=Delegate(_delegateAddreses);
  16.        owner = msg.sender;
  17.    }
  18.    // an attacker can call Delegate.pwn() in the context of Delegation, this means that pwn() will modify the state of **Delegation** and not Delegate, the result is that the attacker takes unauthorized ownership of the contract.
  19.    function()public{
  20.        if(delegate.delegatecall(msg.data)){
  21.            this;
  22.        }
  23.    }
  24. }

Reentrancy(TheDAO hack)

Solidity 中 call 函数被调用时, 如果带有 value 参数, 则会转发所有他所收到的 gas。

在一下代码片段中, call函数在sender的余额实际减少前被调用。这里有一个漏洞曾导致TheDAO攻击。

  1. function withdraw(uint _amount)public{
  2.  if(balances[msg.sender]>= _amount){
  3.    if(msg.sender.call.value(_amount)()){
  4.      _amount;
  5.    }
  6.    balances[msg.sender]-= amount;
  7.  }
  8. }

引自Reddit的解释:

  1. In simple words, it’s like the bank teller doesn’t change your balance until she has given you all the money you requested.“Can I withdraw $500?Wait, before that , can I withdraw $500?”

  2. And so on.The smart contracts as designed only check you have $500 at beginning once,and allow themselves to be interrupted

目录
相关文章
|
消息中间件 中间件 Kafka
分布式事务最全详解 ,看这篇就够了!
本文详解分布式事务的一致性及实战解决方案,包括CAP理论、BASE理论及2PC、TCC、消息队列等常见方案,助你深入理解分布式系统的核心技术。关注【mikechen的互联网架构】,10年+BAT架构经验倾囊相授。
分布式事务最全详解 ,看这篇就够了!
|
人工智能 安全 JavaScript
革新低代码开发!VTJ.PRO v0.12.58 发布:首推「AI代码校验修复引擎」,破解生成式代码质量隐患
VTJ.PRO发布v0.12.58版本,推出「AI-CodeFix」智能引擎,实现AI生成代码的自动校验、诊断与修复,解决低代码开发调试难题。通过动态语义扫描、智能修复策略和开发者体验升级,大幅降低错误率,提升开发效率与代码质量,助力企业实现安全可控的AI开发。
544 0
|
算法 数据安全/隐私保护
VSG虚拟同步发电机simulink建模与仿真
### VSG虚拟同步发电机Simulink建模与仿真简介 虚拟同步发电机(VSG)技术是电力电子领域的重要创新,尤其在可再生能源接入电网方面展现出巨大潜力。VSG通过先进的控制策略,使逆变器控制的电源系统(如光伏、风能)表现出与传统同步发电机类似的动态行为,提高电力系统的稳定性和兼容性。本课题基于MATLAB2022a进行VSG的Simulink建模与仿真,核心内容包括电流控制、电压控制、频率控制及虚拟惯量与阻尼控制。系统仿真结果展示了VSG的有效性,并验证了其在实际应用中的潜力。
|
存储 缓存 Kubernetes
在K8S中,集群节点宕机,可能由哪些原因造成?
在K8S中,集群节点宕机,可能由哪些原因造成?
|
API Python
Blender脚本开发
Blender脚本开发
1114 1
|
XML JSON 程序员
程序员必知:常用天气预报API接口整理(转)
程序员必知:常用天气预报API接口整理(转)
918 0
|
机器学习/深度学习 数据可视化 PyTorch
|
存储 JavaScript
Vue父子组件通信(父级向子级传递数据、子级向父级传递数据、Vue父子组件存储到data数据的访问)
Vue父子组件通信(父级向子级传递数据、子级向父级传递数据、Vue父子组件存储到data数据的访问)
573 0
Vue父子组件通信(父级向子级传递数据、子级向父级传递数据、Vue父子组件存储到data数据的访问)
|
缓存 JavaScript
Vue 中keep-alive组件将会被缓存
Vue 中keep-alive组件将会被缓存