web3系列——重入攻击(solidity)

我们的BNB3项目目前处于推广阶段了!希望尊敬的各位程序员来加入!

最近DEXX被盗了😂,我又双叒开始入门合约安全!确实,在web2似乎很少遇见hacker,但是在新的领域,真的需要各位优秀的程序员加入!!

什么是智能合约中的重入攻击?如何防范这种攻击?

防范措施:

  • 使用 Checks-Effects-Interactions 模式:先进行检查,修改合约状态,再与外部合约交互。
  • 使用 Reentrancy Guard:通过在合约中引入状态标志,防止重入调用。

攻击原理

  1. 合约 A 调用合约 B 的一个函数,转账或执行其他逻辑。
  2. 合约 B 在逻辑中调用外部合约 C(通常是攻击者的合约)。
  3. 合约 C 的回调函数再次调用合约 A 的函数,而此时合约 A 尚未完成状态更新,可能导致重复执行敏感逻辑(例如转账资金),从而被攻击者多次利用。

Vulnerable 合约

这是一个简单的提款合约,用户可以存款并提取他们的余额,但存在重入漏洞。

Attacker 合约 攻击者合约通过构造恶意逻辑,在回调函数中反复调用 withdraw 函数,窃取 Vulnerable 合约的资金。

解决办法

  • 将状态更新放在外部调用之前(采用检查-效应-交互模式)。

    solidity 复制代码
    function withdraw(uint256 amount) public nonReentrant {
        require(balances[msg.sender] >= amount, "Insufficient balance");
    
        // 更新余额
        balances[msg.sender] -= amount;
    
        // 转账操作
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Transfer failed");
    }
  • 使用 OpenZeppelin 的 ReentrancyGuard 防止重入攻击。

solidity 复制代码
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract SecureContract is ReentrancyGuard {
    mapping(address => uint256) public balances;

    // 用户存款
    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }

    // 防止重入的提款函数
    function withdraw(uint256 amount) public nonReentrant {
        require(balances[msg.sender] >= amount, "Insufficient balance");

        // 更新余额
        balances[msg.sender] -= amount;

        // 执行外部调用
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Transfer failed");
    }

    // 获取合约余额
    function getContractBalance() public view returns (uint256) {
        return address(this).balance;
    }
}

ps: BNB3平台在测试上线了,欢迎各位来玩😊

相关推荐
木西9 小时前
React Native DApp 开发全栈实战·从 0 到 1 系列(兑换-合约部分)
web3·智能合约·solidity
全干engineer2 天前
区块链web3项目实战-Truffle petshop
web3·区块链
Armonia生态2 天前
Armonia Mall超级数字生态WEB3商城的引领者
web3·armonia-mall
alex1003 天前
【一天一个Web3概念】Web3.0赛道分析:新一轮技术浪潮下的机遇与挑战
web3
Web3_Daisy4 天前
克隆代币 + 捆绑开盘:多链环境下的低成本发币玩法
人工智能·web3·区块链·比特币
清 晨4 天前
Web3:去中心化网络指南
web3·去中心化·区块链·facebook·tiktok·instagram·clonbrowser
清 晨4 天前
Web3.0应用成功的诀窍
web3·互联网·facebook·tiktok·instagram·指纹浏览器·clonbrowser
moz与京4 天前
【面试向】热门技术话题(上)
人工智能·物联网·机器学习·面试·web3·区块链·元宇宙
木西5 天前
React Native DApp 开发全栈实战·从 0 到 1 系列(永续合约交易-前端部分)
react native·web3·智能合约
OpenBuild.xyz6 天前
Web3 开发者周刊 66 | 重新审视L2:跨链桥与定序器背后的信任裂痕
web3·区块链·业界资讯·周报·数字货币