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.

94 lines
2.3 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. proof := proofs[i]
  25. // Check total/index
  26. require.Equal(t, proof.Index, i, "Unmatched indicies: %d vs %d", proof.Index, i)
  27. require.Equal(t, proof.Total, total, "Unmatched totals: %d vs %d", proof.Total, total)
  28. // Verify success
  29. err := proof.Verify(rootHash, item)
  30. require.NoError(t, err, "Verification failed: %v.", err)
  31. // Trail too long should make it fail
  32. origAunts := proof.Aunts
  33. proof.Aunts = append(proof.Aunts, cmn.RandBytes(32))
  34. err = proof.Verify(rootHash, item)
  35. require.Error(t, err, "Expected verification to fail for wrong trail length")
  36. proof.Aunts = origAunts
  37. // Trail too short should make it fail
  38. proof.Aunts = proof.Aunts[0 : len(proof.Aunts)-1]
  39. err = proof.Verify(rootHash, item)
  40. require.Error(t, err, "Expected verification to fail for wrong trail length")
  41. proof.Aunts = origAunts
  42. // Mutating the itemHash should make it fail.
  43. err = proof.Verify(rootHash, MutateByteSlice(item))
  44. require.Error(t, err, "Expected verification to fail for mutated leaf hash")
  45. // Mutating the rootHash should make it fail.
  46. err = proof.Verify(MutateByteSlice(rootHash), item)
  47. require.Error(t, err, "Expected verification to fail for mutated root hash")
  48. }
  49. }
  50. func Test_getSplitPoint(t *testing.T) {
  51. tests := []struct {
  52. length int
  53. want int
  54. }{
  55. {1, 0},
  56. {2, 1},
  57. {3, 2},
  58. {4, 2},
  59. {5, 4},
  60. {10, 8},
  61. {20, 16},
  62. {100, 64},
  63. {255, 128},
  64. {256, 128},
  65. {257, 256},
  66. }
  67. for _, tt := range tests {
  68. got := getSplitPoint(tt.length)
  69. require.Equal(t, tt.want, got, "getSplitPoint(%d) = %v, want %v", tt.length, got, tt.want)
  70. }
  71. }