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.

291 lines
9.3 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
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/libs/log"
  18. "github.com/tendermint/tendermint/types"
  19. )
  20. // for testing
  21. func assertMempool(txn txNotifier) mempool.Mempool {
  22. return txn.(mempool.Mempool)
  23. }
  24. func TestMempoolNoProgressUntilTxsAvailable(t *testing.T) {
  25. ctx, cancel := context.WithCancel(context.Background())
  26. defer cancel()
  27. baseConfig := configSetup(t)
  28. config, err := ResetConfig("consensus_mempool_txs_available_test")
  29. require.NoError(t, err)
  30. t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) })
  31. config.Consensus.CreateEmptyBlocks = false
  32. state, privVals := randGenesisState(baseConfig, 1, false, 10)
  33. cs := newStateWithConfig(ctx, log.TestingLogger(), config, state, privVals[0], NewCounterApplication())
  34. assertMempool(cs.txNotifier).EnableTxsAvailable()
  35. height, round := cs.Height, cs.Round
  36. newBlockCh := subscribe(ctx, t, cs.eventBus, types.EventQueryNewBlock)
  37. startTestRound(ctx, cs, height, round)
  38. ensureNewEventOnChannel(newBlockCh) // first block gets committed
  39. ensureNoNewEventOnChannel(newBlockCh)
  40. deliverTxsRange(ctx, cs, 0, 1)
  41. ensureNewEventOnChannel(newBlockCh) // commit txs
  42. ensureNewEventOnChannel(newBlockCh) // commit updated app hash
  43. ensureNoNewEventOnChannel(newBlockCh)
  44. }
  45. func TestMempoolProgressAfterCreateEmptyBlocksInterval(t *testing.T) {
  46. baseConfig := configSetup(t)
  47. ctx, cancel := context.WithCancel(context.Background())
  48. defer cancel()
  49. config, err := ResetConfig("consensus_mempool_txs_available_test")
  50. require.NoError(t, err)
  51. t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) })
  52. config.Consensus.CreateEmptyBlocksInterval = ensureTimeout
  53. state, privVals := randGenesisState(baseConfig, 1, false, 10)
  54. cs := newStateWithConfig(ctx, log.TestingLogger(), config, state, privVals[0], NewCounterApplication())
  55. assertMempool(cs.txNotifier).EnableTxsAvailable()
  56. newBlockCh := subscribe(ctx, t, cs.eventBus, types.EventQueryNewBlock)
  57. startTestRound(ctx, cs, cs.Height, cs.Round)
  58. ensureNewEventOnChannel(newBlockCh) // first block gets committed
  59. ensureNoNewEventOnChannel(newBlockCh) // then we dont make a block ...
  60. ensureNewEventOnChannel(newBlockCh) // until the CreateEmptyBlocksInterval has passed
  61. }
  62. func TestMempoolProgressInHigherRound(t *testing.T) {
  63. baseConfig := configSetup(t)
  64. ctx, cancel := context.WithCancel(context.Background())
  65. defer cancel()
  66. config, err := ResetConfig("consensus_mempool_txs_available_test")
  67. require.NoError(t, err)
  68. t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) })
  69. config.Consensus.CreateEmptyBlocks = false
  70. state, privVals := randGenesisState(baseConfig, 1, false, 10)
  71. cs := newStateWithConfig(ctx, log.TestingLogger(), config, state, privVals[0], NewCounterApplication())
  72. assertMempool(cs.txNotifier).EnableTxsAvailable()
  73. height, round := cs.Height, cs.Round
  74. newBlockCh := subscribe(ctx, t, cs.eventBus, types.EventQueryNewBlock)
  75. newRoundCh := subscribe(ctx, t, cs.eventBus, types.EventQueryNewRound)
  76. timeoutCh := subscribe(ctx, t, cs.eventBus, types.EventQueryTimeoutPropose)
  77. cs.setProposal = func(proposal *types.Proposal) error {
  78. if cs.Height == 2 && cs.Round == 0 {
  79. // dont set the proposal in round 0 so we timeout and
  80. // go to next round
  81. cs.logger.Info("Ignoring set proposal at height 2, round 0")
  82. return nil
  83. }
  84. return cs.defaultSetProposal(proposal)
  85. }
  86. startTestRound(ctx, cs, height, round)
  87. ensureNewRound(newRoundCh, height, round) // first round at first height
  88. ensureNewEventOnChannel(newBlockCh) // first block gets committed
  89. height++ // moving to the next height
  90. round = 0
  91. ensureNewRound(newRoundCh, height, round) // first round at next height
  92. deliverTxsRange(ctx, cs, 0, 1) // we deliver txs, but dont set a proposal so we get the next round
  93. ensureNewTimeout(timeoutCh, height, round, cs.config.TimeoutPropose.Nanoseconds())
  94. round++ // moving to the next round
  95. ensureNewRound(newRoundCh, height, round) // wait for the next round
  96. ensureNewEventOnChannel(newBlockCh) // now we can commit the block
  97. }
  98. func deliverTxsRange(ctx context.Context, cs *State, start, end int) {
  99. // Deliver some txs.
  100. for i := start; i < end; i++ {
  101. txBytes := make([]byte, 8)
  102. binary.BigEndian.PutUint64(txBytes, uint64(i))
  103. err := assertMempool(cs.txNotifier).CheckTx(ctx, txBytes, nil, mempool.TxInfo{})
  104. if err != nil {
  105. panic(fmt.Sprintf("Error after CheckTx: %v", err))
  106. }
  107. }
  108. }
  109. func TestMempoolTxConcurrentWithCommit(t *testing.T) {
  110. ctx, cancel := context.WithCancel(context.Background())
  111. defer cancel()
  112. config := configSetup(t)
  113. logger := log.TestingLogger()
  114. state, privVals := randGenesisState(config, 1, false, 10)
  115. stateStore := sm.NewStore(dbm.NewMemDB())
  116. blockStore := store.NewBlockStore(dbm.NewMemDB())
  117. cs := newStateWithConfigAndBlockStore(
  118. ctx,
  119. logger, config, state, privVals[0], NewCounterApplication(), blockStore)
  120. err := stateStore.Save(state)
  121. require.NoError(t, err)
  122. newBlockHeaderCh := subscribe(ctx, t, cs.eventBus, types.EventQueryNewBlockHeader)
  123. const numTxs int64 = 3000
  124. go deliverTxsRange(ctx, cs, 0, int(numTxs))
  125. startTestRound(ctx, cs, cs.Height, cs.Round)
  126. for n := int64(0); n < numTxs; {
  127. select {
  128. case msg := <-newBlockHeaderCh:
  129. headerEvent := msg.Data().(types.EventDataNewBlockHeader)
  130. n += headerEvent.NumTxs
  131. case <-time.After(30 * time.Second):
  132. t.Fatal("Timed out waiting 30s to commit blocks with transactions")
  133. }
  134. }
  135. }
  136. func TestMempoolRmBadTx(t *testing.T) {
  137. config := configSetup(t)
  138. ctx, cancel := context.WithCancel(context.Background())
  139. defer cancel()
  140. state, privVals := randGenesisState(config, 1, false, 10)
  141. app := NewCounterApplication()
  142. stateStore := sm.NewStore(dbm.NewMemDB())
  143. blockStore := store.NewBlockStore(dbm.NewMemDB())
  144. cs := newStateWithConfigAndBlockStore(ctx, log.TestingLogger(), config, state, privVals[0], app, blockStore)
  145. err := stateStore.Save(state)
  146. require.NoError(t, err)
  147. // increment the counter by 1
  148. txBytes := make([]byte, 8)
  149. binary.BigEndian.PutUint64(txBytes, uint64(0))
  150. resDeliver := app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes})
  151. assert.False(t, resDeliver.IsErr(), fmt.Sprintf("expected no error. got %v", resDeliver))
  152. resCommit := app.Commit()
  153. assert.True(t, len(resCommit.Data) > 0)
  154. emptyMempoolCh := make(chan struct{})
  155. checkTxRespCh := make(chan struct{})
  156. go func() {
  157. // Try to send the tx through the mempool.
  158. // CheckTx should not err, but the app should return a bad abci code
  159. // and the tx should get removed from the pool
  160. err := assertMempool(cs.txNotifier).CheckTx(ctx, txBytes, func(r *abci.Response) {
  161. if r.GetCheckTx().Code != code.CodeTypeBadNonce {
  162. t.Errorf("expected checktx to return bad nonce, got %v", r)
  163. return
  164. }
  165. checkTxRespCh <- struct{}{}
  166. }, mempool.TxInfo{})
  167. if err != nil {
  168. t.Errorf("error after CheckTx: %v", err)
  169. return
  170. }
  171. // check for the tx
  172. for {
  173. txs := assertMempool(cs.txNotifier).ReapMaxBytesMaxGas(int64(len(txBytes)), -1)
  174. if len(txs) == 0 {
  175. emptyMempoolCh <- struct{}{}
  176. return
  177. }
  178. time.Sleep(10 * time.Millisecond)
  179. }
  180. }()
  181. // Wait until the tx returns
  182. ticker := time.After(time.Second * 5)
  183. select {
  184. case <-checkTxRespCh:
  185. // success
  186. case <-ticker:
  187. t.Errorf("timed out waiting for tx to return")
  188. return
  189. }
  190. // Wait until the tx is removed
  191. ticker = time.After(time.Second * 5)
  192. select {
  193. case <-emptyMempoolCh:
  194. // success
  195. case <-ticker:
  196. t.Errorf("timed out waiting for tx to be removed")
  197. return
  198. }
  199. }
  200. // CounterApplication that maintains a mempool state and resets it upon commit
  201. type CounterApplication struct {
  202. abci.BaseApplication
  203. txCount int
  204. mempoolTxCount int
  205. }
  206. func NewCounterApplication() *CounterApplication {
  207. return &CounterApplication{}
  208. }
  209. func (app *CounterApplication) Info(req abci.RequestInfo) abci.ResponseInfo {
  210. return abci.ResponseInfo{Data: fmt.Sprintf("txs:%v", app.txCount)}
  211. }
  212. func (app *CounterApplication) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx {
  213. txValue := txAsUint64(req.Tx)
  214. if txValue != uint64(app.txCount) {
  215. return abci.ResponseDeliverTx{
  216. Code: code.CodeTypeBadNonce,
  217. Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue)}
  218. }
  219. app.txCount++
  220. return abci.ResponseDeliverTx{Code: code.CodeTypeOK}
  221. }
  222. func (app *CounterApplication) CheckTx(req abci.RequestCheckTx) abci.ResponseCheckTx {
  223. txValue := txAsUint64(req.Tx)
  224. if txValue != uint64(app.mempoolTxCount) {
  225. return abci.ResponseCheckTx{
  226. Code: code.CodeTypeBadNonce,
  227. Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.mempoolTxCount, txValue)}
  228. }
  229. app.mempoolTxCount++
  230. return abci.ResponseCheckTx{Code: code.CodeTypeOK}
  231. }
  232. func txAsUint64(tx []byte) uint64 {
  233. tx8 := make([]byte, 8)
  234. copy(tx8[len(tx8)-len(tx):], tx)
  235. return binary.BigEndian.Uint64(tx8)
  236. }
  237. func (app *CounterApplication) Commit() abci.ResponseCommit {
  238. app.mempoolTxCount = app.txCount
  239. if app.txCount == 0 {
  240. return abci.ResponseCommit{}
  241. }
  242. hash := make([]byte, 8)
  243. binary.BigEndian.PutUint64(hash, uint64(app.txCount))
  244. return abci.ResponseCommit{Data: hash}
  245. }