mirror of
https://github.com/tendermint/tendermint.git
synced 2026-01-05 13:05:09 +00:00
* crypto/merkle: optimize merkle tree hashing (#6513) Upstream https://github.com/lazyledger/lazyledger-core/pull/351 to optimize merkle tree hashing ``` benchmark old ns/op new ns/op delta BenchmarkHashAlternatives/recursive-8 22914 21949 -4.21% BenchmarkHashAlternatives/iterative-8 21634 21939 +1.41% benchmark old allocs new allocs delta BenchmarkHashAlternatives/recursive-8 398 200 -49.75% BenchmarkHashAlternatives/iterative-8 399 301 -24.56% benchmark old bytes new bytes delta BenchmarkHashAlternatives/recursive-8 19088 6496 -65.97% BenchmarkHashAlternatives/iterative-8 21776 13984 -35.78% ``` cc @odeke-em @cuonglm * update pending log Co-authored-by: Marko <marbar3778@yahoo.com>
49 lines
969 B
Go
49 lines
969 B
Go
package merkle
|
|
|
|
import (
|
|
"hash"
|
|
|
|
"github.com/tendermint/tendermint/crypto/tmhash"
|
|
)
|
|
|
|
// TODO: make these have a large predefined capacity
|
|
var (
|
|
leafPrefix = []byte{0}
|
|
innerPrefix = []byte{1}
|
|
)
|
|
|
|
// returns tmhash(<empty>)
|
|
func emptyHash() []byte {
|
|
return tmhash.Sum([]byte{})
|
|
}
|
|
|
|
// returns tmhash(0x00 || leaf)
|
|
func leafHash(leaf []byte) []byte {
|
|
return tmhash.Sum(append(leafPrefix, leaf...))
|
|
}
|
|
|
|
// returns tmhash(0x00 || leaf)
|
|
func leafHashOpt(s hash.Hash, leaf []byte) []byte {
|
|
s.Reset()
|
|
s.Write(leafPrefix)
|
|
s.Write(leaf)
|
|
return s.Sum(nil)
|
|
}
|
|
|
|
// returns tmhash(0x01 || left || right)
|
|
func innerHash(left []byte, right []byte) []byte {
|
|
data := make([]byte, len(innerPrefix)+len(left)+len(right))
|
|
n := copy(data, innerPrefix)
|
|
n += copy(data[n:], left)
|
|
copy(data[n:], right)
|
|
return tmhash.Sum(data)
|
|
}
|
|
|
|
func innerHashOpt(s hash.Hash, left []byte, right []byte) []byte {
|
|
s.Reset()
|
|
s.Write(innerPrefix)
|
|
s.Write(left)
|
|
s.Write(right)
|
|
return s.Sum(nil)
|
|
}
|