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.

74 lines
1.8 KiB

  1. package merkle
  2. import (
  3. . "github.com/tendermint/tendermint/common"
  4. "bytes"
  5. "testing"
  6. )
  7. type testItem []byte
  8. func (tI testItem) Hash() []byte {
  9. return []byte(tI)
  10. }
  11. func TestMerkleTrails(t *testing.T) {
  12. numItems := uint(100)
  13. items := make([]Hashable, numItems)
  14. for i := uint(0); i < numItems; i++ {
  15. items[i] = testItem(RandBytes(32))
  16. }
  17. root := HashFromHashables(items)
  18. trails, rootTrail := HashTrailsFromHashables(items)
  19. // Assert that HashFromHashables and HashTrailsFromHashables are compatible.
  20. if !bytes.Equal(root, rootTrail.Hash) {
  21. t.Errorf("Root mismatch:\n%X vs\n%X", root, rootTrail.Hash)
  22. }
  23. // For each item, check the trail.
  24. for i, item := range items {
  25. itemHash := item.Hash()
  26. flatTrail := trails[i].Flatten()
  27. // Verify success
  28. ok := VerifyHashTrail(uint(i), numItems, itemHash, flatTrail, root)
  29. if !ok {
  30. t.Errorf("Verification failed for index %v.", i)
  31. }
  32. // Wrong item index should make it fail
  33. ok = VerifyHashTrail(uint(i)+1, numItems, itemHash, flatTrail, root)
  34. if ok {
  35. t.Errorf("Expected verification to fail for wrong index %v.", i)
  36. }
  37. // Trail too long should make it fail
  38. trail2 := append(flatTrail, RandBytes(32))
  39. ok = VerifyHashTrail(uint(i), numItems, itemHash, trail2, root)
  40. if ok {
  41. t.Errorf("Expected verification to fail for wrong trail length.")
  42. }
  43. // Trail too short should make it fail
  44. trail2 = flatTrail[:len(flatTrail)-1]
  45. ok = VerifyHashTrail(uint(i), numItems, itemHash, trail2, root)
  46. if ok {
  47. t.Errorf("Expected verification to fail for wrong trail length.")
  48. }
  49. // Mutating the itemHash should make it fail.
  50. itemHash2 := make([]byte, len(itemHash))
  51. copy(itemHash2, itemHash)
  52. itemHash2[0] += byte(0x01)
  53. ok = VerifyHashTrail(uint(i), numItems, itemHash2, flatTrail, root)
  54. if ok {
  55. t.Errorf("Expected verification to fail for mutated leaf hash")
  56. }
  57. }
  58. }