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.

271 lines
8.6 KiB

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
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 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
7 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 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
7 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 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
7 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
8 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
8 years ago
  1. package consensus
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "fmt"
  6. "os"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/stretchr/testify/require"
  11. dbm "github.com/tendermint/tm-db"
  12. "github.com/tendermint/tendermint/abci/example/code"
  13. abci "github.com/tendermint/tendermint/abci/types"
  14. "github.com/tendermint/tendermint/internal/mempool"
  15. sm "github.com/tendermint/tendermint/internal/state"
  16. "github.com/tendermint/tendermint/internal/store"
  17. "github.com/tendermint/tendermint/types"
  18. )
  19. // for testing
  20. func assertMempool(txn txNotifier) mempool.Mempool {
  21. return txn.(mempool.Mempool)
  22. }
  23. func TestMempoolNoProgressUntilTxsAvailable(t *testing.T) {
  24. baseConfig := configSetup(t)
  25. config := ResetConfig("consensus_mempool_txs_available_test")
  26. t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) })
  27. config.Consensus.CreateEmptyBlocks = false
  28. state, privVals := randGenesisState(baseConfig, 1, false, 10)
  29. cs := newStateWithConfig(config, state, privVals[0], NewCounterApplication())
  30. assertMempool(cs.txNotifier).EnableTxsAvailable()
  31. height, round := cs.Height, cs.Round
  32. newBlockCh := subscribe(cs.eventBus, types.EventQueryNewBlock)
  33. startTestRound(cs, height, round)
  34. ensureNewEventOnChannel(newBlockCh) // first block gets committed
  35. ensureNoNewEventOnChannel(newBlockCh)
  36. deliverTxsRange(cs, 0, 1)
  37. ensureNewEventOnChannel(newBlockCh) // commit txs
  38. ensureNewEventOnChannel(newBlockCh) // commit updated app hash
  39. ensureNoNewEventOnChannel(newBlockCh)
  40. }
  41. func TestMempoolProgressAfterCreateEmptyBlocksInterval(t *testing.T) {
  42. baseConfig := configSetup(t)
  43. config := ResetConfig("consensus_mempool_txs_available_test")
  44. t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) })
  45. config.Consensus.CreateEmptyBlocksInterval = ensureTimeout
  46. state, privVals := randGenesisState(baseConfig, 1, false, 10)
  47. cs := newStateWithConfig(config, state, privVals[0], NewCounterApplication())
  48. assertMempool(cs.txNotifier).EnableTxsAvailable()
  49. newBlockCh := subscribe(cs.eventBus, types.EventQueryNewBlock)
  50. startTestRound(cs, cs.Height, cs.Round)
  51. ensureNewEventOnChannel(newBlockCh) // first block gets committed
  52. ensureNoNewEventOnChannel(newBlockCh) // then we dont make a block ...
  53. ensureNewEventOnChannel(newBlockCh) // until the CreateEmptyBlocksInterval has passed
  54. }
  55. func TestMempoolProgressInHigherRound(t *testing.T) {
  56. baseConfig := configSetup(t)
  57. config := ResetConfig("consensus_mempool_txs_available_test")
  58. t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) })
  59. config.Consensus.CreateEmptyBlocks = false
  60. state, privVals := randGenesisState(baseConfig, 1, false, 10)
  61. cs := newStateWithConfig(config, state, privVals[0], NewCounterApplication())
  62. assertMempool(cs.txNotifier).EnableTxsAvailable()
  63. height, round := cs.Height, cs.Round
  64. newBlockCh := subscribe(cs.eventBus, types.EventQueryNewBlock)
  65. newRoundCh := subscribe(cs.eventBus, types.EventQueryNewRound)
  66. timeoutCh := subscribe(cs.eventBus, types.EventQueryTimeoutPropose)
  67. cs.setProposal = func(proposal *types.Proposal) error {
  68. if cs.Height == 2 && cs.Round == 0 {
  69. // dont set the proposal in round 0 so we timeout and
  70. // go to next round
  71. cs.Logger.Info("Ignoring set proposal at height 2, round 0")
  72. return nil
  73. }
  74. return cs.defaultSetProposal(proposal)
  75. }
  76. startTestRound(cs, height, round)
  77. ensureNewRound(newRoundCh, height, round) // first round at first height
  78. ensureNewEventOnChannel(newBlockCh) // first block gets committed
  79. height++ // moving to the next height
  80. round = 0
  81. ensureNewRound(newRoundCh, height, round) // first round at next height
  82. deliverTxsRange(cs, 0, 1) // we deliver txs, but dont set a proposal so we get the next round
  83. ensureNewTimeout(timeoutCh, height, round, cs.config.TimeoutPropose.Nanoseconds())
  84. round++ // moving to the next round
  85. ensureNewRound(newRoundCh, height, round) // wait for the next round
  86. ensureNewEventOnChannel(newBlockCh) // now we can commit the block
  87. }
  88. func deliverTxsRange(cs *State, start, end int) {
  89. // Deliver some txs.
  90. for i := start; i < end; i++ {
  91. txBytes := make([]byte, 8)
  92. binary.BigEndian.PutUint64(txBytes, uint64(i))
  93. err := assertMempool(cs.txNotifier).CheckTx(context.Background(), txBytes, nil, mempool.TxInfo{})
  94. if err != nil {
  95. panic(fmt.Sprintf("Error after CheckTx: %v", err))
  96. }
  97. }
  98. }
  99. func TestMempoolTxConcurrentWithCommit(t *testing.T) {
  100. config := configSetup(t)
  101. state, privVals := randGenesisState(config, 1, false, 10)
  102. stateStore := sm.NewStore(dbm.NewMemDB())
  103. blockStore := store.NewBlockStore(dbm.NewMemDB())
  104. cs := newStateWithConfigAndBlockStore(config, state, privVals[0], NewCounterApplication(), blockStore)
  105. err := stateStore.Save(state)
  106. require.NoError(t, err)
  107. newBlockHeaderCh := subscribe(cs.eventBus, types.EventQueryNewBlockHeader)
  108. const numTxs int64 = 3000
  109. go deliverTxsRange(cs, 0, int(numTxs))
  110. startTestRound(cs, cs.Height, cs.Round)
  111. for n := int64(0); n < numTxs; {
  112. select {
  113. case msg := <-newBlockHeaderCh:
  114. headerEvent := msg.Data().(types.EventDataNewBlockHeader)
  115. n += headerEvent.NumTxs
  116. case <-time.After(30 * time.Second):
  117. t.Fatal("Timed out waiting 30s to commit blocks with transactions")
  118. }
  119. }
  120. }
  121. func TestMempoolRmBadTx(t *testing.T) {
  122. config := configSetup(t)
  123. state, privVals := randGenesisState(config, 1, false, 10)
  124. app := NewCounterApplication()
  125. stateStore := sm.NewStore(dbm.NewMemDB())
  126. blockStore := store.NewBlockStore(dbm.NewMemDB())
  127. cs := newStateWithConfigAndBlockStore(config, state, privVals[0], app, blockStore)
  128. err := stateStore.Save(state)
  129. require.NoError(t, err)
  130. // increment the counter by 1
  131. txBytes := make([]byte, 8)
  132. binary.BigEndian.PutUint64(txBytes, uint64(0))
  133. resDeliver := app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes})
  134. assert.False(t, resDeliver.IsErr(), fmt.Sprintf("expected no error. got %v", resDeliver))
  135. resCommit := app.Commit()
  136. assert.True(t, len(resCommit.Data) > 0)
  137. emptyMempoolCh := make(chan struct{})
  138. checkTxRespCh := make(chan struct{})
  139. go func() {
  140. // Try to send the tx through the mempool.
  141. // CheckTx should not err, but the app should return a bad abci code
  142. // and the tx should get removed from the pool
  143. err := assertMempool(cs.txNotifier).CheckTx(context.Background(), txBytes, func(r *abci.Response) {
  144. if r.GetCheckTx().Code != code.CodeTypeBadNonce {
  145. t.Errorf("expected checktx to return bad nonce, got %v", r)
  146. return
  147. }
  148. checkTxRespCh <- struct{}{}
  149. }, mempool.TxInfo{})
  150. if err != nil {
  151. t.Errorf("error after CheckTx: %v", err)
  152. return
  153. }
  154. // check for the tx
  155. for {
  156. txs := assertMempool(cs.txNotifier).ReapMaxBytesMaxGas(int64(len(txBytes)), -1)
  157. if len(txs) == 0 {
  158. emptyMempoolCh <- struct{}{}
  159. return
  160. }
  161. time.Sleep(10 * time.Millisecond)
  162. }
  163. }()
  164. // Wait until the tx returns
  165. ticker := time.After(time.Second * 5)
  166. select {
  167. case <-checkTxRespCh:
  168. // success
  169. case <-ticker:
  170. t.Errorf("timed out waiting for tx to return")
  171. return
  172. }
  173. // Wait until the tx is removed
  174. ticker = time.After(time.Second * 5)
  175. select {
  176. case <-emptyMempoolCh:
  177. // success
  178. case <-ticker:
  179. t.Errorf("timed out waiting for tx to be removed")
  180. return
  181. }
  182. }
  183. // CounterApplication that maintains a mempool state and resets it upon commit
  184. type CounterApplication struct {
  185. abci.BaseApplication
  186. txCount int
  187. mempoolTxCount int
  188. }
  189. func NewCounterApplication() *CounterApplication {
  190. return &CounterApplication{}
  191. }
  192. func (app *CounterApplication) Info(req abci.RequestInfo) abci.ResponseInfo {
  193. return abci.ResponseInfo{Data: fmt.Sprintf("txs:%v", app.txCount)}
  194. }
  195. func (app *CounterApplication) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx {
  196. txValue := txAsUint64(req.Tx)
  197. if txValue != uint64(app.txCount) {
  198. return abci.ResponseDeliverTx{
  199. Code: code.CodeTypeBadNonce,
  200. Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue)}
  201. }
  202. app.txCount++
  203. return abci.ResponseDeliverTx{Code: code.CodeTypeOK}
  204. }
  205. func (app *CounterApplication) CheckTx(req abci.RequestCheckTx) abci.ResponseCheckTx {
  206. txValue := txAsUint64(req.Tx)
  207. if txValue != uint64(app.mempoolTxCount) {
  208. return abci.ResponseCheckTx{
  209. Code: code.CodeTypeBadNonce,
  210. Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.mempoolTxCount, txValue)}
  211. }
  212. app.mempoolTxCount++
  213. return abci.ResponseCheckTx{Code: code.CodeTypeOK}
  214. }
  215. func txAsUint64(tx []byte) uint64 {
  216. tx8 := make([]byte, 8)
  217. copy(tx8[len(tx8)-len(tx):], tx)
  218. return binary.BigEndian.Uint64(tx8)
  219. }
  220. func (app *CounterApplication) Commit() abci.ResponseCommit {
  221. app.mempoolTxCount = app.txCount
  222. if app.txCount == 0 {
  223. return abci.ResponseCommit{}
  224. }
  225. hash := make([]byte, 8)
  226. binary.BigEndian.PutUint64(hash, uint64(app.txCount))
  227. return abci.ResponseCommit{Data: hash}
  228. }