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.

205 lines
6.5 KiB

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