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.2 KiB

  1. package types
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. "github.com/stretchr/testify/require"
  6. crypto "github.com/tendermint/go-crypto"
  7. cmn "github.com/tendermint/tmlibs/common"
  8. )
  9. func TestValidateBlock(t *testing.T) {
  10. txs := []Tx{Tx("foo"), Tx("bar")}
  11. lastID := makeBlockIDRandom()
  12. h := int64(3)
  13. voteSet, _, vals := randVoteSet(h-1, 1, VoteTypePrecommit, 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++
  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. }
  62. var nilBytes []byte
  63. func TestNilHeaderHashDoesntCrash(t *testing.T) {
  64. assert.Equal(t, []byte((*Header)(nil).Hash()), nilBytes)
  65. assert.Equal(t, []byte((new(Header)).Hash()), nilBytes)
  66. }
  67. func TestNilDataHashDoesntCrash(t *testing.T) {
  68. assert.Equal(t, []byte((*Data)(nil).Hash()), nilBytes)
  69. assert.Equal(t, []byte(new(Data).Hash()), nilBytes)
  70. }