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.

673 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. thisBlockCommit = &types.Commit{
  459. BlockID: p.BlockID,
  460. Precommits: []*types.CommitSig{p.CommitSig()},
  461. }
  462. }
  463. }
  464. }
  465. // grab the last block too
  466. var block = new(types.Block)
  467. _, err = cdc.UnmarshalBinaryLengthPrefixedReader(thisBlockParts.GetReader(), block, 0)
  468. if err != nil {
  469. panic(err)
  470. }
  471. if block.Height != height+1 {
  472. panic(fmt.Sprintf("read bad block from wal. got height %d, expected %d", block.Height, height+1))
  473. }
  474. commitHeight := thisBlockCommit.Precommits[0].Height
  475. if commitHeight != height+1 {
  476. panic(fmt.Sprintf("commit doesnt match. got height %d, expected %d", commitHeight, height+1))
  477. }
  478. blocks = append(blocks, block)
  479. commits = append(commits, thisBlockCommit)
  480. return blocks, commits, nil
  481. }
  482. func readPieceFromWAL(msg *TimedWALMessage) interface{} {
  483. // for logging
  484. switch m := msg.Msg.(type) {
  485. case msgInfo:
  486. switch msg := m.Msg.(type) {
  487. case *ProposalMessage:
  488. return &msg.Proposal.BlockID.PartsHeader
  489. case *BlockPartMessage:
  490. return msg.Part
  491. case *VoteMessage:
  492. return msg.Vote
  493. }
  494. case EndHeightMessage:
  495. return m
  496. }
  497. return nil
  498. }
  499. // fresh state and mock store
  500. func stateAndStore(config *cfg.Config, pubKey crypto.PubKey, appVersion version.Protocol) (dbm.DB, sm.State, *mockBlockStore) {
  501. stateDB := dbm.NewMemDB()
  502. state, _ := sm.MakeGenesisStateFromFile(config.GenesisFile())
  503. state.Version.Consensus.App = appVersion
  504. store := NewMockBlockStore(config, state.ConsensusParams)
  505. return stateDB, state, store
  506. }
  507. //----------------------------------
  508. // mock block store
  509. type mockBlockStore struct {
  510. config *cfg.Config
  511. params types.ConsensusParams
  512. chain []*types.Block
  513. commits []*types.Commit
  514. }
  515. // TODO: NewBlockStore(db.NewMemDB) ...
  516. func NewMockBlockStore(config *cfg.Config, params types.ConsensusParams) *mockBlockStore {
  517. return &mockBlockStore{config, params, nil, nil}
  518. }
  519. func (bs *mockBlockStore) Height() int64 { return int64(len(bs.chain)) }
  520. func (bs *mockBlockStore) LoadBlock(height int64) *types.Block { return bs.chain[height-1] }
  521. func (bs *mockBlockStore) LoadBlockMeta(height int64) *types.BlockMeta {
  522. block := bs.chain[height-1]
  523. return &types.BlockMeta{
  524. BlockID: types.BlockID{block.Hash(), block.MakePartSet(types.BlockPartSizeBytes).Header()},
  525. Header: block.Header,
  526. }
  527. }
  528. func (bs *mockBlockStore) LoadBlockPart(height int64, index int) *types.Part { return nil }
  529. func (bs *mockBlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) {
  530. }
  531. func (bs *mockBlockStore) LoadBlockCommit(height int64) *types.Commit {
  532. return bs.commits[height-1]
  533. }
  534. func (bs *mockBlockStore) LoadSeenCommit(height int64) *types.Commit {
  535. return bs.commits[height-1]
  536. }
  537. //----------------------------------------
  538. func TestInitChainUpdateValidators(t *testing.T) {
  539. val, _ := types.RandValidator(true, 10)
  540. vals := types.NewValidatorSet([]*types.Validator{val})
  541. app := &initChainApp{vals: types.TM2PB.ValidatorUpdates(vals)}
  542. clientCreator := proxy.NewLocalClientCreator(app)
  543. config := ResetConfig("proxy_test_")
  544. privVal := privval.LoadFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile())
  545. stateDB, state, store := stateAndStore(config, privVal.GetPubKey(), 0x0)
  546. oldValAddr := state.Validators.Validators[0].Address
  547. // now start the app using the handshake - it should sync
  548. genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())
  549. handshaker := NewHandshaker(stateDB, state, store, genDoc)
  550. proxyApp := proxy.NewAppConns(clientCreator)
  551. if err := proxyApp.Start(); err != nil {
  552. t.Fatalf("Error starting proxy app connections: %v", err)
  553. }
  554. defer proxyApp.Stop()
  555. if err := handshaker.Handshake(proxyApp); err != nil {
  556. t.Fatalf("Error on abci handshake: %v", err)
  557. }
  558. // reload the state, check the validator set was updated
  559. state = sm.LoadState(stateDB)
  560. newValAddr := state.Validators.Validators[0].Address
  561. expectValAddr := val.Address
  562. assert.NotEqual(t, oldValAddr, newValAddr)
  563. assert.Equal(t, newValAddr, expectValAddr)
  564. }
  565. // returns the vals on InitChain
  566. type initChainApp struct {
  567. abci.BaseApplication
  568. vals []abci.ValidatorUpdate
  569. }
  570. func (ica *initChainApp) InitChain(req abci.RequestInitChain) abci.ResponseInitChain {
  571. return abci.ResponseInitChain{
  572. Validators: ica.vals,
  573. }
  574. }