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.

194 lines
5.7 KiB

state: add more tests for block validation (#3674) * Expose priv validators for use in testing * Generalize block header validation test past height 1 * Remove ineffectual assignment * Remove redundant SaveState call * Reorder comment for clarity * Use the block executor ApplyBlock function instead of implementing a stripped-down version of it * Remove commented-out code * Remove unnecessary test The required tests already appear to be implemented (implicitly) through the TestValidateBlockHeader test. * Allow for catching of specific error types during TestValidateBlockCommit * Make return error testable * Clean up and add TestValidateBlockCommit code * Fix formatting * Extract function to create a new mock test app * Update comment for clarity * Fix comment * Add skeleton code for evidence-related test * Allow for addressing priv val by address * Generalize test beyond a single validator * Generalize TestValidateBlockEvidence past first height * Reorder code to clearly separate tests and utility code * Use a common constant for stop height for testing in state/validation_test.go * Refactor errors to resemble existing conventions * Fix formatting * Extract common helper functions Having the tests littered with helper functions makes them less easily readable imho, so I've pulled them out into a separate file. This also makes it easier to see what helper functions are available during testing, so we minimize the chance of duplication when writing new tests. * Remove unused parameter * Remove unused parameters * Add field keys * Remove unused height constant * Fix typo * Fix incorrect return error * Add field keys * Use separate package for tests This refactors all of the state package's tests into a state_test package, so as to keep any usage of the state package's internal methods explicit. Any internal methods/constants used by tests are now explicitly exported in state/export_test.go * Refactor: extract helper function to make, validate, execute and commit a block * Rename state function to makeState * Remove redundant constant for number of validators * Refactor mock evidence registration into TestMain * Remove extraneous nVals variable * Replace function-level TODOs with file-level TODO and explanation * Remove extraneous comment * Fix linting issues brought up by GolangCI (pulled in from latest merge from develop)
5 years ago
  1. package state
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "github.com/tendermint/tendermint/crypto"
  7. "github.com/tendermint/tendermint/types"
  8. dbm "github.com/tendermint/tm-db"
  9. )
  10. //-----------------------------------------------------
  11. // Validate block
  12. func validateBlock(evidencePool EvidencePool, stateDB dbm.DB, state State, block *types.Block) error {
  13. // Validate internal consistency.
  14. if err := block.ValidateBasic(); err != nil {
  15. return err
  16. }
  17. // Validate basic info.
  18. if block.Version != state.Version.Consensus {
  19. return fmt.Errorf("Wrong Block.Header.Version. Expected %v, got %v",
  20. state.Version.Consensus,
  21. block.Version,
  22. )
  23. }
  24. if block.ChainID != state.ChainID {
  25. return fmt.Errorf("Wrong Block.Header.ChainID. Expected %v, got %v",
  26. state.ChainID,
  27. block.ChainID,
  28. )
  29. }
  30. if block.Height != state.LastBlockHeight+1 {
  31. return fmt.Errorf("Wrong Block.Header.Height. Expected %v, got %v",
  32. state.LastBlockHeight+1,
  33. block.Height,
  34. )
  35. }
  36. // Validate prev block info.
  37. if !block.LastBlockID.Equals(state.LastBlockID) {
  38. return fmt.Errorf("Wrong Block.Header.LastBlockID. Expected %v, got %v",
  39. state.LastBlockID,
  40. block.LastBlockID,
  41. )
  42. }
  43. // Validate app info
  44. if !bytes.Equal(block.AppHash, state.AppHash) {
  45. return fmt.Errorf("Wrong Block.Header.AppHash. Expected %X, got %v",
  46. state.AppHash,
  47. block.AppHash,
  48. )
  49. }
  50. if !bytes.Equal(block.ConsensusHash, state.ConsensusParams.Hash()) {
  51. return fmt.Errorf("Wrong Block.Header.ConsensusHash. Expected %X, got %v",
  52. state.ConsensusParams.Hash(),
  53. block.ConsensusHash,
  54. )
  55. }
  56. if !bytes.Equal(block.LastResultsHash, state.LastResultsHash) {
  57. return fmt.Errorf("Wrong Block.Header.LastResultsHash. Expected %X, got %v",
  58. state.LastResultsHash,
  59. block.LastResultsHash,
  60. )
  61. }
  62. if !bytes.Equal(block.ValidatorsHash, state.Validators.Hash()) {
  63. return fmt.Errorf("Wrong Block.Header.ValidatorsHash. Expected %X, got %v",
  64. state.Validators.Hash(),
  65. block.ValidatorsHash,
  66. )
  67. }
  68. if !bytes.Equal(block.NextValidatorsHash, state.NextValidators.Hash()) {
  69. return fmt.Errorf("Wrong Block.Header.NextValidatorsHash. Expected %X, got %v",
  70. state.NextValidators.Hash(),
  71. block.NextValidatorsHash,
  72. )
  73. }
  74. // Validate block LastCommit.
  75. if block.Height == 1 {
  76. if len(block.LastCommit.Precommits) != 0 {
  77. return errors.New("Block at height 1 can't have LastCommit precommits")
  78. }
  79. } else {
  80. if len(block.LastCommit.Precommits) != state.LastValidators.Size() {
  81. return types.NewErrInvalidCommitPrecommits(state.LastValidators.Size(), len(block.LastCommit.Precommits))
  82. }
  83. err := state.LastValidators.VerifyCommit(
  84. state.ChainID, state.LastBlockID, block.Height-1, block.LastCommit)
  85. if err != nil {
  86. return err
  87. }
  88. }
  89. // Validate block Time
  90. if block.Height > 1 {
  91. if !block.Time.After(state.LastBlockTime) {
  92. return fmt.Errorf("Block time %v not greater than last block time %v",
  93. block.Time,
  94. state.LastBlockTime,
  95. )
  96. }
  97. medianTime := MedianTime(block.LastCommit, state.LastValidators)
  98. if !block.Time.Equal(medianTime) {
  99. return fmt.Errorf("Invalid block time. Expected %v, got %v",
  100. medianTime,
  101. block.Time,
  102. )
  103. }
  104. } else if block.Height == 1 {
  105. genesisTime := state.LastBlockTime
  106. if !block.Time.Equal(genesisTime) {
  107. return fmt.Errorf("Block time %v is not equal to genesis time %v",
  108. block.Time,
  109. genesisTime,
  110. )
  111. }
  112. }
  113. // Limit the amount of evidence
  114. maxNumEvidence, _ := types.MaxEvidencePerBlock(state.ConsensusParams.Block.MaxBytes)
  115. numEvidence := int64(len(block.Evidence.Evidence))
  116. if numEvidence > maxNumEvidence {
  117. return types.NewErrEvidenceOverflow(maxNumEvidence, numEvidence)
  118. }
  119. // Validate all evidence.
  120. for _, ev := range block.Evidence.Evidence {
  121. if err := VerifyEvidence(stateDB, state, ev); err != nil {
  122. return types.NewErrEvidenceInvalid(ev, err)
  123. }
  124. if evidencePool != nil && evidencePool.IsCommitted(ev) {
  125. return types.NewErrEvidenceInvalid(ev, errors.New("evidence was already committed"))
  126. }
  127. }
  128. // NOTE: We can't actually verify it's the right proposer because we dont
  129. // know what round the block was first proposed. So just check that it's
  130. // a legit address and a known validator.
  131. if len(block.ProposerAddress) != crypto.AddressSize ||
  132. !state.Validators.HasAddress(block.ProposerAddress) {
  133. return fmt.Errorf("Block.Header.ProposerAddress, %X, is not a validator",
  134. block.ProposerAddress,
  135. )
  136. }
  137. return nil
  138. }
  139. // VerifyEvidence verifies the evidence fully by checking:
  140. // - it is sufficiently recent (MaxAge)
  141. // - it is from a key who was a validator at the given height
  142. // - it is internally consistent
  143. // - it was properly signed by the alleged equivocator
  144. func VerifyEvidence(stateDB dbm.DB, state State, evidence types.Evidence) error {
  145. height := state.LastBlockHeight
  146. evidenceAge := height - evidence.Height()
  147. maxAge := state.ConsensusParams.Evidence.MaxAge
  148. if evidenceAge > maxAge {
  149. return fmt.Errorf("Evidence from height %d is too old. Min height is %d",
  150. evidence.Height(), height-maxAge)
  151. }
  152. valset, err := LoadValidators(stateDB, evidence.Height())
  153. if err != nil {
  154. // TODO: if err is just that we cant find it cuz we pruned, ignore.
  155. // TODO: if its actually bad evidence, punish peer
  156. return err
  157. }
  158. // The address must have been an active validator at the height.
  159. // NOTE: we will ignore evidence from H if the key was not a validator
  160. // at H, even if it is a validator at some nearby H'
  161. // XXX: this makes lite-client bisection as is unsafe
  162. // See https://github.com/tendermint/tendermint/issues/3244
  163. ev := evidence
  164. height, addr := ev.Height(), ev.Address()
  165. _, val := valset.GetByAddress(addr)
  166. if val == nil {
  167. return fmt.Errorf("Address %X was not a validator at height %d", addr, height)
  168. }
  169. if err := evidence.Verify(state.ChainID, val.PubKey); err != nil {
  170. return err
  171. }
  172. return nil
  173. }