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.

252 lines
8.1 KiB

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
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
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 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
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
pubsub 2.0 (#3227) * green pubsub tests :OK: * get rid of clientToQueryMap * Subscribe and SubscribeUnbuffered * start adapting other pkgs to new pubsub * nope * rename MsgAndTags to Message * remove TagMap it does not bring any additional benefits * bring back EventSubscriber * fix test * fix data race in TestStartNextHeightCorrectly ``` Write at 0x00c0001c7418 by goroutine 796: github.com/tendermint/tendermint/consensus.TestStartNextHeightCorrectly() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:1296 +0xad testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Previous read at 0x00c0001c7418 by goroutine 858: github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1631 +0x1366 github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1476 +0x8f github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /go/src/github.com/tendermint/tendermint/consensus/state.go:667 +0xa1e github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:628 +0x794 Goroutine 796 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 testing.runTests.func1() /usr/local/go/src/testing/testing.go:1119 +0xa8 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 testing.runTests() /usr/local/go/src/testing/testing.go:1117 +0x4ee testing.(*M).Run() /usr/local/go/src/testing/testing.go:1034 +0x2ee main.main() _testmain.go:214 +0x332 Goroutine 858 (running) created at: github.com/tendermint/tendermint/consensus.(*ConsensusState).startRoutines() /go/src/github.com/tendermint/tendermint/consensus/state.go:334 +0x221 github.com/tendermint/tendermint/consensus.startTestRound() /go/src/github.com/tendermint/tendermint/consensus/common_test.go:122 +0x63 github.com/tendermint/tendermint/consensus.TestStateFullRound1() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:255 +0x397 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ``` * fixes after my own review * fix formatting * wait 100ms before kicking a subscriber out + a test for indexer_service * fixes after my second review * no timeout * add changelog entries * fix merge conflicts * fix typos after Thane's review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * reformat code * rewrite indexer service in the attempt to fix failing test https://github.com/tendermint/tendermint/pull/3227/#issuecomment-462316527 * Revert "rewrite indexer service in the attempt to fix failing test" This reverts commit 0d9107a098230de7138abb1c201877c246e89ed1. * another attempt to fix indexer * fixes after Ethan's review * use unbuffered channel when indexing transactions Refs https://github.com/tendermint/tendermint/pull/3227#discussion_r258786716 * add a comment for EventBus#SubscribeUnbuffered * format code
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
8 years ago
8 years ago
  1. package consensus
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "os"
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/tendermint/tendermint/abci/example/code"
  10. abci "github.com/tendermint/tendermint/abci/types"
  11. mempl "github.com/tendermint/tendermint/mempool"
  12. sm "github.com/tendermint/tendermint/state"
  13. "github.com/tendermint/tendermint/types"
  14. dbm "github.com/tendermint/tm-db"
  15. )
  16. // for testing
  17. func assertMempool(txn txNotifier) mempl.Mempool {
  18. return txn.(mempl.Mempool)
  19. }
  20. func TestMempoolNoProgressUntilTxsAvailable(t *testing.T) {
  21. config := ResetConfig("consensus_mempool_txs_available_test")
  22. defer os.RemoveAll(config.RootDir)
  23. config.Consensus.CreateEmptyBlocks = false
  24. state, privVals := randGenesisState(1, false, 10)
  25. cs := newConsensusStateWithConfig(config, state, privVals[0], NewCounterApplication())
  26. assertMempool(cs.txNotifier).EnableTxsAvailable()
  27. height, round := cs.Height, cs.Round
  28. newBlockCh := subscribe(cs.eventBus, types.EventQueryNewBlock)
  29. startTestRound(cs, height, round)
  30. ensureNewEventOnChannel(newBlockCh) // first block gets committed
  31. ensureNoNewEventOnChannel(newBlockCh)
  32. deliverTxsRange(cs, 0, 1)
  33. ensureNewEventOnChannel(newBlockCh) // commit txs
  34. ensureNewEventOnChannel(newBlockCh) // commit updated app hash
  35. ensureNoNewEventOnChannel(newBlockCh)
  36. }
  37. func TestMempoolProgressAfterCreateEmptyBlocksInterval(t *testing.T) {
  38. config := ResetConfig("consensus_mempool_txs_available_test")
  39. defer os.RemoveAll(config.RootDir)
  40. config.Consensus.CreateEmptyBlocksInterval = ensureTimeout
  41. state, privVals := randGenesisState(1, false, 10)
  42. cs := newConsensusStateWithConfig(config, state, privVals[0], NewCounterApplication())
  43. assertMempool(cs.txNotifier).EnableTxsAvailable()
  44. height, round := cs.Height, cs.Round
  45. newBlockCh := subscribe(cs.eventBus, types.EventQueryNewBlock)
  46. startTestRound(cs, height, round)
  47. ensureNewEventOnChannel(newBlockCh) // first block gets committed
  48. ensureNoNewEventOnChannel(newBlockCh) // then we dont make a block ...
  49. ensureNewEventOnChannel(newBlockCh) // until the CreateEmptyBlocksInterval has passed
  50. }
  51. func TestMempoolProgressInHigherRound(t *testing.T) {
  52. config := ResetConfig("consensus_mempool_txs_available_test")
  53. defer os.RemoveAll(config.RootDir)
  54. config.Consensus.CreateEmptyBlocks = false
  55. state, privVals := randGenesisState(1, false, 10)
  56. cs := newConsensusStateWithConfig(config, state, privVals[0], NewCounterApplication())
  57. assertMempool(cs.txNotifier).EnableTxsAvailable()
  58. height, round := cs.Height, cs.Round
  59. newBlockCh := subscribe(cs.eventBus, types.EventQueryNewBlock)
  60. newRoundCh := subscribe(cs.eventBus, types.EventQueryNewRound)
  61. timeoutCh := subscribe(cs.eventBus, types.EventQueryTimeoutPropose)
  62. cs.setProposal = func(proposal *types.Proposal) error {
  63. if cs.Height == 2 && cs.Round == 0 {
  64. // dont set the proposal in round 0 so we timeout and
  65. // go to next round
  66. cs.Logger.Info("Ignoring set proposal at height 2, round 0")
  67. return nil
  68. }
  69. return cs.defaultSetProposal(proposal)
  70. }
  71. startTestRound(cs, height, round)
  72. ensureNewRound(newRoundCh, height, round) // first round at first height
  73. ensureNewEventOnChannel(newBlockCh) // first block gets committed
  74. height++ // moving to the next height
  75. round = 0
  76. ensureNewRound(newRoundCh, height, round) // first round at next height
  77. deliverTxsRange(cs, 0, 1) // we deliver txs, but dont set a proposal so we get the next round
  78. ensureNewTimeout(timeoutCh, height, round, cs.config.TimeoutPropose.Nanoseconds())
  79. round++ // moving to the next round
  80. ensureNewRound(newRoundCh, height, round) // wait for the next round
  81. ensureNewEventOnChannel(newBlockCh) // now we can commit the block
  82. }
  83. func deliverTxsRange(cs *ConsensusState, start, end int) {
  84. // Deliver some txs.
  85. for i := start; i < end; i++ {
  86. txBytes := make([]byte, 8)
  87. binary.BigEndian.PutUint64(txBytes, uint64(i))
  88. err := assertMempool(cs.txNotifier).CheckTx(txBytes, nil, mempl.TxInfo{})
  89. if err != nil {
  90. panic(fmt.Sprintf("Error after CheckTx: %v", err))
  91. }
  92. }
  93. }
  94. func TestMempoolTxConcurrentWithCommit(t *testing.T) {
  95. state, privVals := randGenesisState(1, false, 10)
  96. blockDB := dbm.NewMemDB()
  97. cs := newConsensusStateWithConfigAndBlockStore(config, state, privVals[0], NewCounterApplication(), blockDB)
  98. sm.SaveState(blockDB, state)
  99. height, round := cs.Height, cs.Round
  100. newBlockCh := subscribe(cs.eventBus, types.EventQueryNewBlock)
  101. NTxs := 3000
  102. go deliverTxsRange(cs, 0, NTxs)
  103. startTestRound(cs, height, round)
  104. for nTxs := 0; nTxs < NTxs; {
  105. ticker := time.NewTicker(time.Second * 30)
  106. select {
  107. case msg := <-newBlockCh:
  108. blockEvent := msg.Data().(types.EventDataNewBlock)
  109. nTxs += len(blockEvent.Block.Txs)
  110. case <-ticker.C:
  111. panic("Timed out waiting to commit blocks with transactions")
  112. }
  113. }
  114. }
  115. func TestMempoolRmBadTx(t *testing.T) {
  116. state, privVals := randGenesisState(1, false, 10)
  117. app := NewCounterApplication()
  118. blockDB := dbm.NewMemDB()
  119. cs := newConsensusStateWithConfigAndBlockStore(config, state, privVals[0], app, blockDB)
  120. sm.SaveState(blockDB, state)
  121. // increment the counter by 1
  122. txBytes := make([]byte, 8)
  123. binary.BigEndian.PutUint64(txBytes, uint64(0))
  124. resDeliver := app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes})
  125. assert.False(t, resDeliver.IsErr(), fmt.Sprintf("expected no error. got %v", resDeliver))
  126. resCommit := app.Commit()
  127. assert.True(t, len(resCommit.Data) > 0)
  128. emptyMempoolCh := make(chan struct{})
  129. checkTxRespCh := make(chan struct{})
  130. go func() {
  131. // Try to send the tx through the mempool.
  132. // CheckTx should not err, but the app should return a bad abci code
  133. // and the tx should get removed from the pool
  134. err := assertMempool(cs.txNotifier).CheckTx(txBytes, func(r *abci.Response) {
  135. if r.GetCheckTx().Code != code.CodeTypeBadNonce {
  136. t.Errorf("expected checktx to return bad nonce, got %v", r)
  137. return
  138. }
  139. checkTxRespCh <- struct{}{}
  140. }, mempl.TxInfo{})
  141. if err != nil {
  142. t.Errorf("error after CheckTx: %v", err)
  143. return
  144. }
  145. // check for the tx
  146. for {
  147. txs := assertMempool(cs.txNotifier).ReapMaxBytesMaxGas(int64(len(txBytes)), -1)
  148. if len(txs) == 0 {
  149. emptyMempoolCh <- struct{}{}
  150. return
  151. }
  152. time.Sleep(10 * time.Millisecond)
  153. }
  154. }()
  155. // Wait until the tx returns
  156. ticker := time.After(time.Second * 5)
  157. select {
  158. case <-checkTxRespCh:
  159. // success
  160. case <-ticker:
  161. t.Errorf("timed out waiting for tx to return")
  162. return
  163. }
  164. // Wait until the tx is removed
  165. ticker = time.After(time.Second * 5)
  166. select {
  167. case <-emptyMempoolCh:
  168. // success
  169. case <-ticker:
  170. t.Errorf("timed out waiting for tx to be removed")
  171. return
  172. }
  173. }
  174. // CounterApplication that maintains a mempool state and resets it upon commit
  175. type CounterApplication struct {
  176. abci.BaseApplication
  177. txCount int
  178. mempoolTxCount int
  179. }
  180. func NewCounterApplication() *CounterApplication {
  181. return &CounterApplication{}
  182. }
  183. func (app *CounterApplication) Info(req abci.RequestInfo) abci.ResponseInfo {
  184. return abci.ResponseInfo{Data: fmt.Sprintf("txs:%v", app.txCount)}
  185. }
  186. func (app *CounterApplication) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx {
  187. txValue := txAsUint64(req.Tx)
  188. if txValue != uint64(app.txCount) {
  189. return abci.ResponseDeliverTx{
  190. Code: code.CodeTypeBadNonce,
  191. Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue)}
  192. }
  193. app.txCount++
  194. return abci.ResponseDeliverTx{Code: code.CodeTypeOK}
  195. }
  196. func (app *CounterApplication) CheckTx(req abci.RequestCheckTx) abci.ResponseCheckTx {
  197. txValue := txAsUint64(req.Tx)
  198. if txValue != uint64(app.mempoolTxCount) {
  199. return abci.ResponseCheckTx{
  200. Code: code.CodeTypeBadNonce,
  201. Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.mempoolTxCount, txValue)}
  202. }
  203. app.mempoolTxCount++
  204. return abci.ResponseCheckTx{Code: code.CodeTypeOK}
  205. }
  206. func txAsUint64(tx []byte) uint64 {
  207. tx8 := make([]byte, 8)
  208. copy(tx8[len(tx8)-len(tx):], tx)
  209. return binary.BigEndian.Uint64(tx8)
  210. }
  211. func (app *CounterApplication) Commit() abci.ResponseCommit {
  212. app.mempoolTxCount = app.txCount
  213. if app.txCount == 0 {
  214. return abci.ResponseCommit{}
  215. }
  216. hash := make([]byte, 8)
  217. binary.BigEndian.PutUint64(hash, uint64(app.txCount))
  218. return abci.ResponseCommit{Data: hash}
  219. }