Solidity Weekly #10

mingderwang
Sep 2, 2018 · 3 min read

keccak256(abi.encodePacked(…))

最近如果你使用 solidity 0.4.24 以上版本編譯; 用到一些 hash functions 例如keccak256()、sha256() 或 ripemd160(),如果你帶入多個參數 (例如 keccak256(“a”, “b”, “c”)),你會看到如下的警示:

Warning: This function only accepts a single "bytes" argument. Please use "abi.encodePacked(...)" or a similar function to encode the data.
keccak256(
^ (Relevant source part starts here and spans across multiple lines)

原因是,以前這些 functions 可以接受多個參數,連在ㄧ起後做一個 hash,但由於不同值在預設 type 被自動 padding 會有不同的結果,再加上多個參數串起來,容易出現不同的 hash 結果, 造成 bugs。所以決定 0.5.0 以後改只接受一個參數。因此,可以利用 abi.encodePacked() 先做一次包裝,再當成一個參數進行 hash。

補充說明,所謂的 padding 就是用 0 填滿到 bytes32 的格式,最典型的例子就是 call 一個function,裡面的參數(parameters) 就會被轉型成 bytes32 格式。

  • 0x0000000000000000000000000000000000000000000000000000000000000045:

a uint32 value 69 padded to 32 bytes

  • 0x0000000000000000000000000000000000000000000000000000000000000001:

boolean true, padded to 32 bytes

  • 0x6162630000000000000000000000000000000000000000000000000000000000:

a bytes3 value "abc" 會被靠左對齊成 32 bytes

links 分享;

*適用於 solidity ^0.4.24;

Taipei Ethereum Meetup

台北以太坊社群專欄

mingderwang

Written by

AI, DevOps, Ethereum enthusiast

Taipei Ethereum Meetup

台北以太坊社群專欄

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade