tendermint/crypto/merkle/simple_tree_test.go

73 lines
2.0 KiB
Go
Raw Normal View History

2018-06-20 15:30:44 -07:00
package merkle
import (
"testing"
"github.com/stretchr/testify/require"
2018-06-20 15:30:44 -07:00
2018-07-01 22:36:49 -04:00
cmn "github.com/tendermint/tendermint/libs/common"
. "github.com/tendermint/tendermint/libs/test"
2018-06-20 15:30:44 -07:00
"github.com/tendermint/tendermint/crypto/tmhash"
2018-06-20 15:30:44 -07:00
)
type testItem []byte
func (tI testItem) Hash() []byte {
return []byte(tI)
}
func TestSimpleProof(t *testing.T) {
total := 100
items := make([][]byte, total)
2018-06-20 15:30:44 -07:00
for i := 0; i < total; i++ {
items[i] = testItem(cmn.RandBytes(tmhash.Size))
}
rootHash := SimpleHashFromByteSlices(items)
2018-06-20 15:30:44 -07:00
rootHash2, proofs := SimpleProofsFromByteSlices(items)
2018-06-20 15:30:44 -07:00
require.Equal(t, rootHash, rootHash2, "Unmatched root hashes: %X vs %X", rootHash, rootHash2)
2018-06-20 15:30:44 -07:00
// For each item, check the trail.
for i, item := range items {
itemHash := tmhash.Sum(item)
2018-06-20 15:30:44 -07:00
proof := proofs[i]
// Check total/index
require.Equal(t, proof.Index, i, "Unmatched indicies: %d vs %d", proof.Index, i)
require.Equal(t, proof.Total, total, "Unmatched totals: %d vs %d", proof.Total, total)
2018-06-20 15:30:44 -07:00
// Verify success
err := proof.Verify(rootHash, itemHash)
require.NoError(t, err, "Verificatior failed: %v.", err)
2018-06-20 15:30:44 -07:00
// Trail too long should make it fail
origAunts := proof.Aunts
proof.Aunts = append(proof.Aunts, cmn.RandBytes(32))
err = proof.Verify(rootHash, itemHash)
require.Error(t, err, "Expected verification to fail for wrong trail length")
2018-06-20 15:30:44 -07:00
proof.Aunts = origAunts
// Trail too short should make it fail
proof.Aunts = proof.Aunts[0 : len(proof.Aunts)-1]
err = proof.Verify(rootHash, itemHash)
require.Error(t, err, "Expected verification to fail for wrong trail length")
2018-06-20 15:30:44 -07:00
proof.Aunts = origAunts
// Mutating the itemHash should make it fail.
err = proof.Verify(rootHash, MutateByteSlice(itemHash))
require.Error(t, err, "Expected verification to fail for mutated leaf hash")
2018-06-20 15:30:44 -07:00
// Mutating the rootHash should make it fail.
err = proof.Verify(MutateByteSlice(rootHash), itemHash)
require.Error(t, err, "Expected verification to fail for mutated root hash")
2018-06-20 15:30:44 -07:00
}
}