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.

601 lines
18 KiB

7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package consensus
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "path"
  10. "strings"
  11. "testing"
  12. "time"
  13. "github.com/tendermint/abci/example/dummy"
  14. crypto "github.com/tendermint/go-crypto"
  15. wire "github.com/tendermint/go-wire"
  16. cmn "github.com/tendermint/tmlibs/common"
  17. dbm "github.com/tendermint/tmlibs/db"
  18. cfg "github.com/tendermint/tendermint/config"
  19. "github.com/tendermint/tendermint/proxy"
  20. sm "github.com/tendermint/tendermint/state"
  21. "github.com/tendermint/tendermint/types"
  22. "github.com/tendermint/tmlibs/log"
  23. )
  24. func init() {
  25. config = ResetConfig("consensus_replay_test")
  26. }
  27. // These tests ensure we can always recover from failure at any part of the consensus process.
  28. // There are two general failure scenarios: failure during consensus, and failure while applying the block.
  29. // Only the latter interacts with the app and store,
  30. // but the former has to deal with restrictions on re-use of priv_validator keys.
  31. // The `WAL Tests` are for failures during the consensus;
  32. // the `Handshake Tests` are for failures in applying the block.
  33. // With the help of the WAL, we can recover from it all!
  34. // NOTE: Files in this dir are generated by running the `build.sh` therein.
  35. // It's a simple way to generate wals for a single block, or multiple blocks, with random transactions,
  36. // and different part sizes. The output is not deterministic, and the stepChanges may need to be adjusted
  37. // after running it (eg. sometimes small_block2 will have 5 block parts, sometimes 6).
  38. // It should only have to be re-run if there is some breaking change to the consensus data structures (eg. blocks, votes)
  39. // or to the behaviour of the app (eg. computes app hash differently)
  40. var data_dir = path.Join(cmn.GoPath, "src/github.com/tendermint/tendermint/consensus", "test_data")
  41. //------------------------------------------------------------------------------------------
  42. // WAL Tests
  43. // TODO: It would be better to verify explicitly which states we can recover from without the wal
  44. // and which ones we need the wal for - then we'd also be able to only flush the
  45. // wal writer when we need to, instead of with every message.
  46. // the priv validator changes step at these lines for a block with 1 val and 1 part
  47. var baseStepChanges = []int{3, 6, 8}
  48. // test recovery from each line in each testCase
  49. var testCases = []*testCase{
  50. newTestCase("empty_block", baseStepChanges), // empty block (has 1 block part)
  51. newTestCase("small_block1", baseStepChanges), // small block with txs in 1 block part
  52. newTestCase("small_block2", []int{3, 11, 13}), // small block with txs across 6 smaller block parts
  53. }
  54. type testCase struct {
  55. name string
  56. log string //full cs wal
  57. stepMap map[int]int8 // map lines of log to privval step
  58. proposeLine int
  59. prevoteLine int
  60. precommitLine int
  61. }
  62. func newTestCase(name string, stepChanges []int) *testCase {
  63. if len(stepChanges) != 3 {
  64. panic(cmn.Fmt("a full wal has 3 step changes! Got array %v", stepChanges))
  65. }
  66. return &testCase{
  67. name: name,
  68. log: readWAL(path.Join(data_dir, name+".cswal")),
  69. stepMap: newMapFromChanges(stepChanges),
  70. proposeLine: stepChanges[0],
  71. prevoteLine: stepChanges[1],
  72. precommitLine: stepChanges[2],
  73. }
  74. }
  75. func newMapFromChanges(changes []int) map[int]int8 {
  76. changes = append(changes, changes[2]+1) // so we add the last step change to the map
  77. m := make(map[int]int8)
  78. var count int
  79. for changeNum, nextChange := range changes {
  80. for ; count < nextChange; count++ {
  81. m[count] = int8(changeNum)
  82. }
  83. }
  84. return m
  85. }
  86. func readWAL(p string) string {
  87. b, err := ioutil.ReadFile(p)
  88. if err != nil {
  89. panic(err)
  90. }
  91. return string(b)
  92. }
  93. func writeWAL(walMsgs string) string {
  94. tempDir := os.TempDir()
  95. walDir := path.Join(tempDir, "/wal"+cmn.RandStr(12))
  96. walFile := path.Join(walDir, "wal")
  97. // Create WAL directory
  98. err := cmn.EnsureDir(walDir, 0700)
  99. if err != nil {
  100. panic(err)
  101. }
  102. // Write the needed WAL to file
  103. err = cmn.WriteFile(walFile, []byte(walMsgs), 0600)
  104. if err != nil {
  105. panic(err)
  106. }
  107. return walFile
  108. }
  109. func waitForBlock(newBlockCh chan interface{}, thisCase *testCase, i int) {
  110. after := time.After(time.Second * 10)
  111. select {
  112. case <-newBlockCh:
  113. case <-after:
  114. panic(cmn.Fmt("Timed out waiting for new block for case '%s' line %d", thisCase.name, i))
  115. }
  116. }
  117. func runReplayTest(t *testing.T, cs *ConsensusState, walFile string, newBlockCh chan interface{},
  118. thisCase *testCase, i int) {
  119. cs.config.SetWalFile(walFile)
  120. started, err := cs.Start()
  121. if err != nil {
  122. t.Fatalf("Cannot start consensus: %v", err)
  123. }
  124. if !started {
  125. t.Error("Consensus did not start")
  126. }
  127. // Wait to make a new block.
  128. // This is just a signal that we haven't halted; its not something contained in the WAL itself.
  129. // Assuming the consensus state is running, replay of any WAL, including the empty one,
  130. // should eventually be followed by a new block, or else something is wrong
  131. waitForBlock(newBlockCh, thisCase, i)
  132. cs.evsw.Stop()
  133. cs.Stop()
  134. LOOP:
  135. for {
  136. select {
  137. case <-newBlockCh:
  138. default:
  139. break LOOP
  140. }
  141. }
  142. cs.Wait()
  143. }
  144. func toPV(pv PrivValidator) *types.PrivValidator {
  145. return pv.(*types.PrivValidator)
  146. }
  147. func setupReplayTest(t *testing.T, thisCase *testCase, nLines int, crashAfter bool) (*ConsensusState, chan interface{}, string, string) {
  148. t.Log("-------------------------------------")
  149. t.Logf("Starting replay test %v (of %d lines of WAL). Crash after = %v", thisCase.name, nLines, crashAfter)
  150. lineStep := nLines
  151. if crashAfter {
  152. lineStep -= 1
  153. }
  154. split := strings.Split(thisCase.log, "\n")
  155. lastMsg := split[nLines]
  156. // we write those lines up to (not including) one with the signature
  157. walFile := writeWAL(strings.Join(split[:nLines], "\n") + "\n")
  158. cs := fixedConsensusStateDummy()
  159. // set the last step according to when we crashed vs the wal
  160. toPV(cs.privValidator).LastHeight = 1 // first block
  161. toPV(cs.privValidator).LastStep = thisCase.stepMap[lineStep]
  162. t.Logf("[WARN] setupReplayTest LastStep=%v", toPV(cs.privValidator).LastStep)
  163. newBlockCh := subscribeToEvent(cs.evsw, "tester", types.EventStringNewBlock(), 1)
  164. return cs, newBlockCh, lastMsg, walFile
  165. }
  166. func readTimedWALMessage(t *testing.T, walMsg string) TimedWALMessage {
  167. var err error
  168. var msg TimedWALMessage
  169. wire.ReadJSON(&msg, []byte(walMsg), &err)
  170. if err != nil {
  171. t.Fatalf("Error reading json data: %v", err)
  172. }
  173. return msg
  174. }
  175. //-----------------------------------------------
  176. // Test the log at every iteration, and set the privVal last step
  177. // as if the log was written after signing, before the crash
  178. func TestWALCrashAfterWrite(t *testing.T) {
  179. for _, thisCase := range testCases {
  180. split := strings.Split(thisCase.log, "\n")
  181. for i := 0; i < len(split)-1; i++ {
  182. cs, newBlockCh, _, walFile := setupReplayTest(t, thisCase, i+1, true)
  183. runReplayTest(t, cs, walFile, newBlockCh, thisCase, i+1)
  184. }
  185. }
  186. }
  187. //-----------------------------------------------
  188. // Test the log as if we crashed after signing but before writing.
  189. // This relies on privValidator.LastSignature being set
  190. func TestWALCrashBeforeWritePropose(t *testing.T) {
  191. for _, thisCase := range testCases {
  192. lineNum := thisCase.proposeLine
  193. // setup replay test where last message is a proposal
  194. cs, newBlockCh, proposalMsg, walFile := setupReplayTest(t, thisCase, lineNum, false)
  195. msg := readTimedWALMessage(t, proposalMsg)
  196. proposal := msg.Msg.(msgInfo).Msg.(*ProposalMessage)
  197. // Set LastSig
  198. toPV(cs.privValidator).LastSignBytes = types.SignBytes(cs.state.ChainID, proposal.Proposal)
  199. toPV(cs.privValidator).LastSignature = proposal.Proposal.Signature
  200. runReplayTest(t, cs, walFile, newBlockCh, thisCase, lineNum)
  201. }
  202. }
  203. func TestWALCrashBeforeWritePrevote(t *testing.T) {
  204. for _, thisCase := range testCases {
  205. testReplayCrashBeforeWriteVote(t, thisCase, thisCase.prevoteLine, types.EventStringCompleteProposal())
  206. }
  207. }
  208. func TestWALCrashBeforeWritePrecommit(t *testing.T) {
  209. for _, thisCase := range testCases {
  210. testReplayCrashBeforeWriteVote(t, thisCase, thisCase.precommitLine, types.EventStringPolka())
  211. }
  212. }
  213. func testReplayCrashBeforeWriteVote(t *testing.T, thisCase *testCase, lineNum int, eventString string) {
  214. // setup replay test where last message is a vote
  215. cs, newBlockCh, voteMsg, walFile := setupReplayTest(t, thisCase, lineNum, false)
  216. types.AddListenerForEvent(cs.evsw, "tester", eventString, func(data types.TMEventData) {
  217. msg := readTimedWALMessage(t, voteMsg)
  218. vote := msg.Msg.(msgInfo).Msg.(*VoteMessage)
  219. // Set LastSig
  220. toPV(cs.privValidator).LastSignBytes = types.SignBytes(cs.state.ChainID, vote.Vote)
  221. toPV(cs.privValidator).LastSignature = vote.Vote.Signature
  222. })
  223. runReplayTest(t, cs, walFile, newBlockCh, thisCase, lineNum)
  224. }
  225. //------------------------------------------------------------------------------------------
  226. // Handshake Tests
  227. var (
  228. NUM_BLOCKS = 6 // number of blocks in the test_data/many_blocks.cswal
  229. mempool = types.MockMempool{}
  230. testPartSize int
  231. )
  232. //---------------------------------------
  233. // Test handshake/replay
  234. // 0 - all synced up
  235. // 1 - saved block but app and state are behind
  236. // 2 - save block and committed but state is behind
  237. var modes = []uint{0, 1, 2}
  238. // Sync from scratch
  239. func TestHandshakeReplayAll(t *testing.T) {
  240. for _, m := range modes {
  241. testHandshakeReplay(t, 0, m)
  242. }
  243. }
  244. // Sync many, not from scratch
  245. func TestHandshakeReplaySome(t *testing.T) {
  246. for _, m := range modes {
  247. testHandshakeReplay(t, 1, m)
  248. }
  249. }
  250. // Sync from lagging by one
  251. func TestHandshakeReplayOne(t *testing.T) {
  252. for _, m := range modes {
  253. testHandshakeReplay(t, NUM_BLOCKS-1, m)
  254. }
  255. }
  256. // Sync from caught up
  257. func TestHandshakeReplayNone(t *testing.T) {
  258. for _, m := range modes {
  259. testHandshakeReplay(t, NUM_BLOCKS, m)
  260. }
  261. }
  262. // Make some blocks. Start a fresh app and apply nBlocks blocks. Then restart the app and sync it up with the remaining blocks
  263. func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) {
  264. config := ResetConfig("proxy_test_")
  265. // copy the many_blocks file
  266. walBody, err := cmn.ReadFile(path.Join(data_dir, "many_blocks.cswal"))
  267. if err != nil {
  268. t.Fatal(err)
  269. }
  270. walFile := writeWAL(string(walBody))
  271. config.Consensus.SetWalFile(walFile)
  272. privVal := types.LoadPrivValidator(config.PrivValidatorFile())
  273. testPartSize = config.Consensus.BlockPartSize
  274. wal, err := NewWAL(walFile, false)
  275. if err != nil {
  276. t.Fatal(err)
  277. }
  278. wal.SetLogger(log.TestingLogger())
  279. if _, err := wal.Start(); err != nil {
  280. t.Fatal(err)
  281. }
  282. chain, commits, err := makeBlockchainFromWAL(wal)
  283. if err != nil {
  284. t.Fatalf(err.Error())
  285. }
  286. state, store := stateAndStore(config, privVal.PubKey)
  287. store.chain = chain
  288. store.commits = commits
  289. // run the chain through state.ApplyBlock to build up the tendermint state
  290. latestAppHash := buildTMStateFromChain(config, state, chain, mode)
  291. // make a new client creator
  292. dummyApp := dummy.NewPersistentDummyApplication(path.Join(config.DBDir(), "2"))
  293. clientCreator2 := proxy.NewLocalClientCreator(dummyApp)
  294. if nBlocks > 0 {
  295. // run nBlocks against a new client to build up the app state.
  296. // use a throwaway tendermint state
  297. proxyApp := proxy.NewAppConns(clientCreator2, nil)
  298. state, _ := stateAndStore(config, privVal.PubKey)
  299. buildAppStateFromChain(proxyApp, state, chain, nBlocks, mode)
  300. }
  301. // now start the app using the handshake - it should sync
  302. handshaker := NewHandshaker(state, store)
  303. proxyApp := proxy.NewAppConns(clientCreator2, handshaker)
  304. if _, err := proxyApp.Start(); err != nil {
  305. t.Fatalf("Error starting proxy app connections: %v", err)
  306. }
  307. // get the latest app hash from the app
  308. res, err := proxyApp.Query().InfoSync()
  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 += 1
  319. } else if nBlocks > 0 && mode == 1 {
  320. expectedBlocksToSync += 1
  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(st *sm.State, blk *types.Block, proxyApp proxy.AppConns) {
  327. err := st.ApplyBlock(nil, proxyApp.Consensus(), blk, blk.MakePartSet(testPartSize).Header(), mempool)
  328. if err != nil {
  329. panic(err)
  330. }
  331. }
  332. func buildAppStateFromChain(proxyApp proxy.AppConns,
  333. state *sm.State, chain []*types.Block, nBlocks int, mode uint) {
  334. // start a new app without handshake, play nBlocks blocks
  335. if _, err := proxyApp.Start(); err != nil {
  336. panic(err)
  337. }
  338. validators := types.TM2PB.Validators(state.Validators)
  339. proxyApp.Consensus().InitChainSync(validators)
  340. defer proxyApp.Stop()
  341. switch mode {
  342. case 0:
  343. for i := 0; i < nBlocks; i++ {
  344. block := chain[i]
  345. applyBlock(state, block, proxyApp)
  346. }
  347. case 1, 2:
  348. for i := 0; i < nBlocks-1; i++ {
  349. block := chain[i]
  350. applyBlock(state, block, proxyApp)
  351. }
  352. if mode == 2 {
  353. // update the dummy height and apphash
  354. // as if we ran commit but not
  355. applyBlock(state, chain[nBlocks-1], proxyApp)
  356. }
  357. }
  358. }
  359. func buildTMStateFromChain(config *cfg.Config, state *sm.State, chain []*types.Block, mode uint) []byte {
  360. // run the whole chain against this client to build up the tendermint state
  361. clientCreator := proxy.NewLocalClientCreator(dummy.NewPersistentDummyApplication(path.Join(config.DBDir(), "1")))
  362. proxyApp := proxy.NewAppConns(clientCreator, nil) // sm.NewHandshaker(config, state, store, ReplayLastBlock))
  363. if _, err := proxyApp.Start(); err != nil {
  364. panic(err)
  365. }
  366. defer proxyApp.Stop()
  367. validators := types.TM2PB.Validators(state.Validators)
  368. proxyApp.Consensus().InitChainSync(validators)
  369. var latestAppHash []byte
  370. switch mode {
  371. case 0:
  372. // sync right up
  373. for _, block := range chain {
  374. applyBlock(state, block, proxyApp)
  375. }
  376. latestAppHash = state.AppHash
  377. case 1, 2:
  378. // sync up to the penultimate as if we stored the block.
  379. // whether we commit or not depends on the appHash
  380. for _, block := range chain[:len(chain)-1] {
  381. applyBlock(state, block, proxyApp)
  382. }
  383. // apply the final block to a state copy so we can
  384. // get the right next appHash but keep the state back
  385. stateCopy := state.Copy()
  386. applyBlock(stateCopy, chain[len(chain)-1], proxyApp)
  387. latestAppHash = stateCopy.AppHash
  388. }
  389. return latestAppHash
  390. }
  391. //--------------------------
  392. // utils for making blocks
  393. func makeBlockchainFromWAL(wal *WAL) ([]*types.Block, []*types.Commit, error) {
  394. // Search for height marker
  395. gr, found, err := wal.group.Search("#ENDHEIGHT: ", makeHeightSearchFunc(0))
  396. if err != nil {
  397. return nil, nil, err
  398. }
  399. if !found {
  400. return nil, nil, errors.New(cmn.Fmt("WAL does not contain height %d.", 1))
  401. }
  402. defer gr.Close()
  403. // log.Notice("Build a blockchain by reading from the WAL")
  404. var blockParts *types.PartSet
  405. var blocks []*types.Block
  406. var commits []*types.Commit
  407. for {
  408. line, err := gr.ReadLine()
  409. if err != nil {
  410. if err == io.EOF {
  411. break
  412. } else {
  413. return nil, nil, err
  414. }
  415. }
  416. piece, err := readPieceFromWAL([]byte(line))
  417. if err != nil {
  418. return nil, nil, err
  419. }
  420. if piece == nil {
  421. continue
  422. }
  423. switch p := piece.(type) {
  424. case *types.PartSetHeader:
  425. // if its not the first one, we have a full block
  426. if blockParts != nil {
  427. var n int
  428. block := wire.ReadBinary(&types.Block{}, blockParts.GetReader(), types.MaxBlockSize, &n, &err).(*types.Block)
  429. blocks = append(blocks, block)
  430. }
  431. blockParts = types.NewPartSetFromHeader(*p)
  432. case *types.Part:
  433. _, err := blockParts.AddPart(p, false)
  434. if err != nil {
  435. return nil, nil, err
  436. }
  437. case *types.Vote:
  438. if p.Type == types.VoteTypePrecommit {
  439. commit := &types.Commit{
  440. BlockID: p.BlockID,
  441. Precommits: []*types.Vote{p},
  442. }
  443. commits = append(commits, commit)
  444. }
  445. }
  446. }
  447. // grab the last block too
  448. var n int
  449. block := wire.ReadBinary(&types.Block{}, blockParts.GetReader(), types.MaxBlockSize, &n, &err).(*types.Block)
  450. blocks = append(blocks, block)
  451. return blocks, commits, nil
  452. }
  453. func readPieceFromWAL(msgBytes []byte) (interface{}, error) {
  454. // Skip over empty and meta lines
  455. if len(msgBytes) == 0 || msgBytes[0] == '#' {
  456. return nil, nil
  457. }
  458. var err error
  459. var msg TimedWALMessage
  460. wire.ReadJSON(&msg, msgBytes, &err)
  461. if err != nil {
  462. fmt.Println("MsgBytes:", msgBytes, string(msgBytes))
  463. return nil, fmt.Errorf("Error reading json data: %v", err)
  464. }
  465. // for logging
  466. switch m := msg.Msg.(type) {
  467. case msgInfo:
  468. switch msg := m.Msg.(type) {
  469. case *ProposalMessage:
  470. return &msg.Proposal.BlockPartsHeader, nil
  471. case *BlockPartMessage:
  472. return msg.Part, nil
  473. case *VoteMessage:
  474. return msg.Vote, nil
  475. }
  476. }
  477. return nil, nil
  478. }
  479. // fresh state and mock store
  480. func stateAndStore(config *cfg.Config, pubKey crypto.PubKey) (*sm.State, *mockBlockStore) {
  481. stateDB := dbm.NewMemDB()
  482. state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile())
  483. state.SetLogger(log.TestingLogger().With("module", "state"))
  484. store := NewMockBlockStore(config)
  485. return state, store
  486. }
  487. //----------------------------------
  488. // mock block store
  489. type mockBlockStore struct {
  490. config *cfg.Config
  491. chain []*types.Block
  492. commits []*types.Commit
  493. }
  494. // TODO: NewBlockStore(db.NewMemDB) ...
  495. func NewMockBlockStore(config *cfg.Config) *mockBlockStore {
  496. return &mockBlockStore{config, nil, nil}
  497. }
  498. func (bs *mockBlockStore) Height() int { return len(bs.chain) }
  499. func (bs *mockBlockStore) LoadBlock(height int) *types.Block { return bs.chain[height-1] }
  500. func (bs *mockBlockStore) LoadBlockMeta(height int) *types.BlockMeta {
  501. block := bs.chain[height-1]
  502. return &types.BlockMeta{
  503. BlockID: types.BlockID{block.Hash(), block.MakePartSet(bs.config.Consensus.BlockPartSize).Header()},
  504. Header: block.Header,
  505. }
  506. }
  507. func (bs *mockBlockStore) LoadBlockPart(height int, index int) *types.Part { return nil }
  508. func (bs *mockBlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) {
  509. }
  510. func (bs *mockBlockStore) LoadBlockCommit(height int) *types.Commit {
  511. return bs.commits[height-1]
  512. }
  513. func (bs *mockBlockStore) LoadSeenCommit(height int) *types.Commit {
  514. return bs.commits[height-1]
  515. }