This commit is contained in:
Ethan Buchman 2018-05-21 20:15:32 -04:00
parent 4fb515fa08
commit d82699bf43
4 changed files with 69 additions and 5 deletions

View File

@ -2,7 +2,7 @@ package merkle
import ( import (
cmn "github.com/tendermint/tmlibs/common" cmn "github.com/tendermint/tmlibs/common"
"golang.org/x/crypto/ripemd160" "github.com/tendermint/tmlibs/merkle/tmhash"
) )
type SimpleMap struct { type SimpleMap struct {
@ -63,7 +63,7 @@ func (sm *SimpleMap) KVPairs() cmn.KVPairs {
type KVPair cmn.KVPair type KVPair cmn.KVPair
func (kv KVPair) Hash() []byte { func (kv KVPair) Hash() []byte {
hasher := ripemd160.New() hasher := tmhash.New()
err := encodeByteSlice(hasher, kv.Key) err := encodeByteSlice(hasher, kv.Key)
if err != nil { if err != nil {
panic(err) panic(err)

View File

@ -25,11 +25,11 @@ For larger datasets, use IAVLTree.
package merkle package merkle
import ( import (
"golang.org/x/crypto/ripemd160" "github.com/tendermint/tmlibs/merkle/tmhash"
) )
func SimpleHashFromTwoHashes(left []byte, right []byte) []byte { func SimpleHashFromTwoHashes(left []byte, right []byte) []byte {
var hasher = ripemd160.New() var hasher = tmhash.New()
err := encodeByteSlice(hasher, left) err := encodeByteSlice(hasher, left)
if err != nil { if err != nil {
panic(err) panic(err)
@ -68,7 +68,7 @@ func SimpleHashFromByteslices(bzs [][]byte) []byte {
} }
func SimpleHashFromBytes(bz []byte) []byte { func SimpleHashFromBytes(bz []byte) []byte {
hasher := ripemd160.New() hasher := tmhash.New()
hasher.Write(bz) hasher.Write(bz)
return hasher.Sum(nil) return hasher.Sum(nil)
} }

41
merkle/tmhash/hash.go Normal file
View File

@ -0,0 +1,41 @@
package tmhash
import (
"crypto/sha256"
"hash"
)
var (
Size = 20
BlockSize = sha256.BlockSize
)
type sha256trunc struct {
sha256 hash.Hash
}
func (h sha256trunc) Write(p []byte) (n int, err error) {
return h.sha256.Write(p)
}
func (h sha256trunc) Sum(b []byte) []byte {
shasum := h.sha256.Sum(b)
return shasum[:Size]
}
func (h sha256trunc) Reset() {
h.sha256.Reset()
}
func (h sha256trunc) Size() int {
return Size
}
func (h sha256trunc) BlockSize() int {
return h.sha256.BlockSize()
}
func New() hash.Hash {
return sha256trunc{
sha256: sha256.New(),
}
}

View File

@ -0,0 +1,23 @@
package tmhash_test
import (
"crypto/sha256"
"testing"
"github.com/stretchr/testify/assert"
"github.com/tendermint/tmlibs/merkle/tmhash"
)
func TestHash(t *testing.T) {
testVector := []byte("abc")
hasher := tmhash.New()
hasher.Write(testVector)
bz := hasher.Sum(nil)
hasher = sha256.New()
hasher.Write(testVector)
bz2 := hasher.Sum(nil)
bz2 = bz2[:20]
assert.Equal(t, bz, bz2)
}