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.

671 lines
20 KiB

  1. package consensus
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "path"
  10. "runtime"
  11. "testing"
  12. "time"
  13. "github.com/stretchr/testify/assert"
  14. "github.com/stretchr/testify/require"
  15. "github.com/tendermint/tendermint/abci/example/kvstore"
  16. abci "github.com/tendermint/tendermint/abci/types"
  17. "github.com/tendermint/tendermint/crypto"
  18. auto "github.com/tendermint/tendermint/libs/autofile"
  19. dbm "github.com/tendermint/tendermint/libs/db"
  20. "github.com/tendermint/tendermint/version"
  21. cfg "github.com/tendermint/tendermint/config"
  22. "github.com/tendermint/tendermint/libs/log"
  23. "github.com/tendermint/tendermint/privval"
  24. "github.com/tendermint/tendermint/proxy"
  25. sm "github.com/tendermint/tendermint/state"
  26. "github.com/tendermint/tendermint/types"
  27. )
  28. var consensusReplayConfig *cfg.Config
  29. func init() {
  30. consensusReplayConfig = ResetConfig("consensus_replay_test")
  31. }
  32. // These tests ensure we can always recover from failure at any part of the consensus process.
  33. // There are two general failure scenarios: failure during consensus, and failure while applying the block.
  34. // Only the latter interacts with the app and store,
  35. // but the former has to deal with restrictions on re-use of priv_validator keys.
  36. // The `WAL Tests` are for failures during the consensus;
  37. // the `Handshake Tests` are for failures in applying the block.
  38. // With the help of the WAL, we can recover from it all!
  39. //------------------------------------------------------------------------------------------
  40. // WAL Tests
  41. // TODO: It would be better to verify explicitly which states we can recover from without the wal
  42. // and which ones we need the wal for - then we'd also be able to only flush the
  43. // wal writer when we need to, instead of with every message.
  44. func startNewConsensusStateAndWaitForBlock(t *testing.T, lastBlockHeight int64, blockDB dbm.DB, stateDB dbm.DB) {
  45. logger := log.TestingLogger()
  46. state, _ := sm.LoadStateFromDBOrGenesisFile(stateDB, consensusReplayConfig.GenesisFile())
  47. privValidator := loadPrivValidator(consensusReplayConfig)
  48. cs := newConsensusStateWithConfigAndBlockStore(consensusReplayConfig, state, privValidator, kvstore.NewKVStoreApplication(), blockDB)
  49. cs.SetLogger(logger)
  50. bytes, _ := ioutil.ReadFile(cs.config.WalFile())
  51. // fmt.Printf("====== WAL: \n\r%s\n", bytes)
  52. t.Logf("====== WAL: \n\r%X\n", bytes)
  53. err := cs.Start()
  54. require.NoError(t, err)
  55. defer cs.Stop()
  56. // This is just a signal that we haven't halted; its not something contained
  57. // in the WAL itself. Assuming the consensus state is running, replay of any
  58. // WAL, including the empty one, should eventually be followed by a new
  59. // block, or else something is wrong.
  60. newBlockSub, err := cs.eventBus.Subscribe(context.Background(), testSubscriber, types.EventQueryNewBlock)
  61. require.NoError(t, err)
  62. select {
  63. case <-newBlockSub.Out():
  64. case <-newBlockSub.Cancelled():
  65. t.Fatal("newBlockSub was cancelled")
  66. case <-time.After(60 * time.Second):
  67. t.Fatal("Timed out waiting for new block (see trace above)")
  68. }
  69. }
  70. func sendTxs(cs *ConsensusState, ctx context.Context) {
  71. for i := 0; i < 256; i++ {
  72. select {
  73. case <-ctx.Done():
  74. return
  75. default:
  76. tx := []byte{byte(i)}
  77. assertMempool(cs.txNotifier).CheckTx(tx, nil)
  78. i++
  79. }
  80. }
  81. }
  82. // TestWALCrash uses crashing WAL to test we can recover from any WAL failure.
  83. func TestWALCrash(t *testing.T) {
  84. testCases := []struct {
  85. name string
  86. initFn func(dbm.DB, *ConsensusState, context.Context)
  87. heightToStop int64
  88. }{
  89. {"empty block",
  90. func(stateDB dbm.DB, cs *ConsensusState, ctx context.Context) {},
  91. 1},
  92. {"many non-empty blocks",
  93. func(stateDB dbm.DB, cs *ConsensusState, ctx context.Context) {
  94. go sendTxs(cs, ctx)
  95. },
  96. 3},
  97. }
  98. for _, tc := range testCases {
  99. t.Run(tc.name, func(t *testing.T) {
  100. crashWALandCheckLiveness(t, tc.initFn, tc.heightToStop)
  101. })
  102. }
  103. }
  104. func crashWALandCheckLiveness(t *testing.T, initFn func(dbm.DB, *ConsensusState, context.Context), heightToStop int64) {
  105. walPaniced := make(chan error)
  106. crashingWal := &crashingWAL{panicCh: walPaniced, heightToStop: heightToStop}
  107. i := 1
  108. LOOP:
  109. for {
  110. // fmt.Printf("====== LOOP %d\n", i)
  111. t.Logf("====== LOOP %d\n", i)
  112. // create consensus state from a clean slate
  113. logger := log.NewNopLogger()
  114. stateDB := dbm.NewMemDB()
  115. state, _ := sm.MakeGenesisStateFromFile(consensusReplayConfig.GenesisFile())
  116. privValidator := loadPrivValidator(consensusReplayConfig)
  117. blockDB := dbm.NewMemDB()
  118. cs := newConsensusStateWithConfigAndBlockStore(consensusReplayConfig, state, privValidator, kvstore.NewKVStoreApplication(), blockDB)
  119. cs.SetLogger(logger)
  120. // start sending transactions
  121. ctx, cancel := context.WithCancel(context.Background())
  122. initFn(stateDB, cs, ctx)
  123. // clean up WAL file from the previous iteration
  124. walFile := cs.config.WalFile()
  125. os.Remove(walFile)
  126. // set crashing WAL
  127. csWal, err := cs.OpenWAL(walFile)
  128. require.NoError(t, err)
  129. crashingWal.next = csWal
  130. // reset the message counter
  131. crashingWal.msgIndex = 1
  132. cs.wal = crashingWal
  133. // start consensus state
  134. err = cs.Start()
  135. require.NoError(t, err)
  136. i++
  137. select {
  138. case err := <-walPaniced:
  139. t.Logf("WAL paniced: %v", err)
  140. // make sure we can make blocks after a crash
  141. startNewConsensusStateAndWaitForBlock(t, cs.Height, blockDB, stateDB)
  142. // stop consensus state and transactions sender (initFn)
  143. cs.Stop()
  144. cancel()
  145. // if we reached the required height, exit
  146. if _, ok := err.(ReachedHeightToStopError); ok {
  147. break LOOP
  148. }
  149. case <-time.After(10 * time.Second):
  150. t.Fatal("WAL did not panic for 10 seconds (check the log)")
  151. }
  152. }
  153. }
  154. // crashingWAL is a WAL which crashes or rather simulates a crash during Save
  155. // (before and after). It remembers a message for which we last panicked
  156. // (lastPanicedForMsgIndex), so we don't panic for it in subsequent iterations.
  157. type crashingWAL struct {
  158. next WAL
  159. panicCh chan error
  160. heightToStop int64
  161. msgIndex int // current message index
  162. lastPanicedForMsgIndex int // last message for which we panicked
  163. }
  164. // WALWriteError indicates a WAL crash.
  165. type WALWriteError struct {
  166. msg string
  167. }
  168. func (e WALWriteError) Error() string {
  169. return e.msg
  170. }
  171. // ReachedHeightToStopError indicates we've reached the required consensus
  172. // height and may exit.
  173. type ReachedHeightToStopError struct {
  174. height int64
  175. }
  176. func (e ReachedHeightToStopError) Error() string {
  177. return fmt.Sprintf("reached height to stop %d", e.height)
  178. }
  179. // Write simulate WAL's crashing by sending an error to the panicCh and then
  180. // exiting the cs.receiveRoutine.
  181. func (w *crashingWAL) Write(m WALMessage) {
  182. if endMsg, ok := m.(EndHeightMessage); ok {
  183. if endMsg.Height == w.heightToStop {
  184. w.panicCh <- ReachedHeightToStopError{endMsg.Height}
  185. runtime.Goexit()
  186. } else {
  187. w.next.Write(m)
  188. }
  189. return
  190. }
  191. if w.msgIndex > w.lastPanicedForMsgIndex {
  192. w.lastPanicedForMsgIndex = w.msgIndex
  193. _, file, line, _ := runtime.Caller(1)
  194. w.panicCh <- WALWriteError{fmt.Sprintf("failed to write %T to WAL (fileline: %s:%d)", m, file, line)}
  195. runtime.Goexit()
  196. } else {
  197. w.msgIndex++
  198. w.next.Write(m)
  199. }
  200. }
  201. func (w *crashingWAL) WriteSync(m WALMessage) {
  202. w.Write(m)
  203. }
  204. func (w *crashingWAL) Group() *auto.Group { return w.next.Group() }
  205. func (w *crashingWAL) SearchForEndHeight(height int64, options *WALSearchOptions) (gr *auto.GroupReader, found bool, err error) {
  206. return w.next.SearchForEndHeight(height, options)
  207. }
  208. func (w *crashingWAL) Start() error { return w.next.Start() }
  209. func (w *crashingWAL) Stop() error { return w.next.Stop() }
  210. func (w *crashingWAL) Wait() { w.next.Wait() }
  211. //------------------------------------------------------------------------------------------
  212. // Handshake Tests
  213. const (
  214. NUM_BLOCKS = 6
  215. )
  216. var (
  217. mempool = sm.MockMempool{}
  218. evpool = sm.MockEvidencePool{}
  219. )
  220. //---------------------------------------
  221. // Test handshake/replay
  222. // 0 - all synced up
  223. // 1 - saved block but app and state are behind
  224. // 2 - save block and committed but state is behind
  225. var modes = []uint{0, 1, 2}
  226. // Sync from scratch
  227. func TestHandshakeReplayAll(t *testing.T) {
  228. for _, m := range modes {
  229. testHandshakeReplay(t, 0, m)
  230. }
  231. }
  232. // Sync many, not from scratch
  233. func TestHandshakeReplaySome(t *testing.T) {
  234. for _, m := range modes {
  235. testHandshakeReplay(t, 1, m)
  236. }
  237. }
  238. // Sync from lagging by one
  239. func TestHandshakeReplayOne(t *testing.T) {
  240. for _, m := range modes {
  241. testHandshakeReplay(t, NUM_BLOCKS-1, m)
  242. }
  243. }
  244. // Sync from caught up
  245. func TestHandshakeReplayNone(t *testing.T) {
  246. for _, m := range modes {
  247. testHandshakeReplay(t, NUM_BLOCKS, m)
  248. }
  249. }
  250. func tempWALWithData(data []byte) string {
  251. walFile, err := ioutil.TempFile("", "wal")
  252. if err != nil {
  253. panic(fmt.Errorf("failed to create temp WAL file: %v", err))
  254. }
  255. _, err = walFile.Write(data)
  256. if err != nil {
  257. panic(fmt.Errorf("failed to write to temp WAL file: %v", err))
  258. }
  259. if err := walFile.Close(); err != nil {
  260. panic(fmt.Errorf("failed to close temp WAL file: %v", err))
  261. }
  262. return walFile.Name()
  263. }
  264. // Make some blocks. Start a fresh app and apply nBlocks blocks. Then restart the app and sync it up with the remaining blocks
  265. func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) {
  266. config := ResetConfig("proxy_test_")
  267. walBody, err := WALWithNBlocks(NUM_BLOCKS)
  268. require.NoError(t, err)
  269. walFile := tempWALWithData(walBody)
  270. config.Consensus.SetWalFile(walFile)
  271. privVal := privval.LoadFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile())
  272. wal, err := NewWAL(walFile)
  273. require.NoError(t, err)
  274. wal.SetLogger(log.TestingLogger())
  275. err = wal.Start()
  276. require.NoError(t, err)
  277. defer wal.Stop()
  278. chain, commits, err := makeBlockchainFromWAL(wal)
  279. require.NoError(t, err)
  280. stateDB, state, store := stateAndStore(config, privVal.GetPubKey(), kvstore.ProtocolVersion)
  281. store.chain = chain
  282. store.commits = commits
  283. // run the chain through state.ApplyBlock to build up the tendermint state
  284. state = buildTMStateFromChain(config, stateDB, state, chain, mode)
  285. latestAppHash := state.AppHash
  286. // make a new client creator
  287. kvstoreApp := kvstore.NewPersistentKVStoreApplication(path.Join(config.DBDir(), "2"))
  288. clientCreator2 := proxy.NewLocalClientCreator(kvstoreApp)
  289. if nBlocks > 0 {
  290. // run nBlocks against a new client to build up the app state.
  291. // use a throwaway tendermint state
  292. proxyApp := proxy.NewAppConns(clientCreator2)
  293. stateDB, state, _ := stateAndStore(config, privVal.GetPubKey(), kvstore.ProtocolVersion)
  294. buildAppStateFromChain(proxyApp, stateDB, state, chain, nBlocks, mode)
  295. }
  296. // now start the app using the handshake - it should sync
  297. genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())
  298. handshaker := NewHandshaker(stateDB, state, store, genDoc)
  299. proxyApp := proxy.NewAppConns(clientCreator2)
  300. if err := proxyApp.Start(); err != nil {
  301. t.Fatalf("Error starting proxy app connections: %v", err)
  302. }
  303. defer proxyApp.Stop()
  304. if err := handshaker.Handshake(proxyApp); err != nil {
  305. t.Fatalf("Error on abci handshake: %v", err)
  306. }
  307. // get the latest app hash from the app
  308. res, err := proxyApp.Query().InfoSync(abci.RequestInfo{Version: ""})
  309. if err != nil {
  310. t.Fatal(err)
  311. }
  312. // the app hash should be synced up
  313. if !bytes.Equal(latestAppHash, res.LastBlockAppHash) {
  314. t.Fatalf("Expected app hashes to match after handshake/replay. got %X, expected %X", res.LastBlockAppHash, latestAppHash)
  315. }
  316. expectedBlocksToSync := NUM_BLOCKS - nBlocks
  317. if nBlocks == NUM_BLOCKS && mode > 0 {
  318. expectedBlocksToSync++
  319. } else if nBlocks > 0 && mode == 1 {
  320. expectedBlocksToSync++
  321. }
  322. if handshaker.NBlocks() != expectedBlocksToSync {
  323. t.Fatalf("Expected handshake to sync %d blocks, got %d", expectedBlocksToSync, handshaker.NBlocks())
  324. }
  325. }
  326. func applyBlock(stateDB dbm.DB, st sm.State, blk *types.Block, proxyApp proxy.AppConns) sm.State {
  327. testPartSize := types.BlockPartSizeBytes
  328. blockExec := sm.NewBlockExecutor(stateDB, log.TestingLogger(), proxyApp.Consensus(), mempool, evpool)
  329. blkID := types.BlockID{blk.Hash(), blk.MakePartSet(testPartSize).Header()}
  330. newState, err := blockExec.ApplyBlock(st, blkID, blk)
  331. if err != nil {
  332. panic(err)
  333. }
  334. return newState
  335. }
  336. func buildAppStateFromChain(proxyApp proxy.AppConns, stateDB dbm.DB,
  337. state sm.State, chain []*types.Block, nBlocks int, mode uint) {
  338. // start a new app without handshake, play nBlocks blocks
  339. if err := proxyApp.Start(); err != nil {
  340. panic(err)
  341. }
  342. defer proxyApp.Stop()
  343. validators := types.TM2PB.ValidatorUpdates(state.Validators)
  344. if _, err := proxyApp.Consensus().InitChainSync(abci.RequestInitChain{
  345. Validators: validators,
  346. }); err != nil {
  347. panic(err)
  348. }
  349. switch mode {
  350. case 0:
  351. for i := 0; i < nBlocks; i++ {
  352. block := chain[i]
  353. state = applyBlock(stateDB, state, block, proxyApp)
  354. }
  355. case 1, 2:
  356. for i := 0; i < nBlocks-1; i++ {
  357. block := chain[i]
  358. state = applyBlock(stateDB, state, block, proxyApp)
  359. }
  360. if mode == 2 {
  361. // update the kvstore height and apphash
  362. // as if we ran commit but not
  363. state = applyBlock(stateDB, state, chain[nBlocks-1], proxyApp)
  364. }
  365. }
  366. }
  367. func buildTMStateFromChain(config *cfg.Config, stateDB dbm.DB, state sm.State, chain []*types.Block, mode uint) sm.State {
  368. // run the whole chain against this client to build up the tendermint state
  369. clientCreator := proxy.NewLocalClientCreator(kvstore.NewPersistentKVStoreApplication(path.Join(config.DBDir(), "1")))
  370. proxyApp := proxy.NewAppConns(clientCreator)
  371. if err := proxyApp.Start(); err != nil {
  372. panic(err)
  373. }
  374. defer proxyApp.Stop()
  375. validators := types.TM2PB.ValidatorUpdates(state.Validators)
  376. if _, err := proxyApp.Consensus().InitChainSync(abci.RequestInitChain{
  377. Validators: validators,
  378. }); err != nil {
  379. panic(err)
  380. }
  381. switch mode {
  382. case 0:
  383. // sync right up
  384. for _, block := range chain {
  385. state = applyBlock(stateDB, state, block, proxyApp)
  386. }
  387. case 1, 2:
  388. // sync up to the penultimate as if we stored the block.
  389. // whether we commit or not depends on the appHash
  390. for _, block := range chain[:len(chain)-1] {
  391. state = applyBlock(stateDB, state, block, proxyApp)
  392. }
  393. // apply the final block to a state copy so we can
  394. // get the right next appHash but keep the state back
  395. applyBlock(stateDB, state, chain[len(chain)-1], proxyApp)
  396. }
  397. return state
  398. }
  399. //--------------------------
  400. // utils for making blocks
  401. func makeBlockchainFromWAL(wal WAL) ([]*types.Block, []*types.Commit, error) {
  402. // Search for height marker
  403. gr, found, err := wal.SearchForEndHeight(0, &WALSearchOptions{})
  404. if err != nil {
  405. return nil, nil, err
  406. }
  407. if !found {
  408. return nil, nil, fmt.Errorf("WAL does not contain height %d.", 1)
  409. }
  410. defer gr.Close() // nolint: errcheck
  411. // log.Notice("Build a blockchain by reading from the WAL")
  412. var blocks []*types.Block
  413. var commits []*types.Commit
  414. var thisBlockParts *types.PartSet
  415. var thisBlockCommit *types.Commit
  416. var height int64
  417. dec := NewWALDecoder(gr)
  418. for {
  419. msg, err := dec.Decode()
  420. if err == io.EOF {
  421. break
  422. } else if err != nil {
  423. return nil, nil, err
  424. }
  425. piece := readPieceFromWAL(msg)
  426. if piece == nil {
  427. continue
  428. }
  429. switch p := piece.(type) {
  430. case EndHeightMessage:
  431. // if its not the first one, we have a full block
  432. if thisBlockParts != nil {
  433. var block = new(types.Block)
  434. _, err = cdc.UnmarshalBinaryLengthPrefixedReader(thisBlockParts.GetReader(), block, 0)
  435. if err != nil {
  436. panic(err)
  437. }
  438. if block.Height != height+1 {
  439. panic(fmt.Sprintf("read bad block from wal. got height %d, expected %d", block.Height, height+1))
  440. }
  441. commitHeight := thisBlockCommit.Precommits[0].Height
  442. if commitHeight != height+1 {
  443. panic(fmt.Sprintf("commit doesnt match. got height %d, expected %d", commitHeight, height+1))
  444. }
  445. blocks = append(blocks, block)
  446. commits = append(commits, thisBlockCommit)
  447. height++
  448. }
  449. case *types.PartSetHeader:
  450. thisBlockParts = types.NewPartSetFromHeader(*p)
  451. case *types.Part:
  452. _, err := thisBlockParts.AddPart(p)
  453. if err != nil {
  454. return nil, nil, err
  455. }
  456. case *types.Vote:
  457. if p.Type == types.PrecommitType {
  458. commitSigs := []*types.CommitSig{p.CommitSig()}
  459. thisBlockCommit = types.NewCommit(p.BlockID, commitSigs)
  460. }
  461. }
  462. }
  463. // grab the last block too
  464. var block = new(types.Block)
  465. _, err = cdc.UnmarshalBinaryLengthPrefixedReader(thisBlockParts.GetReader(), block, 0)
  466. if err != nil {
  467. panic(err)
  468. }
  469. if block.Height != height+1 {
  470. panic(fmt.Sprintf("read bad block from wal. got height %d, expected %d", block.Height, height+1))
  471. }
  472. commitHeight := thisBlockCommit.Precommits[0].Height
  473. if commitHeight != height+1 {
  474. panic(fmt.Sprintf("commit doesnt match. got height %d, expected %d", commitHeight, height+1))
  475. }
  476. blocks = append(blocks, block)
  477. commits = append(commits, thisBlockCommit)
  478. return blocks, commits, nil
  479. }
  480. func readPieceFromWAL(msg *TimedWALMessage) interface{} {
  481. // for logging
  482. switch m := msg.Msg.(type) {
  483. case msgInfo:
  484. switch msg := m.Msg.(type) {
  485. case *ProposalMessage:
  486. return &msg.Proposal.BlockID.PartsHeader
  487. case *BlockPartMessage:
  488. return msg.Part
  489. case *VoteMessage:
  490. return msg.Vote
  491. }
  492. case EndHeightMessage:
  493. return m
  494. }
  495. return nil
  496. }
  497. // fresh state and mock store
  498. func stateAndStore(config *cfg.Config, pubKey crypto.PubKey, appVersion version.Protocol) (dbm.DB, sm.State, *mockBlockStore) {
  499. stateDB := dbm.NewMemDB()
  500. state, _ := sm.MakeGenesisStateFromFile(config.GenesisFile())
  501. state.Version.Consensus.App = appVersion
  502. store := NewMockBlockStore(config, state.ConsensusParams)
  503. return stateDB, state, store
  504. }
  505. //----------------------------------
  506. // mock block store
  507. type mockBlockStore struct {
  508. config *cfg.Config
  509. params types.ConsensusParams
  510. chain []*types.Block
  511. commits []*types.Commit
  512. }
  513. // TODO: NewBlockStore(db.NewMemDB) ...
  514. func NewMockBlockStore(config *cfg.Config, params types.ConsensusParams) *mockBlockStore {
  515. return &mockBlockStore{config, params, nil, nil}
  516. }
  517. func (bs *mockBlockStore) Height() int64 { return int64(len(bs.chain)) }
  518. func (bs *mockBlockStore) LoadBlock(height int64) *types.Block { return bs.chain[height-1] }
  519. func (bs *mockBlockStore) LoadBlockMeta(height int64) *types.BlockMeta {
  520. block := bs.chain[height-1]
  521. return &types.BlockMeta{
  522. BlockID: types.BlockID{block.Hash(), block.MakePartSet(types.BlockPartSizeBytes).Header()},
  523. Header: block.Header,
  524. }
  525. }
  526. func (bs *mockBlockStore) LoadBlockPart(height int64, index int) *types.Part { return nil }
  527. func (bs *mockBlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) {
  528. }
  529. func (bs *mockBlockStore) LoadBlockCommit(height int64) *types.Commit {
  530. return bs.commits[height-1]
  531. }
  532. func (bs *mockBlockStore) LoadSeenCommit(height int64) *types.Commit {
  533. return bs.commits[height-1]
  534. }
  535. //----------------------------------------
  536. func TestInitChainUpdateValidators(t *testing.T) {
  537. val, _ := types.RandValidator(true, 10)
  538. vals := types.NewValidatorSet([]*types.Validator{val})
  539. app := &initChainApp{vals: types.TM2PB.ValidatorUpdates(vals)}
  540. clientCreator := proxy.NewLocalClientCreator(app)
  541. config := ResetConfig("proxy_test_")
  542. privVal := privval.LoadFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile())
  543. stateDB, state, store := stateAndStore(config, privVal.GetPubKey(), 0x0)
  544. oldValAddr := state.Validators.Validators[0].Address
  545. // now start the app using the handshake - it should sync
  546. genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())
  547. handshaker := NewHandshaker(stateDB, state, store, genDoc)
  548. proxyApp := proxy.NewAppConns(clientCreator)
  549. if err := proxyApp.Start(); err != nil {
  550. t.Fatalf("Error starting proxy app connections: %v", err)
  551. }
  552. defer proxyApp.Stop()
  553. if err := handshaker.Handshake(proxyApp); err != nil {
  554. t.Fatalf("Error on abci handshake: %v", err)
  555. }
  556. // reload the state, check the validator set was updated
  557. state = sm.LoadState(stateDB)
  558. newValAddr := state.Validators.Validators[0].Address
  559. expectValAddr := val.Address
  560. assert.NotEqual(t, oldValAddr, newValAddr)
  561. assert.Equal(t, newValAddr, expectValAddr)
  562. }
  563. // returns the vals on InitChain
  564. type initChainApp struct {
  565. abci.BaseApplication
  566. vals []abci.ValidatorUpdate
  567. }
  568. func (ica *initChainApp) InitChain(req abci.RequestInitChain) abci.ResponseInitChain {
  569. return abci.ResponseInitChain{
  570. Validators: ica.vals,
  571. }
  572. }