19 var hashJsonLengthErr = errors.New("common: unmarshalJSON failed: hash must be exactly 32 bytes")
25 func BytesToHash(b []byte) Hash {
31 func StringToHash(s string) Hash { return BytesToHash([]byte(s)) }
32 func BigToHash(b *big.Int) Hash { return BytesToHash(b.Bytes()) }
33 func HexToHash(s string) Hash { return BytesToHash(FromHex(s)) }
35 // Don't use the default 'String' method in case we want to overwrite
37 // Get the string representation of the underlying hash
38 func (h Hash) Str() string { return string(h[:]) }
39 func (h Hash) Bytes() []byte { return h[:] }
40 func (h Hash) Big() *big.Int { return Bytes2Big(h[:]) }
41 func (h Hash) Hex() string { return "0x" + Bytes2Hex(h[:]) }
43 // UnmarshalJSON parses a hash in its hex from to a hash.
44 func (h *Hash) UnmarshalJSON(input []byte) error {
46 if length >= 2 && input[0] == '"' && input[length-1] == '"' {
47 input = input[1 : length-1]
49 // strip "0x" for length check
50 if len(input) > 1 && strings.ToLower(string(input[:2])) == "0x" {
54 // validate the length of the input hash
55 if len(input) != HashLength*2 {
56 return hashJsonLengthErr
58 h.SetBytes(FromHex(string(input)))
62 // Serialize given hash to JSON
63 func (h Hash) MarshalJSON() ([]byte, error) {
64 return json.Marshal(h.Hex())
67 // Sets the hash to the value of b. If b is larger than len(h) it will panic
68 func (h *Hash) SetBytes(b []byte) {
70 b = b[len(b)-HashLength:]
73 copy(h[HashLength-len(b):], b)
76 // Set string `s` to h. If s is larger than len(h) it will panic
77 func (h *Hash) SetString(s string) { h.SetBytes([]byte(s)) }
80 func (h *Hash) Set(other Hash) {
81 for i, v := range other {
86 // Generate implements testing/quick.Generator.
87 func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value {
88 m := rand.Intn(len(h))
89 for i := len(h) - 1; i > m; i-- {
90 h[i] = byte(rand.Uint32())
92 return reflect.ValueOf(h)
95 func EmptyHash(h Hash) bool {