# 智能合约黑客攻击 Ethernaut:  
 18. MagicNumber

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

---

[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 - ….
    

题目
--

设计一个合约，有一下要求

*   地址存储在 solver 里
    
*   提供一个 whatIsTheMeaningOfLife() 方法返回 42
    
*   合约 opcode 小于10
    

Hack思路
------

合约 opcode 小于10只能用汇编了，可以参考[代码](https://solidity-by-example.org/app/simple-bytecode-contract/)。

    
    interface IMagicNumHack {
        function setSolver(address _solver) external;
    }
    
    contract MagicNumHack {
        IMagicNumHack public exploitInst;
    
        constructor(address _target) {
            exploitInst = IMagicNumHack(_target);
    
            bytes memory code = hex"600a600c600039600a6000f3602a60505260206050f3";
            address addr;
            assembly {
                addr := create(0, add(code, 0x20), mload(code))
                if iszero(extcodesize(addr)) { revert(0, 0) }
            }
            exploitInst.setSolver(addr);
        }
    
        function attack() external { }
    }
    

Hack案例
------

…

防范思路
----

…

参考资料
----

*   [Simple Bytecode Contract](https://solidity-by-example.org/app/simple-bytecode-contract/)

---

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