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.

224 lines
7.0 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
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
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
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
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
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
  1. package consensus
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "fmt"
  7. "io"
  8. mrand "math/rand"
  9. "testing"
  10. "time"
  11. "github.com/stretchr/testify/require"
  12. dbm "github.com/tendermint/tm-db"
  13. abciclient "github.com/tendermint/tendermint/abci/client"
  14. "github.com/tendermint/tendermint/abci/example/kvstore"
  15. "github.com/tendermint/tendermint/config"
  16. "github.com/tendermint/tendermint/internal/eventbus"
  17. "github.com/tendermint/tendermint/internal/proxy"
  18. sm "github.com/tendermint/tendermint/internal/state"
  19. "github.com/tendermint/tendermint/internal/store"
  20. "github.com/tendermint/tendermint/libs/log"
  21. "github.com/tendermint/tendermint/privval"
  22. "github.com/tendermint/tendermint/types"
  23. )
  24. // WALGenerateNBlocks generates a consensus WAL. It does this by
  25. // spinning up a stripped down version of node (proxy app, event bus,
  26. // consensus state) with a kvstore application and special consensus
  27. // wal instance (byteBufferWAL) and waits until numBlocks are created.
  28. // If the node fails to produce given numBlocks, it fails the test.
  29. func WALGenerateNBlocks(ctx context.Context, t *testing.T, logger log.Logger, wr io.Writer, numBlocks int) {
  30. t.Helper()
  31. cfg := getConfig(t)
  32. app := kvstore.NewApplication()
  33. logger.Info("generating WAL (last height msg excluded)", "numBlocks", numBlocks)
  34. // COPY PASTE FROM node.go WITH A FEW MODIFICATIONS
  35. // NOTE: we can't import node package because of circular dependency.
  36. // NOTE: we don't do handshake so need to set state.Version.Consensus.App directly.
  37. privValidatorKeyFile := cfg.PrivValidator.KeyFile()
  38. privValidatorStateFile := cfg.PrivValidator.StateFile()
  39. privValidator, err := privval.LoadOrGenFilePV(privValidatorKeyFile, privValidatorStateFile)
  40. if err != nil {
  41. t.Fatal(err)
  42. }
  43. genDoc, err := types.GenesisDocFromFile(cfg.GenesisFile())
  44. if err != nil {
  45. t.Fatal(fmt.Errorf("failed to read genesis file: %w", err))
  46. }
  47. blockStoreDB := dbm.NewMemDB()
  48. stateDB := blockStoreDB
  49. stateStore := sm.NewStore(stateDB)
  50. state, err := sm.MakeGenesisState(genDoc)
  51. if err != nil {
  52. t.Fatal(fmt.Errorf("failed to make genesis state: %w", err))
  53. }
  54. state.Version.Consensus.App = kvstore.ProtocolVersion
  55. if err = stateStore.Save(state); err != nil {
  56. t.Fatal(err)
  57. }
  58. blockStore := store.NewBlockStore(blockStoreDB)
  59. proxyLogger := logger.With("module", "proxy")
  60. proxyApp := proxy.New(abciclient.NewLocalClient(logger, app), proxyLogger, proxy.NopMetrics())
  61. if err := proxyApp.Start(ctx); err != nil {
  62. t.Fatal(fmt.Errorf("failed to start proxy app connections: %w", err))
  63. }
  64. t.Cleanup(proxyApp.Wait)
  65. eventBus := eventbus.NewDefault(logger.With("module", "events"))
  66. if err := eventBus.Start(ctx); err != nil {
  67. t.Fatal(fmt.Errorf("failed to start event bus: %w", err))
  68. }
  69. t.Cleanup(func() { eventBus.Stop(); eventBus.Wait() })
  70. mempool := emptyMempool{}
  71. evpool := sm.EmptyEvidencePool{}
  72. blockExec := sm.NewBlockExecutor(stateStore, log.NewNopLogger(), proxyApp, mempool, evpool, blockStore, eventBus)
  73. consensusState, err := NewState(ctx, logger, cfg.Consensus, stateStore, blockExec, blockStore, mempool, evpool, eventBus)
  74. if err != nil {
  75. t.Fatal(err)
  76. }
  77. if privValidator != nil && privValidator != (*privval.FilePV)(nil) {
  78. consensusState.SetPrivValidator(ctx, privValidator)
  79. }
  80. // END OF COPY PASTE
  81. // set consensus wal to buffered WAL, which will write all incoming msgs to buffer
  82. numBlocksWritten := make(chan struct{})
  83. wal := newByteBufferWAL(logger, NewWALEncoder(wr), int64(numBlocks), numBlocksWritten)
  84. // see wal.go#103
  85. if err := wal.Write(EndHeightMessage{0}); err != nil {
  86. t.Fatal(err)
  87. }
  88. consensusState.wal = wal
  89. if err := consensusState.Start(ctx); err != nil {
  90. t.Fatal(fmt.Errorf("failed to start consensus state: %w", err))
  91. }
  92. t.Cleanup(consensusState.Wait)
  93. defer consensusState.Stop()
  94. timer := time.NewTimer(time.Minute)
  95. defer timer.Stop()
  96. select {
  97. case <-numBlocksWritten:
  98. case <-timer.C:
  99. t.Fatal(fmt.Errorf("waited too long for tendermint to produce %d blocks (grep logs for `wal_generator`)", numBlocks))
  100. }
  101. }
  102. // WALWithNBlocks returns a WAL content with numBlocks.
  103. func WALWithNBlocks(ctx context.Context, t *testing.T, logger log.Logger, numBlocks int) (data []byte, err error) {
  104. var b bytes.Buffer
  105. wr := bufio.NewWriter(&b)
  106. WALGenerateNBlocks(ctx, t, logger, wr, numBlocks)
  107. wr.Flush()
  108. return b.Bytes(), nil
  109. }
  110. func randPort() int {
  111. // returns between base and base + spread
  112. base, spread := 20000, 20000
  113. // nolint:gosec // G404: Use of weak random number generator
  114. return base + mrand.Intn(spread)
  115. }
  116. // makeAddrs constructs local TCP addresses for node services.
  117. // It uses consecutive ports from a random starting point, so that concurrent
  118. // instances are less likely to collide.
  119. func makeAddrs() (p2pAddr, rpcAddr string) {
  120. const addrTemplate = "tcp://127.0.0.1:%d"
  121. start := randPort()
  122. return fmt.Sprintf(addrTemplate, start), fmt.Sprintf(addrTemplate, start+1)
  123. }
  124. // getConfig returns a config for test cases
  125. func getConfig(t *testing.T) *config.Config {
  126. c, err := config.ResetTestRoot(t.TempDir(), t.Name())
  127. require.NoError(t, err)
  128. p2pAddr, rpcAddr := makeAddrs()
  129. c.P2P.ListenAddress = p2pAddr
  130. c.RPC.ListenAddress = rpcAddr
  131. return c
  132. }
  133. // byteBufferWAL is a WAL which writes all msgs to a byte buffer. Writing stops
  134. // when the heightToStop is reached. Client will be notified via
  135. // signalWhenStopsTo channel.
  136. type byteBufferWAL struct {
  137. enc *WALEncoder
  138. stopped bool
  139. heightToStop int64
  140. signalWhenStopsTo chan<- struct{}
  141. logger log.Logger
  142. }
  143. // needed for determinism
  144. var fixedTime, _ = time.Parse(time.RFC3339, "2017-01-02T15:04:05Z")
  145. func newByteBufferWAL(logger log.Logger, enc *WALEncoder, nBlocks int64, signalStop chan<- struct{}) *byteBufferWAL {
  146. return &byteBufferWAL{
  147. enc: enc,
  148. heightToStop: nBlocks,
  149. signalWhenStopsTo: signalStop,
  150. logger: logger,
  151. }
  152. }
  153. // Save writes message to the internal buffer except when heightToStop is
  154. // reached, in which case it will signal the caller via signalWhenStopsTo and
  155. // skip writing.
  156. func (w *byteBufferWAL) Write(m WALMessage) error {
  157. if w.stopped {
  158. w.logger.Debug("WAL already stopped. Not writing message", "msg", m)
  159. return nil
  160. }
  161. if endMsg, ok := m.(EndHeightMessage); ok {
  162. w.logger.Debug("WAL write end height message", "height", endMsg.Height, "stopHeight", w.heightToStop)
  163. if endMsg.Height == w.heightToStop {
  164. w.logger.Debug("Stopping WAL at height", "height", endMsg.Height)
  165. w.signalWhenStopsTo <- struct{}{}
  166. w.stopped = true
  167. return nil
  168. }
  169. }
  170. w.logger.Debug("WAL Write Message", "msg", m)
  171. err := w.enc.Encode(&TimedWALMessage{fixedTime, m})
  172. if err != nil {
  173. panic(fmt.Sprintf("failed to encode the msg %v", m))
  174. }
  175. return nil
  176. }
  177. func (w *byteBufferWAL) WriteSync(m WALMessage) error {
  178. return w.Write(m)
  179. }
  180. func (w *byteBufferWAL) FlushAndSync() error { return nil }
  181. func (w *byteBufferWAL) SearchForEndHeight(
  182. height int64,
  183. options *WALSearchOptions) (rd io.ReadCloser, found bool, err error) {
  184. return nil, false, nil
  185. }
  186. func (w *byteBufferWAL) Start(context.Context) error { return nil }
  187. func (w *byteBufferWAL) Stop() {}
  188. func (w *byteBufferWAL) Wait() {}