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.

203 lines
6.5 KiB

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