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.

83 lines
1.9 KiB

  1. package merkle
  2. import (
  3. . "github.com/tendermint/tendermint/common"
  4. . "github.com/tendermint/tendermint/common/test"
  5. "testing"
  6. )
  7. type testItem []byte
  8. func (tI testItem) Hash() []byte {
  9. return []byte(tI)
  10. }
  11. func TestSimpleProof(t *testing.T) {
  12. numItems := 100
  13. items := make([]Hashable, numItems)
  14. for i := 0; i < numItems; i++ {
  15. items[i] = testItem(RandBytes(32))
  16. }
  17. rootHash := SimpleHashFromHashables(items)
  18. proofs := SimpleProofsFromHashables(items)
  19. // For each item, check the trail.
  20. for i, item := range items {
  21. itemHash := item.Hash()
  22. proof := proofs[i]
  23. // Verify success
  24. ok := proof.Verify(itemHash, rootHash)
  25. if !ok {
  26. t.Errorf("Verification failed for index %v.", i)
  27. }
  28. // Wrong item index should make it fail
  29. proof.Index += 1
  30. {
  31. ok = proof.Verify(itemHash, rootHash)
  32. if ok {
  33. t.Errorf("Expected verification to fail for wrong index %v.", i)
  34. }
  35. }
  36. proof.Index -= 1
  37. // Trail too long should make it fail
  38. origInnerHashes := proof.InnerHashes
  39. proof.InnerHashes = append(proof.InnerHashes, RandBytes(32))
  40. {
  41. ok = proof.Verify(itemHash, rootHash)
  42. if ok {
  43. t.Errorf("Expected verification to fail for wrong trail length.")
  44. }
  45. }
  46. proof.InnerHashes = origInnerHashes
  47. // Trail too short should make it fail
  48. proof.InnerHashes = proof.InnerHashes[0 : len(proof.InnerHashes)-1]
  49. {
  50. ok = proof.Verify(itemHash, rootHash)
  51. if ok {
  52. t.Errorf("Expected verification to fail for wrong trail length.")
  53. }
  54. }
  55. proof.InnerHashes = origInnerHashes
  56. // Mutating the itemHash should make it fail.
  57. ok = proof.Verify(MutateByteSlice(itemHash), rootHash)
  58. if ok {
  59. t.Errorf("Expected verification to fail for mutated leaf hash")
  60. }
  61. // Mutating the rootHash should make it fail.
  62. ok = proof.Verify(itemHash, MutateByteSlice(rootHash))
  63. if ok {
  64. t.Errorf("Expected verification to fail for mutated root hash")
  65. }
  66. }
  67. }