You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.0 KiB

  1. package merkle
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/require"
  5. cmn "github.com/tendermint/tendermint/libs/common"
  6. . "github.com/tendermint/tendermint/libs/test"
  7. "github.com/tendermint/tendermint/crypto/tmhash"
  8. )
  9. type testItem []byte
  10. func (tI testItem) Hash() []byte {
  11. return []byte(tI)
  12. }
  13. func TestSimpleProof(t *testing.T) {
  14. total := 100
  15. items := make([][]byte, total)
  16. for i := 0; i < total; i++ {
  17. items[i] = testItem(cmn.RandBytes(tmhash.Size))
  18. }
  19. rootHash := SimpleHashFromByteSlices(items)
  20. rootHash2, proofs := SimpleProofsFromByteSlices(items)
  21. require.Equal(t, rootHash, rootHash2, "Unmatched root hashes: %X vs %X", rootHash, rootHash2)
  22. // For each item, check the trail.
  23. for i, item := range items {
  24. itemHash := tmhash.Sum(item)
  25. proof := proofs[i]
  26. // Check total/index
  27. require.Equal(t, proof.Index, i, "Unmatched indicies: %d vs %d", proof.Index, i)
  28. require.Equal(t, proof.Total, total, "Unmatched totals: %d vs %d", proof.Total, total)
  29. // Verify success
  30. err := proof.Verify(rootHash, itemHash)
  31. require.NoError(t, err, "Verificatior failed: %v.", err)
  32. // Trail too long should make it fail
  33. origAunts := proof.Aunts
  34. proof.Aunts = append(proof.Aunts, cmn.RandBytes(32))
  35. err = proof.Verify(rootHash, itemHash)
  36. require.Error(t, err, "Expected verification to fail for wrong trail length")
  37. proof.Aunts = origAunts
  38. // Trail too short should make it fail
  39. proof.Aunts = proof.Aunts[0 : len(proof.Aunts)-1]
  40. err = proof.Verify(rootHash, itemHash)
  41. require.Error(t, err, "Expected verification to fail for wrong trail length")
  42. proof.Aunts = origAunts
  43. // Mutating the itemHash should make it fail.
  44. err = proof.Verify(rootHash, MutateByteSlice(itemHash))
  45. require.Error(t, err, "Expected verification to fail for mutated leaf hash")
  46. // Mutating the rootHash should make it fail.
  47. err = proof.Verify(MutateByteSlice(rootHash), itemHash)
  48. require.Error(t, err, "Expected verification to fail for mutated root hash")
  49. }
  50. }