第二章里是不是有个函数没用?
Closed this issue · 1 comments
MuuJian commented
contract MappingStorage {
mapping(uint => uint) public a;
uint256 public b = 5;
constructor(){
a[0] = 1;
a[1] = 2;
}
function getHash(bytes memory bb) public pure returns(bytes32){
return keccak256(bb);
}
// hashmap的slot计算公式:slot = keccak256(h(k) . p),其中 . 意味着把前后2个值拼接到一起,类似于abi.encode(h(k), p)
// get slot of a[0] 时 key = 0, p = 0, result = 0xad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5
// get slot of a[1] 时 key = 1, p = 0, result = 0xada5013122d395ba3c54772283fb069b10426056ef8ca54750cb9bb552a59e7d
function getSlot(uint key, uint p) public pure returns(bytes32){
return keccak256(abi.encode(key, p));
}
}
getHash()
是不是多余了,getSlot
已经把哈希也算好了
MuuJian commented
其实这里foundry并没有将映射的存储布局显示完全,没有给出a[0]和a[1]的位置。其实,它们分别在:
a[0]: 0xad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5
keccak256(0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)
计算而得,你可以把它们输入getHash()函数,并检查输出的值。
这段不已经把地址算出来了吗keccak256(abi.encode(key, p))
,而不需要再通过getHash()来获得地址