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.

88 lines
2.0 KiB

  1. package merkle
  2. import (
  3. "bytes"
  4. cmn "github.com/tendermint/tmlibs/common"
  5. . "github.com/tendermint/tmlibs/test"
  6. "testing"
  7. "github.com/tendermint/go-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([]Hasher, total)
  16. for i := 0; i < total; i++ {
  17. items[i] = testItem(cmn.RandBytes(tmhash.Size))
  18. }
  19. rootHash := SimpleHashFromHashers(items)
  20. rootHash2, proofs := SimpleProofsFromHashers(items)
  21. if !bytes.Equal(rootHash, rootHash2) {
  22. t.Errorf("Unmatched root hashes: %X vs %X", rootHash, rootHash2)
  23. }
  24. // For each item, check the trail.
  25. for i, item := range items {
  26. itemHash := item.Hash()
  27. proof := proofs[i]
  28. // Verify success
  29. ok := proof.Verify(i, total, itemHash, rootHash)
  30. if !ok {
  31. t.Errorf("Verification failed for index %v.", i)
  32. }
  33. // Wrong item index should make it fail
  34. {
  35. ok = proof.Verify((i+1)%total, total, itemHash, rootHash)
  36. if ok {
  37. t.Errorf("Expected verification to fail for wrong index %v.", i)
  38. }
  39. }
  40. // Trail too long should make it fail
  41. origAunts := proof.Aunts
  42. proof.Aunts = append(proof.Aunts, cmn.RandBytes(32))
  43. {
  44. ok = proof.Verify(i, total, itemHash, rootHash)
  45. if ok {
  46. t.Errorf("Expected verification to fail for wrong trail length.")
  47. }
  48. }
  49. proof.Aunts = origAunts
  50. // Trail too short should make it fail
  51. proof.Aunts = proof.Aunts[0 : len(proof.Aunts)-1]
  52. {
  53. ok = proof.Verify(i, total, itemHash, rootHash)
  54. if ok {
  55. t.Errorf("Expected verification to fail for wrong trail length.")
  56. }
  57. }
  58. proof.Aunts = origAunts
  59. // Mutating the itemHash should make it fail.
  60. ok = proof.Verify(i, total, MutateByteSlice(itemHash), rootHash)
  61. if ok {
  62. t.Errorf("Expected verification to fail for mutated leaf hash")
  63. }
  64. // Mutating the rootHash should make it fail.
  65. ok = proof.Verify(i, total, itemHash, MutateByteSlice(rootHash))
  66. if ok {
  67. t.Errorf("Expected verification to fail for mutated root hash")
  68. }
  69. }
  70. }