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.

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