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.

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