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.

229 lines
7.0 KiB

  1. package consensus
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "io"
  7. "path/filepath"
  8. "testing"
  9. "time"
  10. db "github.com/tendermint/tm-db"
  11. "github.com/tendermint/tendermint/abci/example/kvstore"
  12. cfg "github.com/tendermint/tendermint/config"
  13. "github.com/tendermint/tendermint/libs/log"
  14. tmrand "github.com/tendermint/tendermint/libs/rand"
  15. "github.com/tendermint/tendermint/privval"
  16. "github.com/tendermint/tendermint/proxy"
  17. sm "github.com/tendermint/tendermint/state"
  18. "github.com/tendermint/tendermint/store"
  19. "github.com/tendermint/tendermint/types"
  20. )
  21. // WALGenerateNBlocks generates a consensus WAL. It does this by spinning up a
  22. // stripped down version of node (proxy app, event bus, consensus state) with a
  23. // persistent kvstore application and special consensus wal instance
  24. // (byteBufferWAL) and waits until numBlocks are created.
  25. // If the node fails to produce given numBlocks, it returns an error.
  26. func WALGenerateNBlocks(t *testing.T, wr io.Writer, numBlocks int) (err error) {
  27. config := getConfig(t)
  28. app := kvstore.NewPersistentKVStoreApplication(filepath.Join(config.DBDir(), "wal_generator"))
  29. logger := log.TestingLogger().With("wal_generator", "wal_generator")
  30. logger.Info("generating WAL (last height msg excluded)", "numBlocks", numBlocks)
  31. // ///////////////////////////////////////////////////////////////////////////
  32. // COPY PASTE FROM node.go WITH A FEW MODIFICATIONS
  33. // NOTE: we can't import node package because of circular dependency.
  34. // NOTE: we don't do handshake so need to set state.Version.Consensus.App directly.
  35. privValidatorKeyFile := config.PrivValidatorKeyFile()
  36. privValidatorStateFile := config.PrivValidatorStateFile()
  37. privValidator := privval.LoadOrGenFilePV(privValidatorKeyFile, privValidatorStateFile)
  38. genDoc, err := types.GenesisDocFromFile(config.GenesisFile())
  39. if err != nil {
  40. return fmt.Errorf("failed to read genesis file: %w", err)
  41. }
  42. blockStoreDB := db.NewMemDB()
  43. stateDB := blockStoreDB
  44. stateStore := sm.NewStore(stateDB)
  45. state, err := sm.MakeGenesisState(genDoc)
  46. if err != nil {
  47. return fmt.Errorf("failed to make genesis state: %w", err)
  48. }
  49. state.Version.Consensus.App = kvstore.ProtocolVersion
  50. if err = stateStore.Save(state); err != nil {
  51. t.Error(err)
  52. }
  53. blockStore := store.NewBlockStore(blockStoreDB)
  54. proxyApp := proxy.NewAppConns(proxy.NewLocalClientCreator(app))
  55. proxyApp.SetLogger(logger.With("module", "proxy"))
  56. if err := proxyApp.Start(); err != nil {
  57. return fmt.Errorf("failed to start proxy app connections: %w", err)
  58. }
  59. t.Cleanup(func() {
  60. if err := proxyApp.Stop(); err != nil {
  61. t.Error(err)
  62. }
  63. })
  64. eventBus := types.NewEventBus()
  65. eventBus.SetLogger(logger.With("module", "events"))
  66. if err := eventBus.Start(); err != nil {
  67. return fmt.Errorf("failed to start event bus: %w", err)
  68. }
  69. t.Cleanup(func() {
  70. if err := eventBus.Stop(); err != nil {
  71. t.Error(err)
  72. }
  73. })
  74. mempool := emptyMempool{}
  75. evpool := sm.EmptyEvidencePool{}
  76. blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyApp.Consensus(), mempool, evpool)
  77. consensusState := NewState(config.Consensus, state.Copy(),
  78. blockExec, blockStore, mempool, evpool, map[int64]Misbehavior{})
  79. consensusState.SetLogger(logger)
  80. consensusState.SetEventBus(eventBus)
  81. if privValidator != nil {
  82. consensusState.SetPrivValidator(privValidator)
  83. }
  84. // END OF COPY PASTE
  85. // ///////////////////////////////////////////////////////////////////////////
  86. // set consensus wal to buffered WAL, which will write all incoming msgs to buffer
  87. numBlocksWritten := make(chan struct{})
  88. wal := newByteBufferWAL(logger, NewWALEncoder(wr), int64(numBlocks), numBlocksWritten)
  89. // see wal.go#103
  90. if err := wal.Write(EndHeightMessage{0}); err != nil {
  91. t.Error(err)
  92. }
  93. consensusState.wal = wal
  94. if err := consensusState.Start(); err != nil {
  95. return fmt.Errorf("failed to start consensus state: %w", err)
  96. }
  97. select {
  98. case <-numBlocksWritten:
  99. if err := consensusState.Stop(); err != nil {
  100. t.Error(err)
  101. }
  102. return nil
  103. case <-time.After(1 * time.Minute):
  104. if err := consensusState.Stop(); err != nil {
  105. t.Error(err)
  106. }
  107. return fmt.Errorf("waited too long for tendermint to produce %d blocks (grep logs for `wal_generator`)", numBlocks)
  108. }
  109. }
  110. // WALWithNBlocks returns a WAL content with numBlocks.
  111. func WALWithNBlocks(t *testing.T, numBlocks int) (data []byte, err error) {
  112. var b bytes.Buffer
  113. wr := bufio.NewWriter(&b)
  114. if err := WALGenerateNBlocks(t, wr, numBlocks); err != nil {
  115. return []byte{}, err
  116. }
  117. wr.Flush()
  118. return b.Bytes(), nil
  119. }
  120. func randPort() int {
  121. // returns between base and base + spread
  122. base, spread := 20000, 20000
  123. return base + tmrand.Intn(spread)
  124. }
  125. func makeAddrs() (string, string, string) {
  126. start := randPort()
  127. return fmt.Sprintf("tcp://127.0.0.1:%d", start),
  128. fmt.Sprintf("tcp://127.0.0.1:%d", start+1),
  129. fmt.Sprintf("tcp://127.0.0.1:%d", start+2)
  130. }
  131. // getConfig returns a config for test cases
  132. func getConfig(t *testing.T) *cfg.Config {
  133. c := cfg.ResetTestRoot(t.Name())
  134. // and we use random ports to run in parallel
  135. tm, rpc, grpc := makeAddrs()
  136. c.P2P.ListenAddress = tm
  137. c.RPC.ListenAddress = rpc
  138. c.RPC.GRPCListenAddress = grpc
  139. return c
  140. }
  141. // byteBufferWAL is a WAL which writes all msgs to a byte buffer. Writing stops
  142. // when the heightToStop is reached. Client will be notified via
  143. // signalWhenStopsTo channel.
  144. type byteBufferWAL struct {
  145. enc *WALEncoder
  146. stopped bool
  147. heightToStop int64
  148. signalWhenStopsTo chan<- struct{}
  149. logger log.Logger
  150. }
  151. // needed for determinism
  152. var fixedTime, _ = time.Parse(time.RFC3339, "2017-01-02T15:04:05Z")
  153. func newByteBufferWAL(logger log.Logger, enc *WALEncoder, nBlocks int64, signalStop chan<- struct{}) *byteBufferWAL {
  154. return &byteBufferWAL{
  155. enc: enc,
  156. heightToStop: nBlocks,
  157. signalWhenStopsTo: signalStop,
  158. logger: logger,
  159. }
  160. }
  161. // Save writes message to the internal buffer except when heightToStop is
  162. // reached, in which case it will signal the caller via signalWhenStopsTo and
  163. // skip writing.
  164. func (w *byteBufferWAL) Write(m WALMessage) error {
  165. if w.stopped {
  166. w.logger.Debug("WAL already stopped. Not writing message", "msg", m)
  167. return nil
  168. }
  169. if endMsg, ok := m.(EndHeightMessage); ok {
  170. w.logger.Debug("WAL write end height message", "height", endMsg.Height, "stopHeight", w.heightToStop)
  171. if endMsg.Height == w.heightToStop {
  172. w.logger.Debug("Stopping WAL at height", "height", endMsg.Height)
  173. w.signalWhenStopsTo <- struct{}{}
  174. w.stopped = true
  175. return nil
  176. }
  177. }
  178. w.logger.Debug("WAL Write Message", "msg", m)
  179. err := w.enc.Encode(&TimedWALMessage{fixedTime, m})
  180. if err != nil {
  181. panic(fmt.Sprintf("failed to encode the msg %v", m))
  182. }
  183. return nil
  184. }
  185. func (w *byteBufferWAL) WriteSync(m WALMessage) error {
  186. return w.Write(m)
  187. }
  188. func (w *byteBufferWAL) FlushAndSync() error { return nil }
  189. func (w *byteBufferWAL) SearchForEndHeight(
  190. height int64,
  191. options *WALSearchOptions) (rd io.ReadCloser, found bool, err error) {
  192. return nil, false, nil
  193. }
  194. func (w *byteBufferWAL) Start() error { return nil }
  195. func (w *byteBufferWAL) Stop() error { return nil }
  196. func (w *byteBufferWAL) Wait() {}