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.

262 lines
8.0 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
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
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_test
  2. import (
  3. "bytes"
  4. "fmt"
  5. abci "github.com/tendermint/tendermint/abci/types"
  6. "github.com/tendermint/tendermint/crypto"
  7. "github.com/tendermint/tendermint/crypto/ed25519"
  8. "github.com/tendermint/tendermint/proxy"
  9. sm "github.com/tendermint/tendermint/state"
  10. "github.com/tendermint/tendermint/types"
  11. tmtime "github.com/tendermint/tendermint/types/time"
  12. dbm "github.com/tendermint/tm-cmn/db"
  13. )
  14. type paramsChangeTestCase struct {
  15. height int64
  16. params types.ConsensusParams
  17. }
  18. // always returns true if asked if any evidence was already committed.
  19. type mockEvPoolAlwaysCommitted struct{}
  20. func (m mockEvPoolAlwaysCommitted) PendingEvidence(int64) []types.Evidence { return nil }
  21. func (m mockEvPoolAlwaysCommitted) AddEvidence(types.Evidence) error { return nil }
  22. func (m mockEvPoolAlwaysCommitted) Update(*types.Block, sm.State) {}
  23. func (m mockEvPoolAlwaysCommitted) IsCommitted(types.Evidence) bool { return true }
  24. func newTestApp() proxy.AppConns {
  25. app := &testApp{}
  26. cc := proxy.NewLocalClientCreator(app)
  27. return proxy.NewAppConns(cc)
  28. }
  29. func makeAndCommitGoodBlock(
  30. state sm.State,
  31. height int64,
  32. lastCommit *types.Commit,
  33. proposerAddr []byte,
  34. blockExec *sm.BlockExecutor,
  35. privVals map[string]types.PrivValidator,
  36. evidence []types.Evidence) (sm.State, types.BlockID, *types.Commit, error) {
  37. // A good block passes
  38. state, blockID, err := makeAndApplyGoodBlock(state, height, lastCommit, proposerAddr, blockExec, evidence)
  39. if err != nil {
  40. return state, types.BlockID{}, nil, err
  41. }
  42. // Simulate a lastCommit for this block from all validators for the next height
  43. commit, err := makeValidCommit(height, blockID, state.Validators, privVals)
  44. if err != nil {
  45. return state, types.BlockID{}, nil, err
  46. }
  47. return state, blockID, commit, nil
  48. }
  49. func makeAndApplyGoodBlock(state sm.State, height int64, lastCommit *types.Commit, proposerAddr []byte,
  50. blockExec *sm.BlockExecutor, evidence []types.Evidence) (sm.State, types.BlockID, error) {
  51. block, _ := state.MakeBlock(height, makeTxs(height), lastCommit, evidence, proposerAddr)
  52. if err := blockExec.ValidateBlock(state, block); err != nil {
  53. return state, types.BlockID{}, err
  54. }
  55. blockID := types.BlockID{Hash: block.Hash(), PartsHeader: types.PartSetHeader{}}
  56. state, err := blockExec.ApplyBlock(state, blockID, block)
  57. if err != nil {
  58. return state, types.BlockID{}, err
  59. }
  60. return state, blockID, nil
  61. }
  62. func makeValidCommit(height int64, blockID types.BlockID, vals *types.ValidatorSet, privVals map[string]types.PrivValidator) (*types.Commit, error) {
  63. sigs := make([]*types.CommitSig, 0)
  64. for i := 0; i < vals.Size(); i++ {
  65. _, val := vals.GetByIndex(i)
  66. vote, err := types.MakeVote(height, blockID, vals, privVals[val.Address.String()], chainID)
  67. if err != nil {
  68. return nil, err
  69. }
  70. sigs = append(sigs, vote.CommitSig())
  71. }
  72. return types.NewCommit(blockID, sigs), nil
  73. }
  74. // make some bogus txs
  75. func makeTxs(height int64) (txs []types.Tx) {
  76. for i := 0; i < nTxsPerBlock; i++ {
  77. txs = append(txs, types.Tx([]byte{byte(height), byte(i)}))
  78. }
  79. return txs
  80. }
  81. func makeState(nVals, height int) (sm.State, dbm.DB, map[string]types.PrivValidator) {
  82. vals := make([]types.GenesisValidator, nVals)
  83. privVals := make(map[string]types.PrivValidator, nVals)
  84. for i := 0; i < nVals; i++ {
  85. secret := []byte(fmt.Sprintf("test%d", i))
  86. pk := ed25519.GenPrivKeyFromSecret(secret)
  87. valAddr := pk.PubKey().Address()
  88. vals[i] = types.GenesisValidator{
  89. Address: valAddr,
  90. PubKey: pk.PubKey(),
  91. Power: 1000,
  92. Name: fmt.Sprintf("test%d", i),
  93. }
  94. privVals[valAddr.String()] = types.NewMockPVWithParams(pk, false, false)
  95. }
  96. s, _ := sm.MakeGenesisState(&types.GenesisDoc{
  97. ChainID: chainID,
  98. Validators: vals,
  99. AppHash: nil,
  100. })
  101. stateDB := dbm.NewMemDB()
  102. sm.SaveState(stateDB, s)
  103. for i := 1; i < height; i++ {
  104. s.LastBlockHeight++
  105. s.LastValidators = s.Validators.Copy()
  106. sm.SaveState(stateDB, s)
  107. }
  108. return s, stateDB, privVals
  109. }
  110. func makeBlock(state sm.State, height int64) *types.Block {
  111. block, _ := state.MakeBlock(height, makeTxs(state.LastBlockHeight), new(types.Commit), nil, state.Validators.GetProposer().Address)
  112. return block
  113. }
  114. func genValSet(size int) *types.ValidatorSet {
  115. vals := make([]*types.Validator, size)
  116. for i := 0; i < size; i++ {
  117. vals[i] = types.NewValidator(ed25519.GenPrivKey().PubKey(), 10)
  118. }
  119. return types.NewValidatorSet(vals)
  120. }
  121. func makeConsensusParams(
  122. blockBytes, blockGas int64,
  123. blockTimeIotaMs int64,
  124. evidenceAge int64,
  125. ) types.ConsensusParams {
  126. return types.ConsensusParams{
  127. Block: types.BlockParams{
  128. MaxBytes: blockBytes,
  129. MaxGas: blockGas,
  130. TimeIotaMs: blockTimeIotaMs,
  131. },
  132. Evidence: types.EvidenceParams{
  133. MaxAge: evidenceAge,
  134. },
  135. }
  136. }
  137. func makeHeaderPartsResponsesValPubKeyChange(state sm.State, pubkey crypto.PubKey) (types.Header, types.BlockID, *sm.ABCIResponses) {
  138. block := makeBlock(state, state.LastBlockHeight+1)
  139. abciResponses := &sm.ABCIResponses{
  140. EndBlock: &abci.ResponseEndBlock{ValidatorUpdates: nil},
  141. }
  142. // If the pubkey is new, remove the old and add the new.
  143. _, val := state.NextValidators.GetByIndex(0)
  144. if !bytes.Equal(pubkey.Bytes(), val.PubKey.Bytes()) {
  145. abciResponses.EndBlock = &abci.ResponseEndBlock{
  146. ValidatorUpdates: []abci.ValidatorUpdate{
  147. types.TM2PB.NewValidatorUpdate(val.PubKey, 0),
  148. types.TM2PB.NewValidatorUpdate(pubkey, 10),
  149. },
  150. }
  151. }
  152. return block.Header, types.BlockID{Hash: block.Hash(), PartsHeader: types.PartSetHeader{}}, abciResponses
  153. }
  154. func makeHeaderPartsResponsesValPowerChange(state sm.State, power int64) (types.Header, types.BlockID, *sm.ABCIResponses) {
  155. block := makeBlock(state, state.LastBlockHeight+1)
  156. abciResponses := &sm.ABCIResponses{
  157. EndBlock: &abci.ResponseEndBlock{ValidatorUpdates: nil},
  158. }
  159. // If the pubkey is new, remove the old and add the new.
  160. _, val := state.NextValidators.GetByIndex(0)
  161. if val.VotingPower != power {
  162. abciResponses.EndBlock = &abci.ResponseEndBlock{
  163. ValidatorUpdates: []abci.ValidatorUpdate{
  164. types.TM2PB.NewValidatorUpdate(val.PubKey, power),
  165. },
  166. }
  167. }
  168. return block.Header, types.BlockID{Hash: block.Hash(), PartsHeader: types.PartSetHeader{}}, abciResponses
  169. }
  170. func makeHeaderPartsResponsesParams(state sm.State, params types.ConsensusParams) (types.Header, types.BlockID, *sm.ABCIResponses) {
  171. block := makeBlock(state, state.LastBlockHeight+1)
  172. abciResponses := &sm.ABCIResponses{
  173. EndBlock: &abci.ResponseEndBlock{ConsensusParamUpdates: types.TM2PB.ConsensusParams(&params)},
  174. }
  175. return block.Header, types.BlockID{Hash: block.Hash(), PartsHeader: types.PartSetHeader{}}, abciResponses
  176. }
  177. func randomGenesisDoc() *types.GenesisDoc {
  178. pubkey := ed25519.GenPrivKey().PubKey()
  179. return &types.GenesisDoc{
  180. GenesisTime: tmtime.Now(),
  181. ChainID: "abc",
  182. Validators: []types.GenesisValidator{
  183. {
  184. Address: pubkey.Address(),
  185. PubKey: pubkey,
  186. Power: 10,
  187. Name: "myval",
  188. },
  189. },
  190. ConsensusParams: types.DefaultConsensusParams(),
  191. }
  192. }
  193. //----------------------------------------------------------------------------
  194. type testApp struct {
  195. abci.BaseApplication
  196. CommitVotes []abci.VoteInfo
  197. ByzantineValidators []abci.Evidence
  198. ValidatorUpdates []abci.ValidatorUpdate
  199. }
  200. var _ abci.Application = (*testApp)(nil)
  201. func (app *testApp) Info(req abci.RequestInfo) (resInfo abci.ResponseInfo) {
  202. return abci.ResponseInfo{}
  203. }
  204. func (app *testApp) BeginBlock(req abci.RequestBeginBlock) abci.ResponseBeginBlock {
  205. app.CommitVotes = req.LastCommitInfo.Votes
  206. app.ByzantineValidators = req.ByzantineValidators
  207. return abci.ResponseBeginBlock{}
  208. }
  209. func (app *testApp) EndBlock(req abci.RequestEndBlock) abci.ResponseEndBlock {
  210. return abci.ResponseEndBlock{ValidatorUpdates: app.ValidatorUpdates}
  211. }
  212. func (app *testApp) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx {
  213. return abci.ResponseDeliverTx{Events: []abci.Event{}}
  214. }
  215. func (app *testApp) CheckTx(req abci.RequestCheckTx) abci.ResponseCheckTx {
  216. return abci.ResponseCheckTx{}
  217. }
  218. func (app *testApp) Commit() abci.ResponseCommit {
  219. return abci.ResponseCommit{}
  220. }
  221. func (app *testApp) Query(reqQuery abci.RequestQuery) (resQuery abci.ResponseQuery) {
  222. return
  223. }