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.

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