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.

472 lines
15 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
6 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
  1. package state_test
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. "github.com/stretchr/testify/mock"
  8. "github.com/stretchr/testify/require"
  9. dbm "github.com/tendermint/tm-db"
  10. abciclient "github.com/tendermint/tendermint/abci/client"
  11. abci "github.com/tendermint/tendermint/abci/types"
  12. "github.com/tendermint/tendermint/crypto"
  13. "github.com/tendermint/tendermint/crypto/ed25519"
  14. "github.com/tendermint/tendermint/crypto/encoding"
  15. "github.com/tendermint/tendermint/crypto/tmhash"
  16. "github.com/tendermint/tendermint/internal/eventbus"
  17. mmock "github.com/tendermint/tendermint/internal/mempool/mock"
  18. "github.com/tendermint/tendermint/internal/proxy"
  19. sm "github.com/tendermint/tendermint/internal/state"
  20. "github.com/tendermint/tendermint/internal/state/mocks"
  21. sf "github.com/tendermint/tendermint/internal/state/test/factory"
  22. "github.com/tendermint/tendermint/internal/store"
  23. "github.com/tendermint/tendermint/libs/log"
  24. "github.com/tendermint/tendermint/libs/pubsub"
  25. tmtime "github.com/tendermint/tendermint/libs/time"
  26. "github.com/tendermint/tendermint/types"
  27. "github.com/tendermint/tendermint/version"
  28. )
  29. var (
  30. chainID = "execution_chain"
  31. testPartSize uint32 = 65536
  32. )
  33. func TestApplyBlock(t *testing.T) {
  34. app := &testApp{}
  35. cc := abciclient.NewLocalCreator(app)
  36. logger := log.TestingLogger()
  37. proxyApp := proxy.NewAppConns(cc, logger, proxy.NopMetrics())
  38. err := proxyApp.Start()
  39. require.Nil(t, err)
  40. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  41. state, stateDB, _ := makeState(1, 1)
  42. stateStore := sm.NewStore(stateDB)
  43. blockStore := store.NewBlockStore(dbm.NewMemDB())
  44. blockExec := sm.NewBlockExecutor(stateStore, logger, proxyApp.Consensus(),
  45. mmock.Mempool{}, sm.EmptyEvidencePool{}, blockStore)
  46. block := sf.MakeBlock(state, 1, new(types.Commit))
  47. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
  48. state, err = blockExec.ApplyBlock(state, blockID, block)
  49. require.Nil(t, err)
  50. // TODO check state and mempool
  51. assert.EqualValues(t, 1, state.Version.Consensus.App, "App version wasn't updated")
  52. }
  53. // TestBeginBlockValidators ensures we send absent validators list.
  54. func TestBeginBlockValidators(t *testing.T) {
  55. app := &testApp{}
  56. cc := abciclient.NewLocalCreator(app)
  57. proxyApp := proxy.NewAppConns(cc, log.TestingLogger(), proxy.NopMetrics())
  58. err := proxyApp.Start()
  59. require.Nil(t, err)
  60. defer proxyApp.Stop() //nolint:errcheck // no need to check error again
  61. state, stateDB, _ := makeState(2, 2)
  62. stateStore := sm.NewStore(stateDB)
  63. prevHash := state.LastBlockID.Hash
  64. prevParts := types.PartSetHeader{}
  65. prevBlockID := types.BlockID{Hash: prevHash, PartSetHeader: prevParts}
  66. var (
  67. now = tmtime.Now()
  68. commitSig0 = types.NewCommitSigForBlock(
  69. []byte("Signature1"),
  70. state.Validators.Validators[0].Address,
  71. now)
  72. commitSig1 = types.NewCommitSigForBlock(
  73. []byte("Signature2"),
  74. state.Validators.Validators[1].Address,
  75. now)
  76. absentSig = types.NewCommitSigAbsent()
  77. )
  78. testCases := []struct {
  79. desc string
  80. lastCommitSigs []types.CommitSig
  81. expectedAbsentValidators []int
  82. }{
  83. {"none absent", []types.CommitSig{commitSig0, commitSig1}, []int{}},
  84. {"one absent", []types.CommitSig{commitSig0, absentSig}, []int{1}},
  85. {"multiple absent", []types.CommitSig{absentSig, absentSig}, []int{0, 1}},
  86. }
  87. for _, tc := range testCases {
  88. lastCommit := types.NewCommit(1, 0, prevBlockID, tc.lastCommitSigs)
  89. // block for height 2
  90. block := sf.MakeBlock(state, 2, lastCommit)
  91. _, err = sm.ExecCommitBlock(nil, proxyApp.Consensus(), block, log.TestingLogger(), stateStore, 1, state)
  92. require.Nil(t, err, tc.desc)
  93. // -> app receives a list of validators with a bool indicating if they signed
  94. ctr := 0
  95. for i, v := range app.CommitVotes {
  96. if ctr < len(tc.expectedAbsentValidators) &&
  97. tc.expectedAbsentValidators[ctr] == i {
  98. assert.False(t, v.SignedLastBlock)
  99. ctr++
  100. } else {
  101. assert.True(t, v.SignedLastBlock)
  102. }
  103. }
  104. }
  105. }
  106. // TestBeginBlockByzantineValidators ensures we send byzantine validators list.
  107. func TestBeginBlockByzantineValidators(t *testing.T) {
  108. app := &testApp{}
  109. cc := abciclient.NewLocalCreator(app)
  110. proxyApp := proxy.NewAppConns(cc, log.TestingLogger(), proxy.NopMetrics())
  111. err := proxyApp.Start()
  112. require.Nil(t, err)
  113. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  114. state, stateDB, privVals := makeState(1, 1)
  115. stateStore := sm.NewStore(stateDB)
  116. defaultEvidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  117. privVal := privVals[state.Validators.Validators[0].Address.String()]
  118. blockID := makeBlockID([]byte("headerhash"), 1000, []byte("partshash"))
  119. header := &types.Header{
  120. Version: version.Consensus{Block: version.BlockProtocol, App: 1},
  121. ChainID: state.ChainID,
  122. Height: 10,
  123. Time: defaultEvidenceTime,
  124. LastBlockID: blockID,
  125. LastCommitHash: crypto.CRandBytes(tmhash.Size),
  126. DataHash: crypto.CRandBytes(tmhash.Size),
  127. ValidatorsHash: state.Validators.Hash(),
  128. NextValidatorsHash: state.Validators.Hash(),
  129. ConsensusHash: crypto.CRandBytes(tmhash.Size),
  130. AppHash: crypto.CRandBytes(tmhash.Size),
  131. LastResultsHash: crypto.CRandBytes(tmhash.Size),
  132. EvidenceHash: crypto.CRandBytes(tmhash.Size),
  133. ProposerAddress: crypto.CRandBytes(crypto.AddressSize),
  134. }
  135. // we don't need to worry about validating the evidence as long as they pass validate basic
  136. dve := types.NewMockDuplicateVoteEvidenceWithValidator(3, defaultEvidenceTime, privVal, state.ChainID)
  137. dve.ValidatorPower = 1000
  138. lcae := &types.LightClientAttackEvidence{
  139. ConflictingBlock: &types.LightBlock{
  140. SignedHeader: &types.SignedHeader{
  141. Header: header,
  142. Commit: types.NewCommit(10, 0, makeBlockID(header.Hash(), 100, []byte("partshash")), []types.CommitSig{{
  143. BlockIDFlag: types.BlockIDFlagNil,
  144. ValidatorAddress: crypto.AddressHash([]byte("validator_address")),
  145. Timestamp: defaultEvidenceTime,
  146. Signature: crypto.CRandBytes(types.MaxSignatureSize),
  147. }}),
  148. },
  149. ValidatorSet: state.Validators,
  150. },
  151. CommonHeight: 8,
  152. ByzantineValidators: []*types.Validator{state.Validators.Validators[0]},
  153. TotalVotingPower: 12,
  154. Timestamp: defaultEvidenceTime,
  155. }
  156. ev := []types.Evidence{dve, lcae}
  157. abciEv := []abci.Evidence{
  158. {
  159. Type: abci.EvidenceType_DUPLICATE_VOTE,
  160. Height: 3,
  161. Time: defaultEvidenceTime,
  162. Validator: types.TM2PB.Validator(state.Validators.Validators[0]),
  163. TotalVotingPower: 10,
  164. },
  165. {
  166. Type: abci.EvidenceType_LIGHT_CLIENT_ATTACK,
  167. Height: 8,
  168. Time: defaultEvidenceTime,
  169. Validator: types.TM2PB.Validator(state.Validators.Validators[0]),
  170. TotalVotingPower: 12,
  171. },
  172. }
  173. evpool := &mocks.EvidencePool{}
  174. evpool.On("PendingEvidence", mock.AnythingOfType("int64")).Return(ev, int64(100))
  175. evpool.On("Update", mock.AnythingOfType("state.State"), mock.AnythingOfType("types.EvidenceList")).Return()
  176. evpool.On("CheckEvidence", mock.AnythingOfType("types.EvidenceList")).Return(nil)
  177. blockStore := store.NewBlockStore(dbm.NewMemDB())
  178. blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyApp.Consensus(),
  179. mmock.Mempool{}, evpool, blockStore)
  180. block := sf.MakeBlock(state, 1, new(types.Commit))
  181. block.Evidence = types.EvidenceData{Evidence: ev}
  182. block.Header.EvidenceHash = block.Evidence.Hash()
  183. blockID = types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
  184. _, err = blockExec.ApplyBlock(state, blockID, block)
  185. require.Nil(t, err)
  186. // TODO check state and mempool
  187. assert.Equal(t, abciEv, app.ByzantineValidators)
  188. }
  189. func TestValidateValidatorUpdates(t *testing.T) {
  190. pubkey1 := ed25519.GenPrivKey().PubKey()
  191. pubkey2 := ed25519.GenPrivKey().PubKey()
  192. pk1, err := encoding.PubKeyToProto(pubkey1)
  193. assert.NoError(t, err)
  194. pk2, err := encoding.PubKeyToProto(pubkey2)
  195. assert.NoError(t, err)
  196. defaultValidatorParams := types.ValidatorParams{PubKeyTypes: []string{types.ABCIPubKeyTypeEd25519}}
  197. testCases := []struct {
  198. name string
  199. abciUpdates []abci.ValidatorUpdate
  200. validatorParams types.ValidatorParams
  201. shouldErr bool
  202. }{
  203. {
  204. "adding a validator is OK",
  205. []abci.ValidatorUpdate{{PubKey: pk2, Power: 20}},
  206. defaultValidatorParams,
  207. false,
  208. },
  209. {
  210. "updating a validator is OK",
  211. []abci.ValidatorUpdate{{PubKey: pk1, Power: 20}},
  212. defaultValidatorParams,
  213. false,
  214. },
  215. {
  216. "removing a validator is OK",
  217. []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}},
  218. defaultValidatorParams,
  219. false,
  220. },
  221. {
  222. "adding a validator with negative power results in error",
  223. []abci.ValidatorUpdate{{PubKey: pk2, Power: -100}},
  224. defaultValidatorParams,
  225. true,
  226. },
  227. }
  228. for _, tc := range testCases {
  229. tc := tc
  230. t.Run(tc.name, func(t *testing.T) {
  231. err := sm.ValidateValidatorUpdates(tc.abciUpdates, tc.validatorParams)
  232. if tc.shouldErr {
  233. assert.Error(t, err)
  234. } else {
  235. assert.NoError(t, err)
  236. }
  237. })
  238. }
  239. }
  240. func TestUpdateValidators(t *testing.T) {
  241. pubkey1 := ed25519.GenPrivKey().PubKey()
  242. val1 := types.NewValidator(pubkey1, 10)
  243. pubkey2 := ed25519.GenPrivKey().PubKey()
  244. val2 := types.NewValidator(pubkey2, 20)
  245. pk, err := encoding.PubKeyToProto(pubkey1)
  246. require.NoError(t, err)
  247. pk2, err := encoding.PubKeyToProto(pubkey2)
  248. require.NoError(t, err)
  249. testCases := []struct {
  250. name string
  251. currentSet *types.ValidatorSet
  252. abciUpdates []abci.ValidatorUpdate
  253. resultingSet *types.ValidatorSet
  254. shouldErr bool
  255. }{
  256. {
  257. "adding a validator is OK",
  258. types.NewValidatorSet([]*types.Validator{val1}),
  259. []abci.ValidatorUpdate{{PubKey: pk2, Power: 20}},
  260. types.NewValidatorSet([]*types.Validator{val1, val2}),
  261. false,
  262. },
  263. {
  264. "updating a validator is OK",
  265. types.NewValidatorSet([]*types.Validator{val1}),
  266. []abci.ValidatorUpdate{{PubKey: pk, Power: 20}},
  267. types.NewValidatorSet([]*types.Validator{types.NewValidator(pubkey1, 20)}),
  268. false,
  269. },
  270. {
  271. "removing a validator is OK",
  272. types.NewValidatorSet([]*types.Validator{val1, val2}),
  273. []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}},
  274. types.NewValidatorSet([]*types.Validator{val1}),
  275. false,
  276. },
  277. {
  278. "removing a non-existing validator results in error",
  279. types.NewValidatorSet([]*types.Validator{val1}),
  280. []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}},
  281. types.NewValidatorSet([]*types.Validator{val1}),
  282. true,
  283. },
  284. }
  285. for _, tc := range testCases {
  286. tc := tc
  287. t.Run(tc.name, func(t *testing.T) {
  288. updates, err := types.PB2TM.ValidatorUpdates(tc.abciUpdates)
  289. assert.NoError(t, err)
  290. err = tc.currentSet.UpdateWithChangeSet(updates)
  291. if tc.shouldErr {
  292. assert.Error(t, err)
  293. } else {
  294. assert.NoError(t, err)
  295. require.Equal(t, tc.resultingSet.Size(), tc.currentSet.Size())
  296. assert.Equal(t, tc.resultingSet.TotalVotingPower(), tc.currentSet.TotalVotingPower())
  297. assert.Equal(t, tc.resultingSet.Validators[0].Address, tc.currentSet.Validators[0].Address)
  298. if tc.resultingSet.Size() > 1 {
  299. assert.Equal(t, tc.resultingSet.Validators[1].Address, tc.currentSet.Validators[1].Address)
  300. }
  301. }
  302. })
  303. }
  304. }
  305. // TestEndBlockValidatorUpdates ensures we update validator set and send an event.
  306. func TestEndBlockValidatorUpdates(t *testing.T) {
  307. app := &testApp{}
  308. cc := abciclient.NewLocalCreator(app)
  309. logger := log.TestingLogger()
  310. proxyApp := proxy.NewAppConns(cc, logger, proxy.NopMetrics())
  311. err := proxyApp.Start()
  312. require.Nil(t, err)
  313. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  314. state, stateDB, _ := makeState(1, 1)
  315. stateStore := sm.NewStore(stateDB)
  316. blockStore := store.NewBlockStore(dbm.NewMemDB())
  317. blockExec := sm.NewBlockExecutor(
  318. stateStore,
  319. logger,
  320. proxyApp.Consensus(),
  321. mmock.Mempool{},
  322. sm.EmptyEvidencePool{},
  323. blockStore,
  324. )
  325. eventBus := eventbus.NewDefault(logger)
  326. err = eventBus.Start()
  327. require.NoError(t, err)
  328. defer eventBus.Stop() //nolint:errcheck // ignore for tests
  329. blockExec.SetEventBus(eventBus)
  330. updatesSub, err := eventBus.SubscribeWithArgs(context.Background(), pubsub.SubscribeArgs{
  331. ClientID: "TestEndBlockValidatorUpdates",
  332. Query: types.EventQueryValidatorSetUpdates,
  333. })
  334. require.NoError(t, err)
  335. block := sf.MakeBlock(state, 1, new(types.Commit))
  336. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
  337. pubkey := ed25519.GenPrivKey().PubKey()
  338. pk, err := encoding.PubKeyToProto(pubkey)
  339. require.NoError(t, err)
  340. app.ValidatorUpdates = []abci.ValidatorUpdate{
  341. {PubKey: pk, Power: 10},
  342. }
  343. state, err = blockExec.ApplyBlock(state, blockID, block)
  344. require.Nil(t, err)
  345. // test new validator was added to NextValidators
  346. if assert.Equal(t, state.Validators.Size()+1, state.NextValidators.Size()) {
  347. idx, _ := state.NextValidators.GetByAddress(pubkey.Address())
  348. if idx < 0 {
  349. t.Fatalf("can't find address %v in the set %v", pubkey.Address(), state.NextValidators)
  350. }
  351. }
  352. // test we threw an event
  353. ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
  354. defer cancel()
  355. msg, err := updatesSub.Next(ctx)
  356. require.NoError(t, err)
  357. event, ok := msg.Data().(types.EventDataValidatorSetUpdates)
  358. require.True(t, ok, "Expected event of type EventDataValidatorSetUpdates, got %T", msg.Data())
  359. if assert.NotEmpty(t, event.ValidatorUpdates) {
  360. assert.Equal(t, pubkey, event.ValidatorUpdates[0].PubKey)
  361. assert.EqualValues(t, 10, event.ValidatorUpdates[0].VotingPower)
  362. }
  363. }
  364. // TestEndBlockValidatorUpdatesResultingInEmptySet checks that processing validator updates that
  365. // would result in empty set causes no panic, an error is raised and NextValidators is not updated
  366. func TestEndBlockValidatorUpdatesResultingInEmptySet(t *testing.T) {
  367. app := &testApp{}
  368. cc := abciclient.NewLocalCreator(app)
  369. logger := log.TestingLogger()
  370. proxyApp := proxy.NewAppConns(cc, logger, proxy.NopMetrics())
  371. err := proxyApp.Start()
  372. require.Nil(t, err)
  373. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  374. state, stateDB, _ := makeState(1, 1)
  375. stateStore := sm.NewStore(stateDB)
  376. blockStore := store.NewBlockStore(dbm.NewMemDB())
  377. blockExec := sm.NewBlockExecutor(
  378. stateStore,
  379. log.TestingLogger(),
  380. proxyApp.Consensus(),
  381. mmock.Mempool{},
  382. sm.EmptyEvidencePool{},
  383. blockStore,
  384. )
  385. block := sf.MakeBlock(state, 1, new(types.Commit))
  386. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
  387. vp, err := encoding.PubKeyToProto(state.Validators.Validators[0].PubKey)
  388. require.NoError(t, err)
  389. // Remove the only validator
  390. app.ValidatorUpdates = []abci.ValidatorUpdate{
  391. {PubKey: vp, Power: 0},
  392. }
  393. assert.NotPanics(t, func() { state, err = blockExec.ApplyBlock(state, blockID, block) })
  394. assert.NotNil(t, err)
  395. assert.NotEmpty(t, state.NextValidators.Validators)
  396. }
  397. func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) types.BlockID {
  398. var (
  399. h = make([]byte, tmhash.Size)
  400. psH = make([]byte, tmhash.Size)
  401. )
  402. copy(h, hash)
  403. copy(psH, partSetHash)
  404. return types.BlockID{
  405. Hash: h,
  406. PartSetHeader: types.PartSetHeader{
  407. Total: partSetSize,
  408. Hash: psH,
  409. },
  410. }
  411. }