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.

89 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,
  14. 10, 1)
  15. commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals)
  16. require.NoError(t, err)
  17. block := MakeBlock(h, txs, commit)
  18. require.NotNil(t, block)
  19. // proper block must pass
  20. err = block.ValidateBasic()
  21. require.NoError(t, err)
  22. // tamper with NumTxs
  23. block = MakeBlock(h, txs, commit)
  24. block.NumTxs++
  25. err = block.ValidateBasic()
  26. require.Error(t, err)
  27. // remove 1/2 the commits
  28. block = MakeBlock(h, txs, commit)
  29. block.LastCommit.Precommits = commit.Precommits[:commit.Size()/2]
  30. block.LastCommit.hash = nil // clear hash or change wont be noticed
  31. err = block.ValidateBasic()
  32. require.Error(t, err)
  33. // tamper with LastCommitHash
  34. block = MakeBlock(h, txs, commit)
  35. block.LastCommitHash = []byte("something else")
  36. err = block.ValidateBasic()
  37. require.Error(t, err)
  38. // tamper with data
  39. block = MakeBlock(h, txs, commit)
  40. block.Data.Txs[0] = Tx("something else")
  41. block.Data.hash = nil // clear hash or change wont be noticed
  42. err = block.ValidateBasic()
  43. require.Error(t, err)
  44. // tamper with DataHash
  45. block = MakeBlock(h, txs, commit)
  46. block.DataHash = cmn.RandBytes(len(block.DataHash))
  47. err = block.ValidateBasic()
  48. require.Error(t, err)
  49. }
  50. func makeBlockIDRandom() BlockID {
  51. blockHash, blockPartsHeader := crypto.CRandBytes(32), PartSetHeader{123, crypto.CRandBytes(32)}
  52. return BlockID{blockHash, blockPartsHeader}
  53. }
  54. func makeBlockID(hash string, partSetSize int, partSetHash string) BlockID {
  55. return BlockID{
  56. Hash: []byte(hash),
  57. PartsHeader: PartSetHeader{
  58. Total: partSetSize,
  59. Hash: []byte(partSetHash),
  60. },
  61. }
  62. }
  63. var nilBytes []byte
  64. func TestNilHeaderHashDoesntCrash(t *testing.T) {
  65. assert.Equal(t, []byte((*Header)(nil).Hash()), nilBytes)
  66. assert.Equal(t, []byte((new(Header)).Hash()), nilBytes)
  67. }
  68. func TestNilDataHashDoesntCrash(t *testing.T) {
  69. assert.Equal(t, []byte((*Data)(nil).Hash()), nilBytes)
  70. assert.Equal(t, []byte(new(Data).Hash()), nilBytes)
  71. }