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.

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