Skip to main content

Privacy

题目源码

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

contract Privacy {

bool public locked = true;
uint256 public ID = block.timestamp;
uint8 private flattening = 10;
uint8 private denomination = 255;
uint16 private awkwardness = uint16(now);
bytes32[3] private data;

constructor(bytes32[3] memory _data) public {
data = _data;
}

function unlock(bytes16 _key) public {
require(_key == bytes16(data[2]));
locked = false;
}

/*
A bunch of super advanced solidity algorithms...

,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`
.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,
*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^ ,---/V\
`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*. ~|__(o.o)
^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*' UU UU
*/
}

题目要求

将锁解开,即将locked设置为true

题目分析

想要解锁,需要调用unlock方法,并正确传入_key。也就是要想办法获取到bytes16(data[2])的值。由于dataprivate的,所以要通过直接读取storage来获取data[2]的值

根据变量定义我们可以看到Storage布局如下

---------------------------------------------------------
| unused (31) | locked (1) | <- slot 0
---------------------------------------------------------
| ID (32) | <- slot 1
---------------------------------------------------------
| awkwardness (16) | denomination(8) | flattening(8) | <- slot 2
---------------------------------------------------------
data[0] | <- slot 3
---------------------------------------------------------
data[1] | <- slot 4
---------------------------------------------------------
data[2] | <- slot 5
---------------------------------------------------------

我们要读取data[2]的值,通过下面方式获取

// instance即合约地址。5是指第5个slot
await web3.eth.getStorageAt(instance,5) => 0x1a231b273bb6cd8aeb60e7568697a851d822cc66662ead8548194923946295ce
// unlock方法是传bytes16类型,所以截取前16位即可
await contract.unlock("0x1a231b273bb6cd8aeb60e7568697a851")

补充

如果这里data是一个动态数组,则slot的布局结构如下

---------------------------------------------------------
| unused (31) | locked (1) | <- slot 0
---------------------------------------------------------
| ID (32) | <- slot 1
---------------------------------------------------------
| awkwardness (16) | denomination(8) | flattening(8) | <- slot 2
---------------------------------------------------------
| data.length(32) | <- slot 3
---------------------------------------------------------
| data[0] | <- slot keccak256(3)
---------------------------------------------------------
| data[1] | <- slot keccak256(3)+1
---------------------------------------------------------
| data[2] | <- slot keccak256(3)+2
---------------------------------------------------------