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.

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