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.

87 lines
2.0 KiB

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