/
hash.go
44 lines (39 loc) · 905 Bytes
/
hash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package merkle
import (
"bytes"
"github.com/FiboChain/fbc/libs/tendermint/crypto/tmhash"
"sync"
)
// TODO: make these have a large predefined capacity
var (
leafPrefix = []byte{0}
innerPrefix = []byte{1}
hashBytesPool = &sync.Pool{
New: func() interface{} {
return &bytes.Buffer{}
},
}
)
// returns tmhash(0x00 || leaf)
func leafHash(leaf []byte) []byte {
buf := hashBytesPool.Get().(*bytes.Buffer)
buf.Reset()
buf.Grow(len(leafPrefix) + len(leaf))
buf.Write(leafPrefix)
buf.Write(leaf)
h := tmhash.Sum(buf.Bytes())
hashBytesPool.Put(buf)
return h
}
// returns tmhash(0x01 || left || right)
func innerHash(left []byte, right []byte) []byte {
buf := hashBytesPool.Get().(*bytes.Buffer)
buf.Reset()
buf.Grow(len(innerPrefix) + len(left) + len(right))
buf.Write(innerPrefix)
buf.Write(left)
buf.Write(right)
h := tmhash.Sum(buf.Bytes())
hashBytesPool.Put(buf)
return h
}