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.

280 lines
8.5 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
  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 makeVote(height int64, blockID types.BlockID, valSet *types.ValidatorSet, privVal types.PrivValidator) (*types.Vote, error) {
  63. addr := privVal.GetPubKey().Address()
  64. idx, _ := valSet.GetByAddress(addr)
  65. vote := &types.Vote{
  66. ValidatorAddress: addr,
  67. ValidatorIndex: idx,
  68. Height: height,
  69. Round: 0,
  70. Timestamp: tmtime.Now(),
  71. Type: types.PrecommitType,
  72. BlockID: blockID,
  73. }
  74. if err := privVal.SignVote(chainID, vote); err != nil {
  75. return nil, err
  76. }
  77. return vote, nil
  78. }
  79. func makeValidCommit(height int64, blockID types.BlockID, vals *types.ValidatorSet, privVals map[string]types.PrivValidator) (*types.Commit, error) {
  80. sigs := make([]*types.CommitSig, 0)
  81. for i := 0; i < vals.Size(); i++ {
  82. _, val := vals.GetByIndex(i)
  83. vote, err := makeVote(height, blockID, vals, privVals[val.Address.String()])
  84. if err != nil {
  85. return nil, err
  86. }
  87. sigs = append(sigs, vote.CommitSig())
  88. }
  89. return types.NewCommit(blockID, sigs), nil
  90. }
  91. // make some bogus txs
  92. func makeTxs(height int64) (txs []types.Tx) {
  93. for i := 0; i < nTxsPerBlock; i++ {
  94. txs = append(txs, types.Tx([]byte{byte(height), byte(i)}))
  95. }
  96. return txs
  97. }
  98. func makeState(nVals, height int) (sm.State, dbm.DB, map[string]types.PrivValidator) {
  99. vals := make([]types.GenesisValidator, nVals)
  100. privVals := make(map[string]types.PrivValidator, nVals)
  101. for i := 0; i < nVals; i++ {
  102. secret := []byte(fmt.Sprintf("test%d", i))
  103. pk := ed25519.GenPrivKeyFromSecret(secret)
  104. valAddr := pk.PubKey().Address()
  105. vals[i] = types.GenesisValidator{
  106. Address: valAddr,
  107. PubKey: pk.PubKey(),
  108. Power: 1000,
  109. Name: fmt.Sprintf("test%d", i),
  110. }
  111. privVals[valAddr.String()] = types.NewMockPVWithParams(pk, false, false)
  112. }
  113. s, _ := sm.MakeGenesisState(&types.GenesisDoc{
  114. ChainID: chainID,
  115. Validators: vals,
  116. AppHash: nil,
  117. })
  118. stateDB := dbm.NewMemDB()
  119. sm.SaveState(stateDB, s)
  120. for i := 1; i < height; i++ {
  121. s.LastBlockHeight++
  122. s.LastValidators = s.Validators.Copy()
  123. sm.SaveState(stateDB, s)
  124. }
  125. return s, stateDB, privVals
  126. }
  127. func makeBlock(state sm.State, height int64) *types.Block {
  128. block, _ := state.MakeBlock(height, makeTxs(state.LastBlockHeight), new(types.Commit), nil, state.Validators.GetProposer().Address)
  129. return block
  130. }
  131. func genValSet(size int) *types.ValidatorSet {
  132. vals := make([]*types.Validator, size)
  133. for i := 0; i < size; i++ {
  134. vals[i] = types.NewValidator(ed25519.GenPrivKey().PubKey(), 10)
  135. }
  136. return types.NewValidatorSet(vals)
  137. }
  138. func makeConsensusParams(
  139. blockBytes, blockGas int64,
  140. blockTimeIotaMs int64,
  141. evidenceAge int64,
  142. ) types.ConsensusParams {
  143. return types.ConsensusParams{
  144. Block: types.BlockParams{
  145. MaxBytes: blockBytes,
  146. MaxGas: blockGas,
  147. TimeIotaMs: blockTimeIotaMs,
  148. },
  149. Evidence: types.EvidenceParams{
  150. MaxAge: evidenceAge,
  151. },
  152. }
  153. }
  154. func makeHeaderPartsResponsesValPubKeyChange(state sm.State, pubkey crypto.PubKey) (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 !bytes.Equal(pubkey.Bytes(), val.PubKey.Bytes()) {
  162. abciResponses.EndBlock = &abci.ResponseEndBlock{
  163. ValidatorUpdates: []abci.ValidatorUpdate{
  164. types.TM2PB.NewValidatorUpdate(val.PubKey, 0),
  165. types.TM2PB.NewValidatorUpdate(pubkey, 10),
  166. },
  167. }
  168. }
  169. return block.Header, types.BlockID{Hash: block.Hash(), PartsHeader: types.PartSetHeader{}}, abciResponses
  170. }
  171. func makeHeaderPartsResponsesValPowerChange(state sm.State, power int64) (types.Header, types.BlockID, *sm.ABCIResponses) {
  172. block := makeBlock(state, state.LastBlockHeight+1)
  173. abciResponses := &sm.ABCIResponses{
  174. EndBlock: &abci.ResponseEndBlock{ValidatorUpdates: nil},
  175. }
  176. // If the pubkey is new, remove the old and add the new.
  177. _, val := state.NextValidators.GetByIndex(0)
  178. if val.VotingPower != power {
  179. abciResponses.EndBlock = &abci.ResponseEndBlock{
  180. ValidatorUpdates: []abci.ValidatorUpdate{
  181. types.TM2PB.NewValidatorUpdate(val.PubKey, power),
  182. },
  183. }
  184. }
  185. return block.Header, types.BlockID{Hash: block.Hash(), PartsHeader: types.PartSetHeader{}}, abciResponses
  186. }
  187. func makeHeaderPartsResponsesParams(state sm.State, params types.ConsensusParams) (types.Header, types.BlockID, *sm.ABCIResponses) {
  188. block := makeBlock(state, state.LastBlockHeight+1)
  189. abciResponses := &sm.ABCIResponses{
  190. EndBlock: &abci.ResponseEndBlock{ConsensusParamUpdates: types.TM2PB.ConsensusParams(&params)},
  191. }
  192. return block.Header, types.BlockID{Hash: block.Hash(), PartsHeader: types.PartSetHeader{}}, abciResponses
  193. }
  194. func randomGenesisDoc() *types.GenesisDoc {
  195. pubkey := ed25519.GenPrivKey().PubKey()
  196. return &types.GenesisDoc{
  197. GenesisTime: tmtime.Now(),
  198. ChainID: "abc",
  199. Validators: []types.GenesisValidator{
  200. {
  201. Address: pubkey.Address(),
  202. PubKey: pubkey,
  203. Power: 10,
  204. Name: "myval",
  205. },
  206. },
  207. ConsensusParams: types.DefaultConsensusParams(),
  208. }
  209. }
  210. //----------------------------------------------------------------------------
  211. type testApp struct {
  212. abci.BaseApplication
  213. CommitVotes []abci.VoteInfo
  214. ByzantineValidators []abci.Evidence
  215. ValidatorUpdates []abci.ValidatorUpdate
  216. }
  217. var _ abci.Application = (*testApp)(nil)
  218. func (app *testApp) Info(req abci.RequestInfo) (resInfo abci.ResponseInfo) {
  219. return abci.ResponseInfo{}
  220. }
  221. func (app *testApp) BeginBlock(req abci.RequestBeginBlock) abci.ResponseBeginBlock {
  222. app.CommitVotes = req.LastCommitInfo.Votes
  223. app.ByzantineValidators = req.ByzantineValidators
  224. return abci.ResponseBeginBlock{}
  225. }
  226. func (app *testApp) EndBlock(req abci.RequestEndBlock) abci.ResponseEndBlock {
  227. return abci.ResponseEndBlock{ValidatorUpdates: app.ValidatorUpdates}
  228. }
  229. func (app *testApp) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx {
  230. return abci.ResponseDeliverTx{Events: []abci.Event{}}
  231. }
  232. func (app *testApp) CheckTx(req abci.RequestCheckTx) abci.ResponseCheckTx {
  233. return abci.ResponseCheckTx{}
  234. }
  235. func (app *testApp) Commit() abci.ResponseCommit {
  236. return abci.ResponseCommit{}
  237. }
  238. func (app *testApp) Query(reqQuery abci.RequestQuery) (resQuery abci.ResponseQuery) {
  239. return
  240. }