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.

385 lines
10 KiB

blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
abci: Refactor tagging events using list of lists (#3643) ## PR This PR introduces a fundamental breaking change to the structure of ABCI response and tx tags and the way they're processed. Namely, the SDK can support more complex and aggregated events for distribution and slashing. In addition, block responses can include duplicate keys in events. Implement new Event type. An event has a type and a list of KV pairs (ie. list-of-lists). Typical events may look like: "rewards": [{"amount": "5000uatom", "validator": "...", "recipient": "..."}] "sender": [{"address": "...", "balance": "100uatom"}] The events are indexed by {even.type}.{even.attribute[i].key}/.... In this case a client would subscribe or query for rewards.recipient='...' ABCI response types and related types now include Events []Event instead of Tags []cmn.KVPair. PubSub logic now publishes/matches against map[string][]string instead of map[string]string to support duplicate keys in response events (from #1385). A match is successful if the value is found in the slice of strings. closes: #1859 closes: #2905 ## Commits: * Implement Event ABCI type and updates responses to use events * Update messages_test.go * Update kvstore.go * Update event_bus.go * Update subscription.go * Update pubsub.go * Update kvstore.go * Update query logic to handle slice of strings in events * Update Empty#Matches and unit tests * Update pubsub logic * Update EventBus#Publish * Update kv tx indexer * Update godocs * Update ResultEvent to use slice of strings; update RPC * Update more tests * Update abci.md * Check for key in validateAndStringifyEvents * Fix KV indexer to skip empty keys * Fix linting errors * Update CHANGELOG_PENDING.md * Update docs/spec/abci/abci.md Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update abci/types/types.proto Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update docs/spec/abci/abci.md Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update libs/pubsub/query/query.go Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update match function to match if ANY value matches * Implement TestSubscribeDuplicateKeys * Update TestMatches to include multi-key test cases * Update events.go * Update Query interface godoc * Update match godoc * Add godoc for matchValue * DRY-up tx indexing * Return error from PublishWithEvents in EventBus#Publish * Update PublishEventNewBlockHeader to return an error * Fix build * Update events doc in ABCI * Update ABCI events godoc * Implement TestEventBusPublishEventTxDuplicateKeys * Update TestSubscribeDuplicateKeys to be table-driven * Remove mod file * Remove markdown from events godoc * Implement TestTxSearchDeprecatedIndexing test
6 years ago
  1. package v0
  2. import (
  3. "os"
  4. "sort"
  5. "testing"
  6. "time"
  7. "github.com/pkg/errors"
  8. "github.com/tendermint/tendermint/store"
  9. "github.com/stretchr/testify/assert"
  10. abci "github.com/tendermint/tendermint/abci/types"
  11. cfg "github.com/tendermint/tendermint/config"
  12. "github.com/tendermint/tendermint/libs/log"
  13. "github.com/tendermint/tendermint/mock"
  14. "github.com/tendermint/tendermint/p2p"
  15. "github.com/tendermint/tendermint/proxy"
  16. sm "github.com/tendermint/tendermint/state"
  17. "github.com/tendermint/tendermint/types"
  18. tmtime "github.com/tendermint/tendermint/types/time"
  19. dbm "github.com/tendermint/tm-db"
  20. )
  21. var config *cfg.Config
  22. func randGenesisDoc(numValidators int, randPower bool, minPower int64) (*types.GenesisDoc, []types.PrivValidator) {
  23. validators := make([]types.GenesisValidator, numValidators)
  24. privValidators := make([]types.PrivValidator, numValidators)
  25. for i := 0; i < numValidators; i++ {
  26. val, privVal := types.RandValidator(randPower, minPower)
  27. validators[i] = types.GenesisValidator{
  28. PubKey: val.PubKey,
  29. Power: val.VotingPower,
  30. }
  31. privValidators[i] = privVal
  32. }
  33. sort.Sort(types.PrivValidatorsByAddress(privValidators))
  34. return &types.GenesisDoc{
  35. GenesisTime: tmtime.Now(),
  36. ChainID: config.ChainID(),
  37. Validators: validators,
  38. }, privValidators
  39. }
  40. type BlockchainReactorPair struct {
  41. reactor *BlockchainReactor
  42. app proxy.AppConns
  43. }
  44. func newBlockchainReactor(
  45. logger log.Logger,
  46. genDoc *types.GenesisDoc,
  47. privVals []types.PrivValidator,
  48. maxBlockHeight int64) BlockchainReactorPair {
  49. if len(privVals) != 1 {
  50. panic("only support one validator")
  51. }
  52. app := &testApp{}
  53. cc := proxy.NewLocalClientCreator(app)
  54. proxyApp := proxy.NewAppConns(cc)
  55. err := proxyApp.Start()
  56. if err != nil {
  57. panic(errors.Wrap(err, "error start app"))
  58. }
  59. blockDB := dbm.NewMemDB()
  60. stateDB := dbm.NewMemDB()
  61. blockStore := store.NewBlockStore(blockDB)
  62. state, err := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  63. if err != nil {
  64. panic(errors.Wrap(err, "error constructing state from genesis file"))
  65. }
  66. // Make the BlockchainReactor itself.
  67. // NOTE we have to create and commit the blocks first because
  68. // pool.height is determined from the store.
  69. fastSync := true
  70. db := dbm.NewMemDB()
  71. blockExec := sm.NewBlockExecutor(db, log.TestingLogger(), proxyApp.Consensus(),
  72. mock.Mempool{}, sm.MockEvidencePool{})
  73. sm.SaveState(db, state)
  74. // let's add some blocks in
  75. for blockHeight := int64(1); blockHeight <= maxBlockHeight; blockHeight++ {
  76. lastCommit := types.NewCommit(types.BlockID{}, nil)
  77. if blockHeight > 1 {
  78. lastBlockMeta := blockStore.LoadBlockMeta(blockHeight - 1)
  79. lastBlock := blockStore.LoadBlock(blockHeight - 1)
  80. vote, err := types.MakeVote(
  81. lastBlock.Header.Height,
  82. lastBlockMeta.BlockID,
  83. state.Validators,
  84. privVals[0],
  85. lastBlock.Header.ChainID)
  86. if err != nil {
  87. panic(err)
  88. }
  89. voteCommitSig := vote.CommitSig()
  90. lastCommit = types.NewCommit(lastBlockMeta.BlockID, []*types.CommitSig{voteCommitSig})
  91. }
  92. thisBlock := makeBlock(blockHeight, state, lastCommit)
  93. thisParts := thisBlock.MakePartSet(types.BlockPartSizeBytes)
  94. blockID := types.BlockID{Hash: thisBlock.Hash(), PartsHeader: thisParts.Header()}
  95. state, err = blockExec.ApplyBlock(state, blockID, thisBlock)
  96. if err != nil {
  97. panic(errors.Wrap(err, "error apply block"))
  98. }
  99. blockStore.SaveBlock(thisBlock, thisParts, lastCommit)
  100. }
  101. bcReactor := NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  102. bcReactor.SetLogger(logger.With("module", "blockchain"))
  103. return BlockchainReactorPair{bcReactor, proxyApp}
  104. }
  105. func TestNoBlockResponse(t *testing.T) {
  106. config = cfg.ResetTestRoot("blockchain_reactor_test")
  107. defer os.RemoveAll(config.RootDir)
  108. genDoc, privVals := randGenesisDoc(1, false, 30)
  109. maxBlockHeight := int64(65)
  110. reactorPairs := make([]BlockchainReactorPair, 2)
  111. reactorPairs[0] = newBlockchainReactor(log.TestingLogger(), genDoc, privVals, maxBlockHeight)
  112. reactorPairs[1] = newBlockchainReactor(log.TestingLogger(), genDoc, privVals, 0)
  113. p2p.MakeConnectedSwitches(config.P2P, 2, func(i int, s *p2p.Switch) *p2p.Switch {
  114. s.AddReactor("BLOCKCHAIN", reactorPairs[i].reactor)
  115. return s
  116. }, p2p.Connect2Switches)
  117. defer func() {
  118. for _, r := range reactorPairs {
  119. r.reactor.Stop()
  120. r.app.Stop()
  121. }
  122. }()
  123. tests := []struct {
  124. height int64
  125. existent bool
  126. }{
  127. {maxBlockHeight + 2, false},
  128. {10, true},
  129. {1, true},
  130. {100, false},
  131. }
  132. for {
  133. if reactorPairs[1].reactor.pool.IsCaughtUp() {
  134. break
  135. }
  136. time.Sleep(10 * time.Millisecond)
  137. }
  138. assert.Equal(t, maxBlockHeight, reactorPairs[0].reactor.store.Height())
  139. for _, tt := range tests {
  140. block := reactorPairs[1].reactor.store.LoadBlock(tt.height)
  141. if tt.existent {
  142. assert.True(t, block != nil)
  143. } else {
  144. assert.True(t, block == nil)
  145. }
  146. }
  147. }
  148. // NOTE: This is too hard to test without
  149. // an easy way to add test peer to switch
  150. // or without significant refactoring of the module.
  151. // Alternatively we could actually dial a TCP conn but
  152. // that seems extreme.
  153. func TestBadBlockStopsPeer(t *testing.T) {
  154. config = cfg.ResetTestRoot("blockchain_reactor_test")
  155. defer os.RemoveAll(config.RootDir)
  156. genDoc, privVals := randGenesisDoc(1, false, 30)
  157. maxBlockHeight := int64(148)
  158. otherChain := newBlockchainReactor(log.TestingLogger(), genDoc, privVals, maxBlockHeight)
  159. defer func() {
  160. otherChain.reactor.Stop()
  161. otherChain.app.Stop()
  162. }()
  163. reactorPairs := make([]BlockchainReactorPair, 4)
  164. reactorPairs[0] = newBlockchainReactor(log.TestingLogger(), genDoc, privVals, maxBlockHeight)
  165. reactorPairs[1] = newBlockchainReactor(log.TestingLogger(), genDoc, privVals, 0)
  166. reactorPairs[2] = newBlockchainReactor(log.TestingLogger(), genDoc, privVals, 0)
  167. reactorPairs[3] = newBlockchainReactor(log.TestingLogger(), genDoc, privVals, 0)
  168. switches := p2p.MakeConnectedSwitches(config.P2P, 4, func(i int, s *p2p.Switch) *p2p.Switch {
  169. s.AddReactor("BLOCKCHAIN", reactorPairs[i].reactor)
  170. return s
  171. }, p2p.Connect2Switches)
  172. defer func() {
  173. for _, r := range reactorPairs {
  174. r.reactor.Stop()
  175. r.app.Stop()
  176. }
  177. }()
  178. for {
  179. if reactorPairs[3].reactor.pool.IsCaughtUp() {
  180. break
  181. }
  182. time.Sleep(1 * time.Second)
  183. }
  184. //at this time, reactors[0-3] is the newest
  185. assert.Equal(t, 3, reactorPairs[1].reactor.Switch.Peers().Size())
  186. //mark reactorPairs[3] is an invalid peer
  187. reactorPairs[3].reactor.store = otherChain.reactor.store
  188. lastReactorPair := newBlockchainReactor(log.TestingLogger(), genDoc, privVals, 0)
  189. reactorPairs = append(reactorPairs, lastReactorPair)
  190. switches = append(switches, p2p.MakeConnectedSwitches(config.P2P, 1, func(i int, s *p2p.Switch) *p2p.Switch {
  191. s.AddReactor("BLOCKCHAIN", reactorPairs[len(reactorPairs)-1].reactor)
  192. return s
  193. }, p2p.Connect2Switches)...)
  194. for i := 0; i < len(reactorPairs)-1; i++ {
  195. p2p.Connect2Switches(switches, i, len(reactorPairs)-1)
  196. }
  197. for {
  198. if lastReactorPair.reactor.pool.IsCaughtUp() || lastReactorPair.reactor.Switch.Peers().Size() == 0 {
  199. break
  200. }
  201. time.Sleep(1 * time.Second)
  202. }
  203. assert.True(t, lastReactorPair.reactor.Switch.Peers().Size() < len(reactorPairs)-1)
  204. }
  205. func TestBcBlockRequestMessageValidateBasic(t *testing.T) {
  206. testCases := []struct {
  207. testName string
  208. requestHeight int64
  209. expectErr bool
  210. }{
  211. {"Valid Request Message", 0, false},
  212. {"Valid Request Message", 1, false},
  213. {"Invalid Request Message", -1, true},
  214. }
  215. for _, tc := range testCases {
  216. tc := tc
  217. t.Run(tc.testName, func(t *testing.T) {
  218. request := bcBlockRequestMessage{Height: tc.requestHeight}
  219. assert.Equal(t, tc.expectErr, request.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  220. })
  221. }
  222. }
  223. func TestBcNoBlockResponseMessageValidateBasic(t *testing.T) {
  224. testCases := []struct {
  225. testName string
  226. nonResponseHeight int64
  227. expectErr bool
  228. }{
  229. {"Valid Non-Response Message", 0, false},
  230. {"Valid Non-Response Message", 1, false},
  231. {"Invalid Non-Response Message", -1, true},
  232. }
  233. for _, tc := range testCases {
  234. tc := tc
  235. t.Run(tc.testName, func(t *testing.T) {
  236. nonResponse := bcNoBlockResponseMessage{Height: tc.nonResponseHeight}
  237. assert.Equal(t, tc.expectErr, nonResponse.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  238. })
  239. }
  240. }
  241. func TestBcStatusRequestMessageValidateBasic(t *testing.T) {
  242. testCases := []struct {
  243. testName string
  244. requestHeight int64
  245. expectErr bool
  246. }{
  247. {"Valid Request Message", 0, false},
  248. {"Valid Request Message", 1, false},
  249. {"Invalid Request Message", -1, true},
  250. }
  251. for _, tc := range testCases {
  252. tc := tc
  253. t.Run(tc.testName, func(t *testing.T) {
  254. request := bcStatusRequestMessage{Height: tc.requestHeight}
  255. assert.Equal(t, tc.expectErr, request.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  256. })
  257. }
  258. }
  259. func TestBcStatusResponseMessageValidateBasic(t *testing.T) {
  260. testCases := []struct {
  261. testName string
  262. responseHeight int64
  263. expectErr bool
  264. }{
  265. {"Valid Response Message", 0, false},
  266. {"Valid Response Message", 1, false},
  267. {"Invalid Response Message", -1, true},
  268. }
  269. for _, tc := range testCases {
  270. tc := tc
  271. t.Run(tc.testName, func(t *testing.T) {
  272. response := bcStatusResponseMessage{Height: tc.responseHeight}
  273. assert.Equal(t, tc.expectErr, response.ValidateBasic() != nil, "Validate Basic had an unexpected result")
  274. })
  275. }
  276. }
  277. //----------------------------------------------
  278. // utility funcs
  279. func makeTxs(height int64) (txs []types.Tx) {
  280. for i := 0; i < 10; i++ {
  281. txs = append(txs, types.Tx([]byte{byte(height), byte(i)}))
  282. }
  283. return txs
  284. }
  285. func makeBlock(height int64, state sm.State, lastCommit *types.Commit) *types.Block {
  286. block, _ := state.MakeBlock(height, makeTxs(height), lastCommit, nil, state.Validators.GetProposer().Address)
  287. return block
  288. }
  289. type testApp struct {
  290. abci.BaseApplication
  291. }
  292. var _ abci.Application = (*testApp)(nil)
  293. func (app *testApp) Info(req abci.RequestInfo) (resInfo abci.ResponseInfo) {
  294. return abci.ResponseInfo{}
  295. }
  296. func (app *testApp) BeginBlock(req abci.RequestBeginBlock) abci.ResponseBeginBlock {
  297. return abci.ResponseBeginBlock{}
  298. }
  299. func (app *testApp) EndBlock(req abci.RequestEndBlock) abci.ResponseEndBlock {
  300. return abci.ResponseEndBlock{}
  301. }
  302. func (app *testApp) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx {
  303. return abci.ResponseDeliverTx{Events: []abci.Event{}}
  304. }
  305. func (app *testApp) CheckTx(req abci.RequestCheckTx) abci.ResponseCheckTx {
  306. return abci.ResponseCheckTx{}
  307. }
  308. func (app *testApp) Commit() abci.ResponseCommit {
  309. return abci.ResponseCommit{}
  310. }
  311. func (app *testApp) Query(reqQuery abci.RequestQuery) (resQuery abci.ResponseQuery) {
  312. return
  313. }