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.

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