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.

75 lines
1.9 KiB

  1. package types
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/require"
  5. crypto "github.com/tendermint/go-crypto"
  6. cmn "github.com/tendermint/tmlibs/common"
  7. )
  8. func TestValidateBlock(t *testing.T) {
  9. txs := []Tx{Tx("foo"), Tx("bar")}
  10. lastID := makeBlockIDRandom()
  11. h := int64(3)
  12. voteSet, _, vals := randVoteSet(h-1, 1, VoteTypePrecommit,
  13. 10, 1)
  14. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  15. require.NoError(t, err)
  16. block := MakeBlock(h, txs, commit)
  17. require.NotNil(t, block)
  18. // proper block must pass
  19. err = block.ValidateBasic()
  20. require.NoError(t, err)
  21. // tamper with NumTxs
  22. block = MakeBlock(h, txs, commit)
  23. block.NumTxs += 1
  24. err = block.ValidateBasic()
  25. require.Error(t, err)
  26. // remove 1/2 the commits
  27. block = MakeBlock(h, txs, commit)
  28. block.LastCommit.Precommits = commit.Precommits[:commit.Size()/2]
  29. block.LastCommit.hash = nil // clear hash or change wont be noticed
  30. err = block.ValidateBasic()
  31. require.Error(t, err)
  32. // tamper with LastCommitHash
  33. block = MakeBlock(h, txs, commit)
  34. block.LastCommitHash = []byte("something else")
  35. err = block.ValidateBasic()
  36. require.Error(t, err)
  37. // tamper with data
  38. block = MakeBlock(h, txs, commit)
  39. block.Data.Txs[0] = Tx("something else")
  40. block.Data.hash = nil // clear hash or change wont be noticed
  41. err = block.ValidateBasic()
  42. require.Error(t, err)
  43. // tamper with DataHash
  44. block = MakeBlock(h, txs, commit)
  45. block.DataHash = cmn.RandBytes(len(block.DataHash))
  46. err = block.ValidateBasic()
  47. require.Error(t, err)
  48. }
  49. func makeBlockIDRandom() BlockID {
  50. blockHash, blockPartsHeader := crypto.CRandBytes(32), PartSetHeader{123, crypto.CRandBytes(32)}
  51. return BlockID{blockHash, blockPartsHeader}
  52. }
  53. func makeBlockID(hash string, partSetSize int, partSetHash string) BlockID {
  54. return BlockID{
  55. Hash: []byte(hash),
  56. PartsHeader: PartSetHeader{
  57. Total: partSetSize,
  58. Hash: []byte(partSetHash),
  59. },
  60. }
  61. }