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.

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